0

I'm new on Android and I'm trying to connect my android application to my local server phpmyadmin. I've seen some tutorial about the interaction Android-MySql through PHP pages (using JSON), but I have a problem with the output (how do I convert what I obtained from JSON to String, for example?). To make you better understand the problem, this is my code:

JSONParser.java

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

This is my PHP file "get_product.php" (the DB connection works fine):

<?php

$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();

if (isset($_GET["ID"])) {
$ID_work = $_GET['ID'];

$result = mysql_query("SELECT * FROM PRODUCTS WHERE ID = $ID");

if (!empty($result)) {
    if (mysql_num_rows($result) > 0) {

        $result = mysql_fetch_array($result);

        $product = array();
        $product["ID"] = $result["ID"];
        $product["title"] = $result["title"];
        $product["description"] = $result["description"];

        // success
        $response["success"] = 1;

        // user node
        $response["product"] = array();

        array_push($response["product"], $product);

        // echoing JSON response
        echo json_encode($response);
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No product found";

    // echo no users JSON
    echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

echo json_encode($response);
}

?>

In the Manifest I insert internet permissions and now, in my activity I insert:

private static String url = "http://IP_ADDRESS/connect/get_product.php";

But now how can I save title and description obtained in a String?

Thank you very much indeed for your help!

@Sajmon: This is the LogCat

05-13 19:53:32.322: E/JSON Parser(10336): Error parsing data org.json.JSONException: Value <HTML><HEAD><TITLE> of type java.lang.String cannot be converted to JSONObject
05-13 19:53:32.322: D/AndroidRuntime(10336): Shutting down VM
05-13 19:53:32.322: W/dalvikvm(10336): threadid=1: thread exiting with uncaught exception (group=0x4001d578)
05-13 19:53:32.332: E/AndroidRuntime(10336): FATAL EXCEPTION: main
05-13 19:53:32.332: E/AndroidRuntime(10336): java.lang.RuntimeException: Unable to start activity ComponentInfo{package/package.MyActivity}: java.lang.NullPointerException
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.app.ActivityThread.access$1500(ActivityThread.java:121)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.os.Looper.loop(Looper.java:138)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.app.ActivityThread.main(ActivityThread.java:3701)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at java.lang.reflect.Method.invokeNative(Native Method)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at java.lang.reflect.Method.invoke(Method.java:507)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at dalvik.system.NativeStart.main(Native Method)
05-13 19:53:32.332: E/AndroidRuntime(10336): Caused by: java.lang.NullPointerException
05-13 19:53:32.332: E/AndroidRuntime(10336):    at package.MyActivity.onCreate(MyActivity.java:158)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-13 19:53:32.332: E/AndroidRuntime(10336):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
05-13 19:53:32.332: E/AndroidRuntime(10336):    ... 11 more

and the line 158 is:

String title = obj.getString("title");
2
  • where you facing problem? First get the json and then parse it Commented May 13, 2013 at 16:48
  • On PHP side make sure you prevent sql injection. Use mysql_real_escape_string everywhere you use $_GET or $_POST etc to get a variable you are going to use in a SQL statement. Commented May 13, 2013 at 18:22

1 Answer 1

1

So you almost got it. Actually your makeHttpRequest() method returns JSONObject returned from PHP script.

Now you only need to parse your JSON and retrieve and save values from it.

Here is solution as pseudo-code:

JSONParser parser = new JSONParser();
JSONObject obj = parser.makeHttpRequest("GET", <url>, <params>);
// getting data from JSON
String title = obj.getString("title");
String decription = obj.getString("description");
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your help! I try as follow, but the application in my device crashes.. Where am I doing wrong? (sorry for formatting..)
public class A extends Activity { .. String ID; private static String url = "..."; JSONParser parser = new JSONParser(); private static final String TAG_ID = "ID"; public void onCreate(Bundle s) { ... try { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ID", ID)); JSONObject obj = parser.makeHttpRequest(url, "GET", params); String title = obj.getString("title"); String description = obj.getString("description"); } catch (JSONException e) { e.printStackTrace(); } } .. }
@kareth add to your question your full logcat.
Thank you, I've posted the logcat!
@kareth you don't have valid JSON, look at logcat, you are getting at first JSONException that probably then result in NullPointerException.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.