I am getting a exception while working in json . My JSONPresr class is as follow
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println(" value in json sting"+json);
} 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());
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
System.out.println(" error is here");
}
// return JSON String
return jObj;
}
}
I am getting my data by these code
String TAG_user_detail = "user_details";
String TAG_user_id = "user_id";
String TAG_user_name = "user_name";
String TAG_user_phone = "user_phone";
String TAG_ref_id = "ref_id";
JSONArray user_detail_jsonarray = null;
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
user_detail_jsonarray = json.getJSONArray(TAG_user_detail);
// looping through All Contacts
for(int i = 0; i < user_detail_jsonarray.length(); i++){
JSONObject c = user_detail_jsonarray.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt(TAG_user_id);
System.out.println("user id from json"+id);
String name_fromjson = c.getString(TAG_user_name);
System.out.println("user name from json"+name_fromjson);
int phone_no_fromjson = c.getInt(TAG_user_phone);
System.out.println("user phone from json"+phone_no_fromjson);
int ref_id_fromjson = c.getInt(TAG_ref_id);
System.out.println("user ref id from json"+ref_id_fromjson);
}
} catch (JSONException e) {
e.printStackTrace();
}
But i am countiniously getting Exception in this line
user_detail_jsonarray = json.getJSONArray(TAG_user_detail);
My Stake Trace message is as
{"ref_id":1295,"user_name":"chand","user_phone":"9620085675","user_id":"1"} at user_details of type org.json.JSONObject cannot be converted to JSONArray
I tried many link but unfortunately i am not able to get my result. Please any body just help me to solve this issue. Thanks in advance to all
Its clear from error that you are trying to convert Json Object into Json array. That should not.
Here is the code to read your JSON response.
String json = "Assuming that here is your JSON response";
try {
JSONObject parentObject = new JSONObject(json);
JSONObject userDetails = parentObject.getJSONObject("user_details");
//And then read attributes like
String name = userDetails.getString("user_name");
String phone = userDetails.getString("user_phone");
String id = userDetails.getString("ref_id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above code is for {"user_details":{"user_id":"1","user_name":"chand","user_phone":"9620085675","ref_id":6386}} JSON.
Learn from exception
org.json.JSONObject cannot be converted to JSONArray
You are getting this exception org.json.JSONObject cannot be converted to JSONArray
because you are trying to convert JSONObject to JSONArray which is not possible.
{ represents json object node
[ represents json array node
your jsondata is json object format. change this line
JsonObject user_detail_jsonobj = json.getJSONObject(TAG_user_detail);
Related
I tried to parse some strings from this JSON-site:
I wrote this code with asynctask:
package com.example.nortti.jsonexample;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
TextView txView;
//URL to get JSON Array
private static String url = "http://localhost:10101/api/stats/1";
//JSON Node Names
private static final String TAG_USER = "";
private static final String TAG_NAME = "PersonName";
private static final String TAG_EMAIL = "Rank";
JSONArray user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
user = null;
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
txView = (TextView)findViewById(R.id.txView);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
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(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray("ArrayOfCommonStatViewModel");
Toast.makeText(getApplication(),user.toString(),Toast.LENGTH_SHORT).show();
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
txView.setText(name+" " +email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And I have another class like:
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(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;
}
}
But it says that I have a NullPointerException
I want to get a JSONArray to get information and put it into a ListView.
UPD: Here is JSON screenshot
UPD2: full log
12-17 14:17:03.712 20308-20308/com.example.nortti.politrange E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nortti.politrange, PID: 20308
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:102)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:373)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:225)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:178)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at com.example.nortti.politrange.utils.WebApiAdapter.select(WebApiAdapter.java:33)
at com.example.nortti.politrange.intefaces.impls.PersonCatalog.populateData(PersonCatalog.java:37)
at com.example.nortti.politrange.views.GeneralFragment.listData(GeneralFragment.java:65)
at com.example.nortti.politrange.views.GeneralFragment.onClick(GeneralFragment.java:88)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
you are getting a NetworkOnMainThread exception because you are implementing a network operation in a UI thread so for loading the json data from your localhost you need to implement a seperate thread for it
You are getting NetworkOrMainThreadException.
Put below code on onCreate():
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Hope this will help you.
You are trying to parse an XML document with a JSON Parser, it won't work. Let's take a look on this link , it will show you how to parse an XML document (in Android environment) on a proper way:
The content that you are trying to parse is actually xml not JSON. If you need to do network requests, parse the JSON, you can use Retrofit library. It is very simple and hassle-free. Here is a nice tutorial for the same. Hope it helps.
instead of developping the whole parsing code, try to use the Volley library of Google, it's an asynchrone library for parsing JSON.
here is a good tutorial.
enter code here
////In android studio add http client and http core libs/////
class mytask extends AsyncTask {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "http://192.168.1.13/mywebservice/getbook.php";
json = getJSONFromUrl(url);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(ctx, json, Toast.LENGTH_LONG).show();
parser_01();
}
}
// from url to json object starts.......................................
public String 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");
sb.append(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
// from url to json object Ends.......................................
public void parser_01() {
try {
String jstring = json;
JSONObject jobject = new JSONObject(jstring);
JSONArray bookarray = jobject.getJSONArray("data");
for (int i = 0; i < bookarray.length(); i++) {
String isdn = bookarray.getJSONObject(i).getString("isdn") + "";
String title = bookarray.getJSONObject(i).getString("title") + "";
String author = bookarray.getJSONObject(i).getString("author") + "";
String price = bookarray.getJSONObject(i).getString("price") + "";
}
} catch (Exception e) {
// TODO: handle exception
}
}
I am currently learning how to create apps on Android Studio and have been trying to make a JSON connection with a server and bring back the information from the server and display it in my app. I have been able to make the connection as logical shows however I am unclear of the error that faces me and how to solve it. I will show here my two classes I have constructed to make the JSON connection and the error I am shown. When I run the emulator it just says, Unfotunatley, JSONconnection app has stopped working.
Thanks for the help
Error on logcat with exception
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection E/JSON Parser﹕ Error parsing data org.json.JSONException: Value [{"id":"170656","RatingValue":"5","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Cheeky Coffee Co","Longitude":"-2.240435","RatingDate":"2014-02-06","AddressLine1":"Unit 10, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"171710","RatingValue":"3","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Nando's","Longitude":"-2.240435","RatingDate":"2013-01-17","AddressLine1":"Unit 3, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"172780","RatingValue":"4","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Zouk Tea Bar & Grill","Longitude":"-2.240435","RatingDate":"2010-06-11","AddressLine1":"Unit 5 The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"170593","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Caffe Nero","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"8A Oxford Road","AddressLine3":"Manchester"},{"id":"171089","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Greggs","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"10 Oxford Road","AddressLine3":"Manchester"},{"id":"171185","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Holiday Inn Express","Longitude":"-2.23997","RatingDate":"2011-03-17","AddressLine1":"","AddressLine2":"2-4 Oxford Road","AddressLine3":"Manchester"},{"id":"171382","RatingValue":"1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Kukoos","Longitude":"-2.23997","RatingDate":"2013-11-18","AddressLine1":"","AddressLine2":"12a Oxford Road","AddressLine3":"Manchester"},{"id":"171404","RatingValue":"-1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Ladbrokes","Longitude":"-2.23997","RatingDate":"2010-11-09","AddressLine1":"","AddressLine2":"10B Oxford Road","AddressLine3":"Manchester"},{"id":"172281","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Subway","Longitude":"-2.23997","RatingDate":"2013-10-09","AddressLine1":"","AddressLine2":"12 Oxford Road","AddressLine3":"Manchester"},{"id":"171119","RatingValue":"5","DistanceKM":"0.100210503082758","PostCode":"M1 5GE","Latitude":"53.47208","BusinessName":"H & M Convenience Store","Longitude":"-2.241442","RatingDate":"2010-09-16","AddressLine1":"Student Village","AddressLine2":"Lower Chatham Street","AddressLine3":"Manchester"}] of type org.json.JSONArray cannot be converted to JSONObject
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection D/AndroidRuntime﹕ Shutting down VM
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb2cbdb20)
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.adam.jsonconnection, PID: 1656
JSONParser Class
package com.example.adam.jsonconnection;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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;
}
}
MainActivity Class
package com.example.adam.jsonconnection;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
//URL to get JSON Array
private static String url = "";
//JSON Node Names
private static final String TAG_NEAREST = "nearest";
private static final String TAG_BusinessName = "BusinessName";
JSONArray nearest = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
nearest = json.getJSONArray(TAG_NEAREST);
JSONObject c = nearest.getJSONObject(0);
// Storing JSON item in a Variable
String businessName = c.getString(TAG_BusinessName);
//Importing TextView
final TextView BusinessNameText = (TextView)findViewById(R.id.BusinessName);
//Set JSON Data in TextView
BusinessNameText.setText(businessName);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You have a JSONArray and you're attempting to create a JSONObject object with it.
Simple change your code to:
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Or edit your response so that it is a json object.
Your JSON is an Array from root, so you must change from:
JSONObject json = jParser.getJSONFromUrl(url);
to
JSONArray json = jParser.getJSONFromUrl(url);
and return a JSONArray from getJSONFromUrl
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
I suggest you to use:
jsonObject.optString("your_key");
instead of:
jsonObject.getString("your_key");
this will automatically handle possible "null" values
I am having issues with my attempt to connect via JSON to a PHP file to access MySQL in android. I cannot for the life of me figure out why this is causing my app to crash. Any ideas?
It is throwing the following error:
AndroidRuntime
FATAL EXCEPTION: main
I am attemping to call this from my main activity:
new getData().getMovie();
Which calls this:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.*;
import org.json.*;
import android.util.Log;
import android.widget.Toast;
public class getData extends FullscreenActivity{
public void getMovie() {
String result = "";
String rID="1";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ids",rID));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/myphp.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch(Exception e){
Toast.makeText(this, "Error in http connection "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
InputStream is = null;
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){
Toast.makeText(this, "Error converting result "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", 1: "+json_data.getString("1")+
", 2: "+json_data.getString("2")+
", 3: "+json_data.getString("3")+
", 4: "+json_data.getString("4")+
", 5: "+json_data.getString("5")
);
}
} catch (JSONException e) {
Toast.makeText(this, "Error parsing data "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
First, make sure your app requests the INTERNET permission. More on that here. Second, you can significantly declutter your code using the droidQuery library:
public void getMovie() {
$.ajax(new AjaxOptions().url("http://website.com/myphp.php")
.type("POST")
.dataType("JSON")
.data("{ids: 1}")
.context(this)
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
JSONArray json = (JSONArray) params[0];
Object[] datas = $.makeArray(json);
for (Object data : datas) {
JSONObject obj = (JSONObject) data;
Map<String, ?> map = $.map(obj);
Log.i("log_tag", map.toString());//will print all JSON Objects in a Key-Value format, such as "{1, 'text'}"
}
}
})
.error(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
String reason = (String) params[2];
droidQuery.toast("Error in Ajax Request: " + reason, Toast.LENGTH_LONG);
}
}));
}
Thirdly, if you are still getting error, surround your call to getMovie() in a try-catch block, catching a Throwable instead of an Exception:
try {
new getData().getMovie();
}
catch (Throwable t) {
t.printStackTrace();
}
I created a json result in mvc and I'm building an Android app to get the json result. This is what my json result looks like
{"name":"Mr. Spock","gender":"Male"}
This is my controller
public ActionResult Index()
{
var result = new { name = "Mr. Spock", gender = "Male" };
return Json(result, JsonRequestBehavior.AllowGet);
}
And this I'm using in android
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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;
}
}
I have a declared variable url. Every time I debug, the json variable does not have any values and says "errors during the evaluation"
Anyone with a tip? I tried working with Gson, but no succes
Kind regards
I'll give you some code for Gson. It really is much easier to work with than the built in JSON parsing code. Here's a minimal example using your JSON.
Person.class:
package com.example.tutorial.models;
import com.google.gson.annotations.SerializedName;
public class Person {
#SerializedName("gender")
public String gender = "";
#SerializedName("name")
public String name = "";
}
The annotations are really only necessary when your variable and JSON name differ, but I tend to always include them as it reinforces that they are coming from JSON.
To deserialize:
Gson gson = new GsonBuilder().create();
Person person = gson.fromJson(json, Person.class);
It really is that simple. If this does not work, log the result from the web server and make sure it really is the valid JSON string you expect it to be.
I do have one question, where is your AsyncTask? Your attempt to open a connection to the webserver in the UI thread will definitely cause a NetworkOnMainThreadException. I created a library to do RESTful calls on Android. It's licensed under BSD, so feel free to use it as a guide or outright use it: https://github.com/nedwidek/Android-Rest-API
Trying to get the json from http request by using this class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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;
}
}
But some times getting the exception like
E/Buffer Error(300): Error converting result java.io.IOException: Attempted read on closed stream.
Can any one help on this thanks in advance.
try like this way..
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet("https://somejson.json");
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
thanks i changed the code to this:Now its double faster than before.
But i need to test more number of times since i was getting the exception which i posted as question very rarely.
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet(url);
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
json = EntityUtils.toString(entity);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
It was faster than before ,But problem is app crashing when its the network connection is slow.
I suggest removing the static. With me it worked after the removal.
static InputStream is = null;
At first i really don't like your static InputStream variable, why static? Just make it normal variable and not static. And especially in Android static variables are not a win at all.
And second if you want to get JSON from Server you need to use GET request instead of POST
And to question.
I think problem is that you should close BufferedReader rather than InputStream
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
// next work
And at the end one suggestion. What about to use EntityUtils instead of getContent(). You will save a time by it instead of reading from InputStream.
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity);
and now you have quickly JSON as String.
just make InputStream non-static that's all.
I used post method and just fine...