I'm trying to retrieve data back from my database as JSON, and set that result to a JSONObject which then displays in a textview.
Here is the code:
private class ShowDBActivity3 extends AsyncTask<Void, Void, String>{
protected String doInBackground(Void... voids){
String s = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("URL");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
Log.e("This is the result: ", result.toString());
JSONObject jArray = new JSONObject(result);
String title = jArray.getString("title");
String rating = jArray.getString("rating");
String username = jArray.getString("username");
s = "Movie: " + title + "\n" +
"Rating: " + rating + "\n";
return s;
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
return s;
}
protected void onPostExecute(String s){
show.setText(s);
}
}
And here is the result that gets returned:
This is the result:﹕ [{"0":"16","id":"16","1":"The Hulk","title":"The Hulk","2":"7","rating":"7","3":"tlong3","username":"tlong3"},{"0":"19","id":"19","1":"The Incredible Hulk","title":"The Incredible Hulk","2":"3","rating":"3","3":"tlong3","username":"tlong3"},{"0":"20","id":"20","1":"Testtt","title":"Testtt","2":"6","rating":"6","3":"Tlong3","username":"Tlong3"}]
...which cannot be converted to a JSONObject for some reason. Here is the error:
04-28 13:14:25.372 20099-20830/com.android.movies E/Fail 3﹕ org.json.JSONException: Value [{"3":"tlong3","id":"16","2":"7","username":"tlong3","title":"The Hulk","1":"The Hulk","0":"16","rating":"7"},{"3":"tlong3","id":"19","2":"3","username":"tlong3","title":"The Incredible Hulk","1":"The Incredible Hulk","0":"19","rating":"3"},{"3":"Tlong3","id":"20","2":"6","username":"Tlong3","title":"Testtt","1":"Testtt","0":"20","rating":"6"}] of type org.json.JSONArray cannot be converted to JSONObject