Reputation:
I'm fetching data through JSON-Parsing
, but getting "NullPointerException" and Error A JSONArray text must start with '[' at character 1 of {
. following is what I have tried so far :
/** Method for returning JSONObject */
protected JSONObject lastTweet() {
try {
HttpGet request = new HttpGet("http://api.androidhive.info/contacts/");
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonArray = new JSONArray(data);
JSONObject lastT = jsonArray.getJSONObject(0);
return (lastT);
} else {
Log.e(MY_TAG, "Error");
return null;
}
} catch (ClientProtocolException e) {
Log.e(MY_TAG, "Error " + e.getMessage());
return null;
} catch (IOException e) {
Log.e(MY_TAG, "Error " + e.getMessage());
return null;
} catch (JSONException e) {
Log.e(MY_TAG, "Error " + e.getMessage());
return null;
}
}
Now when I actually make this code work for me is following :
new AsyncTask<String, Integer, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("Please wait..");
dialog.setMessage("Data is being loaded");
dialog.show();
}
@Override
protected String doInBackground(String... params) { // TODO
try {
jsonObject = lastTweet();
return jsonObject.getString("name");
} catch (JSONException e) {
return null;
}
}
@Override
protected void onPostExecute(String result) { // TODO
super.onPostExecute(result);
textView.setText(result);
dialog.dismiss();
}
}.execute(null, null, null);
that gives me the following LogCat
:
How to solve that issue?
Upvotes: 0
Views: 101
Reputation: 15533
Json you are retriewing is not a JSONArray, it is a JSONObject
Change this:
JSONArray jsonArray = new JSONArray(data);
To this:
JSONObject jsonObject = new JSONObject (data);
JSONArray contactsJsonArray = jsonObject.getJSONArray("contacts");
// TODO: loop over contactsJsonArray
JSONObject contactJsonObject = contactsJsonArray.getJSONObject(0);
String nameOfAContact = contactJsonObject.getString("name");
Upvotes: 0
Reputation: 1265
you are storing json object in json array
use this:: JSONObject jsonObject = new JSONObject (data);
Upvotes: 1
Reputation: 3373
You're casting a JSONObject
as a JSONArray
.
Change this
JSONArray jsonArray = new JSONArray(data);
to this
JSONArray jsonArray = new JSONObject(data).getJSONArray("contacts");
Upvotes: 0
Reputation: 6120
JSON should start and end with { and }, are you sure your json is
{"contacts":[{},{}]}
and not only
"contacts":[{},{}]
Upvotes: 0
Reputation: 3522
The error contains the solution:
A JSONArray text must start with '['
Check if the response starts with a [
rather than a {
.
If it is true you are receiving a JSONObject, and not a JSONArray.
Upvotes: 1