1

Currently my PHP file that is used to interface between the MySQL server and my Android app looks like:

<?php
// array for JSON response
$response = array();

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

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // get all products from products table
    $result = mysql_query("SELECT * FROM profiles_profilelists WHERE ProfileID = '$ID'") or die(mysql_error());

    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
        $response["lists"] = array();

        while ($row = mysql_fetch_array($result)) {
        // temp user array
        $lists = array();
        $lists["ProfileListID"] = $row["ProfileListID"];
        $lists["ProfileListName"] = $row["ProfileListName"];

        // push single product into final response array
        array_push($response["lists"], $lists);
        }
        // success
        $response["success"] = 1;

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

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

    // echoing JSON response
    echo json_encode($response);
}
?>

This works fine however when I add:

$result2 = mysql_query("SELECT * FROM profiles_profilelistitems WHERE ProfileListID = ".$row["ProfileListName"]) or die(mysql_error());

$lists["ListCount"] = mysql_num_rows($result2);

To my Php so it looks like:

<?php


// array for JSON response
$response = array();

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

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // get all products from products table
    $result = mysql_query("SELECT * FROM profiles_profilelists WHERE ProfileID = '$ID'") or die(mysql_error());

    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
        $response["lists"] = array();

        while ($row = mysql_fetch_array($result)) {
        // temp user array
        $lists = array();
        $lists["ProfileListID"] = $row["ProfileListID"];
        $lists["ProfileListName"] = $row["ProfileListName"];

        $result2 = mysql_query("SELECT * FROM profiles_profilelistitems WHERE ProfileListID = ".$row["ProfileListName"]) or die(mysql_error());

        $lists["ListCount"] = mysql_num_rows($result2);

        // push single product into final response array
        array_push($response["lists"], $lists);
        }
        // success
        $response["success"] = 1;

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

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

    // echoing JSON response
    echo json_encode($response);
}
?>

I end up with the above error. The complete trace is:

09-03 17:05:57.836: E/JSON Parser(675): Error parsing data org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject
09-03 17:05:59.617: E/AndroidRuntime(675): FATAL EXCEPTION: AsyncTask #1
09-03 17:05:59.617: E/AndroidRuntime(675): java.lang.RuntimeException: An error occured while executing doInBackground()
09-03 17:05:59.617: E/AndroidRuntime(675):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-03 17:05:59.617: E/AndroidRuntime(675):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.lang.Thread.run(Thread.java:856)
09-03 17:05:59.617: E/AndroidRuntime(675): Caused by: java.lang.NullPointerException
09-03 17:05:59.617: E/AndroidRuntime(675):  at com.test.app.MyLists$LoadAllLists.doInBackground(MyLists.java:267)
09-03 17:05:59.617: E/AndroidRuntime(675):  at com.test.app.MyLists$LoadAllLists.doInBackground(MyLists.java:1)
09-03 17:05:59.617: E/AndroidRuntime(675):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-03 17:05:59.617: E/AndroidRuntime(675):  ... 5 more

The code that the trace links to from within the app:

protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("porfileID", Integer.toString(userID)));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray("lists");
                    productsList.clear();
                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString("ProfileListID");
                        String name = c.getString("ProfileListName");
                        //String count = c.getString("ListCount");
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put("ProfileListID", id);
                        map.put("ProfileListName", name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

And finally the json parser I am using

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;

    }
}
4
  • Have you tried looking at the format of the JSON object being returned by php to see if it is correct? Commented Sep 3, 2013 at 18:44
  • @E.Odebugg the odd thing is it works fine before I add the two other lines to the PHP surely this is not changing the format? or am I wrong Commented Sep 3, 2013 at 18:46
  • I think it might since you are adding it to the response array... you can look at the response you get on the Android side and use a JSON verifier (jsonlint.com) to check there are not formatting issues Commented Sep 3, 2013 at 18:53
  • please post your json string response Commented Sep 3, 2013 at 19:23

2 Answers 2

1

If you are getting error only after introducing the PHP line then you may have error in the query itself. Try dumping the query to get more insights.

SELECT * FROM profiles_profilelistitems WHERE ProfileListID = ".$row["ProfileListName"]

should be

SELECT * FROM profiles_profilelistitems WHERE ProfileListID = '".$row["ProfileListName"]."'"
Sign up to request clarification or add additional context in comments.

Comments

0

Problem is in php only , rewrite query or check php . I have also faced same problem , and problem is not in android or anything , it is in php only , and usually in the query . If query seems correct then also rewrite query once .

Comments

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.