0

I am trying to get data from a mySQL database using PHP. This is my fist real attempt of getting data remotely & using JSON. The php file is functioning correctly because it outputs in a browser as a JSON string and i valadated it using JSONLint. So, I am not sure what I have wrong here. Any help would be greatly appreciated

This is what LogCat is throwing:

Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
threadid=9: thread exiting with uncaught exception (group=0x401dce20)
FATAL EXCEPTION: Thread-10
java.lang.NullPointerException
at com.andaero.test.JSON.JSONMain$1.run(JSONMain.java:39)
at java.lang.Thread.run(Thread.java:1020)

UPDATE: I removed the echo method from the php file as Mark requested. I think it has to do with "JSONArray a = json.getJSONArray("regulatory"). I also tried everyone else's approach with no prevail.

Here are the classes:

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "regulatory";
        JSONObject jArray = null;

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        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();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

The List Activity:

public class JSONMain extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);

        final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        new Thread(new Runnable() {
            public void run() {
                JSONObject json = JSONfunctions
                        .getJSONfromURL("http://192.168.1.34/andaero/regulatory_list_ASC.php");

                try {

                    JSONArray a = json.getJSONArray("regulatory");

                    for (int i = 0; i < a.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject e = a.getJSONObject(i);

                        map.put("id", String.valueOf(i));
                        map.put("label", e.getString("label"));
                        map.put("title", e.getString("title"));
                        map.put("caption", e.getString("description"));
                        map.put("dummy", e.getString("gotoURL"));
                        mylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("log_tag", "Error parsing data " + e.toString());
                }
            }
        }).start();

        ListAdapter adapter = new SimpleAdapter(this, mylist,
                R.layout.list_item, new String[] { "label", "title", "caption",
                        "dummy" }, new int[] { R.id.label, R.id.listTitle,
                        R.id.caption, R.id.dummy });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv
                        .getItemAtPosition(position);
                Toast.makeText(JSONMain.this,
                        "ID '" + o.get("id") + "' was clicked.",
                        Toast.LENGTH_SHORT).show();

            }
        });
    }
} 

EDITED: The PHP:

    <?php
//MySQL Database Connect
include 'andaerologin.php';

mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");

$output = new stdClass();
$output->regulatory = array();
while($row = mysql_fetch_assoc($sql)) {
    $output->regulatory[] = $row;
}

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo (json_encode($output));

mysql_close();
?>

The JSON returned data **(in-part - The data is confidential & JSON has been validated as per above!!)

[
{
_id: "**",
label: "**",
title: "**",
description: "**",
date: "**",
gotoURL: null,
intent: "QueryDisplay"
}, * additional rows.....>
]
}
  • it will be very helpful to see the JSON part. The chars ` – Rafael T Jan 31 '12 at 22:43
  • @Rafael I added the returned JSON data. Please keep in mind that JSON was validated as per my question. Thnx. –  Jan 31 '12 at 23:03
  • It is your web server and it gives you GARBAGE. I've tested your method to retrieve json and it's working fine. I even created the php you have to make the json out of mysql. Everything works perfect. You have to fix your server first. Otherwise I can throw you the URL I used for the json and you can test it. – Sergey Benner Feb 01 '12 at 13:25
  • 1
    check this link for correct mime types http://stackoverflow.com/questions/477816/the-right-json-content-type – Sergey Benner Feb 01 '12 at 14:55
  • @Sergey Benner I think you maybe right. I changed he php file (see above) and I cant find what is wrong with the server. I also ran it off another server on the network but I still get the same error. The only variable that is the same is each server is XAMPP v3.0.2. I dont now were to look to see where the problem resides.??? Again the returned array is validated. –  Feb 01 '12 at 19:32
  • test your json by assigning it to your result string and see if it will work. just going straight. instead of `result = sb.toString();` set `result="yourjsonhere";` and run the application. – Sergey Benner Feb 01 '12 at 21:11

1 Answers1

0

It is obvious that you're trying to parse and recieve Value <?xml of type java.lang.String and not JSON data there

Sergey Benner
  • 4,421
  • 2
  • 22
  • 29
  • Ive been told that ( –  Jan 31 '12 at 23:07
  • in the first place have you looked in the debugger at this loop `while ((line = reader.readLine()) != null) { sb.append(line + "\n"); }` what does it return to you? the line itself? – Sergey Benner Jan 31 '12 at 23:09
  • The debugger is not pointing at that line. Could you please say why that is calling XML and what would be the correct replacement. Thank you again for your input. –  Jan 31 '12 at 23:20
  • I mean what you get with your call result = sb.toString(); what is the result string there? clear string? have you looked at it? what does your browser return? like if you click on the source of the called URL? does it return you the clear json? – Sergey Benner Jan 31 '12 at 23:26
  • I have written a sample the other day which is working http://stackoverflow.com/questions/9066684/android-to-mysql-thru-php – Sergey Benner Jan 31 '12 at 23:29
  • Yes I get a JSON string returned when I open the php in the browser. Again it is validated aswell with JSONView and JSONLint. I added the line `sb.append(reader.readLine() + "\n"); String line="0";` that was inyour post because that was to onlything different - same error pointing to line 38 in the JSONMan class??? –  Jan 31 '12 at 23:39
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/7218/discussion-between-andaero-and-sergey-benner) –  Jan 31 '12 at 23:42