Reputation: 11
I have this piece of code here which I have grabbed from http://mobilesiri.com/json-parsing-in-android-using-android-studio/ and modified it to my own use.
public String makeWebServiceCall(String addr, int requestMethod) {
URL url;
String response = "";
try {
url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestMethod == Constant.GET) {
conn.setRequestMethod("GET");
} else if (requestMethod == Constant.DELETE) {
conn.setRequestMethod("DELETE");
}
int reqResponseCode = conn.getResponseCode();
if ((requestMethod == Constant.GET || requestMethod == Constant.DELETE) && reqResponseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (MalformedURLException murle) {
Log.e(MalformedURLException.class.getName(), murle.getMessage());
} catch (IOException ioe) {
Log.e(IOException.class.getName(), ioe.getMessage());
}
return response;
}
Put this in a normal Java environment, along with the libraries, I'm able to get the output in this form
{"status":"FOUND","data":[{"category_id":3,"category_name":"Experience Sharing Area"},{"category_id":4,"category_name":"Frequently Asked Questions"},{"category_id":1,"category_name":"General Pain Advice"},{"category_id":2,"category_name":"Pain Categorization Section"}]}
Put this in Android to parse data, I get the JSONException - org.json.JSONException: End of input at character 0 of
Here is where I implement it.
protected Void doInBackground(Void... voids) {
WebRequest webReq = new WebRequest();
String jsonStr = webReq.makeWebServiceCall(Constant.WEB_SERVER_ADDR + Constant.GET_CATEGORY, Constant.GET);
Log.d("URL:", Constant.WEB_SERVER_ADDR + Constant.GET_CATEGORY);
Log.d("Response:", " > " + jsonStr);
categoryList = parseJSON(jsonStr);
return null;
}
Is there any issues with this?
Upvotes: 0
Views: 103
Reputation: 75788
You are getting JSONException: End of input at character 0.
Post your parseJSON Class .
{"status":"FOUND","data":[{"category_id":3,"category_name":"Experience Sharing Area"},{"category_id":4,"category_name":"Frequently Asked Questions"},{"category_id":1,"category_name":"General Pain Advice"},{"category_id":2,"category_name":"Pain Categorization Section"}]}
Your Parsing will be
try {
JSONObject reader = new JSONObject("YOUR_JSON_STRING");
JSONArray jsonArray = reader.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonItem = jsonArray.getJSONObject(i);
try {
jsonItem = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
String cate_id= jsonItem.getString("category_id");
String category_name= jsonItem.getString("category_name");
}
// Add adapter
} catch (JSONException e) {
e.printStackTrace();
}
}
Upvotes: 1