Original Question -
I was following a tutorial on json in android, but having problem to get json value using Async in android. First I created jsonparser class and added following to it -
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
Then to use this in fragment by async i tried -
class getTopicId extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Topic of the Day ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl("http://medicalguru.in/android/tod.php");
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
topic_id = json.getInt("value");
}
catch (JSONException e) {
e.printStackTrace();
}
finally {
Toast.makeText(getActivity(), "topic id -"+topic_id, Toast.LENGTH_LONG).show();
}
}
}
but the app is crashing when i execute this async. my logcat shows -
03-06 15:07:03.123: E/AndroidRuntime(2041): FATAL EXCEPTION: main
03-06 15:07:03.123: E/AndroidRuntime(2041): java.lang.NullPointerException
03-06 15:07:03.123: E/AndroidRuntime(2041): at in.medicalguru.DailyTestFragment$getTopicId.onPostExecute(DailyTestFragment.java:786)
03-06 15:07:03.123: E/AndroidRuntime(2041): at in.medicalguru.DailyTestFragment$getTopicId.onPostExecute(DailyTestFragment.java:1)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.AsyncTask.finish(AsyncTask.java:631)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.Handler.dispatchMessage(Handler.java:99)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.Looper.loop(Looper.java:137)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-06 15:07:03.123: E/AndroidRuntime(2041): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 15:07:03.123: E/AndroidRuntime(2041): at java.lang.reflect.Method.invoke(Method.java:525)
03-06 15:07:03.123: E/AndroidRuntime(2041): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-06 15:07:03.123: E/AndroidRuntime(2041): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-06 15:07:03.123: E/AndroidRuntime(2041): at dalvik.system.NativeStart.main(Native Method)
The link mentioned above in the code outputs as -
{"value":1}
when opened normally, but when I run in async it says err related to nullpointer? Couldn't figure, where I am making mistake ?
Edit 1 : *tod.php* code (Since Matthew has pointed something which I dont understand, so it may be helpful)
<?php
$today = date("Ymd");
switch($today){
case 20140304 :
$tod["value"] = 24;
break;
case 20140305 :
$tod["value"] = 25;
break;
case 20140306 :
$tod["value"] = 1;
break;
default:
$tod["value"] = 1;
break;
}
echo json_encode($tod);
?>
Edit 2 : *Found the problem (fully for me) but Partly in Real* - A special thanks to Matthew for his idea, to uncomment the error logs of function getJSONFromUrl(String url). I got a new error line in logcat -
Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject
After little bit of search on google and stacksoverflow I found one suggestion to change chrSet to UTF-8 instead of iso-8859-1. and it worked for my requested url in both situations (with or without WWW - suggestion to test, by nikis). But this answer is partial real, because, now 2 unanswered questions developed - 1. Why did chrSet change worked? In future, what chrSet to be used, to avoid this problem, and what's the use of other one chrSet? 2. Matthew has replicated my Json to his server mwesly.com/test/ . Trial on his server, logcat shows following error in all cases (with or without WWW, with or without using index.php in the end) -
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Now, why is this error appearing on his server? What should be done to prevent/treat this error. If I need to ask these updated questions separately, please let me know.