I am trying to parse JSON data and make that data available in listview on an Android app.
I receive the following error:
org.json.JSONException: No value for CarModelImage
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:510)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:212)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:162)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
07-21 14:03:48.252 25946-25946/com.example.justin.myapplication V/List parsed﹕ []
My code:
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = "";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "CarID";
private static final String TAG_MODELIMG = "CarModelImage";
JSONArray carid = null; //Initializes JSON array
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, String>>caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lv = getListView();
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
String model_img = ((ImageView) view.findViewById(R.id.model_img)).toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//getApplicationContext()
//sending data to new activity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
in.putExtra("TAG_MODELIMG", model_img);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, String>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
//Prints array in app
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String jsonString = jsonObj.getString(TAG_MODELIMG);
getBitmapFromString(jsonString);
String model_img = c.getString(TAG_MODELIMG);
Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, String> matchGetCars = new HashMap<String, String>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_MODELIMG, model_img);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
private Bitmap getBitmapFromString(String jsonString) {
byte[] decodedString = Base64.decode("CarModelImage", Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID, TAG_MODELIMG}, new int[]{R.id.car_id, R.id.model_img});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
}
I understand that the error is occurring around the following, but I do not understand where I went wrong:
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String jsonString = jsonObj.getString(TAG_MODELIMG);
getBitmapFromString(jsonString);
String model_img = c.getString(TAG_MODELIMG);
Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, String> matchGetCars = new HashMap<String, String>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_MODELIMG, model_img);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
A brief view of the JSON array:
{"cars":[{"id":1,"CarID":"20946","CarModelImage":"JDMQ.jpg".....so on...
I appreciate any insight as to why this is occurring. Thank you.
(P.S.: I realize that there are many similar posts and I have tried to apply their solutions with no luck.)
You're calling getString on jsonObj when you mean to call it on c.
Related
I want to parse below data but I got a errors when I try other url like this http://api.learn2crack.com/android/jsonos/ for the parsing json data I can parsing data,but when I try below code for the parsing I got a below error.
Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
android.view.WindowLeaked: Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at jsonparse.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at jsonparse.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
)
{
"AllUsersResult":[
{
"GroupID":null,
"ID":1,
"Password":"1234",
"Role":null,
"Username":"admin",
"customerID":null
}
]
}
MainActivity class
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://192.168.0.39:8090/TrackBinSvc.svc/AllUsers/admin/1234";
//JSON Node Names
private static final String TAG_OS = "AllUsersResult";
private static final String TAG_VER = "GroupID";
private static final String TAG_NAME = "Password";
private static final String TAG_API = "Username";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
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 from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
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 am suggest you parse data with volley library it is easy to use and also flexible ! Here is Tutorial link !
Hope this will helps you ! Cheers !
Change your JSONParse class to this..
private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
if(json!=null)
{
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
return oslist;
}
//else DATA Not Found or Server not connected
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result_list) {
if(pDialog!=null)
{
pDialog.dismiss();
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result_list,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+result_list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Hope this will help you.
I know that there are many posts about this particular error, but none of them are solving my issue and I am new to Android development. As a result of this error, I am unable to see the data in a listView for an app.
The following is my code:
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = "http://"";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "car_id";
JSONArray carid = null; //Initializes JSON array
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, String>>caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lv = getListView();
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//getApplicationContext()
//sending data to new activity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, String>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
//Prints array in app
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
//Hashmap for single match
HashMap<String, String> matchGetCars = new HashMap<String, String>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID}, new int[]{R.id.car_id});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
}
I realize that an error is occurring near the following:
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
//Hashmap for single match
HashMap<String, String> matchGetCars = new HashMap<String, String>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
Here is the logcat data:
org.json.JSONException: No value for car_id
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:510)
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:202)
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:155)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
07-20 15:31:30.455 7567-7567/com.example.justin.myapplication V/List parsed﹕ []
A brief view of what the JSON looks like:
{"cars":[{"id":1,"CarID":"20946"....so on...
I appreciate if any suggestions could be thoroughly explained and demonstrated as to why this error is occurring. Thank you greatly.
Replace
private static final String TAG_CARID = "car_id";
with
private static final String TAG_CARID = "CarID";
You JSONArray has key "CarID", whereas you are searching for "car_id".
Hope this helps :)
"cars" is jsonArray in the jsonObject. You must get the array first and then extract values from it. I cant give you code example right now, because I am currently on my phone.
I know there are many great explanations in StackOverFlow regarding this error. But I have spent countless hours trying to solve this error in my code but I couldn't. I am new to android programming. Hopefully you guys can help.
I am trying to store data in MySQL using PHP in this android app.
Here is my MainActivity
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Here is my JSONParser.java
public class JSONParser {
static InputStream is = null ;
static JSONObject jObj = null ;
static String json = " " ;
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
//Log.i("DATA","json data is :: "+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
//jarr = new JSONArray(json);
//jObj = jarr.getJSONObject(0);
//JSONParser parser = new JSONParser();
//Object obj = parser.parse(json);
//JSONObject jsonObj = (JSONObject) obj;
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
The full logcat
02-25 14:13:43.070 2708-2725/com.example.user.callarocket D/request!﹕ starting
02-25 14:13:43.132 2708-2723/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 14:13:43.132 2708-2723/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c46c20, error=EGL_SUCCESS
02-25 14:13:43.318 2708-2725/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 14:13:43.318 2708-2725/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.example.user.callarocket, PID: 2708
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.user.callarocket.MainActivity$CreateUser.doInBackground(MainActivity.java:129)
at com.example.user.callarocket.MainActivity$CreateUser.doInBackground(MainActivity.java:86)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
02-25 14:13:45.643 2708-2708/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{279ba229 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.callarocket.MainActivity$CreateUser.onPreExecute(MainActivity.java:100)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.user.callarocket.MainActivity.onClick(MainActivity.java:82)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
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:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
This is my AsyncTask:
public class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(GetData.this);
protected void onPreExecute() {
dialog.setMessage("Searching Database");
dialog.show();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String Listing_ID = c.getString(lblListing_ID);
String Event_ID = c.getString(lblEvent_ID);
String Venue_ID = c.getString(lblVenue_ID);
String Start_Date = c.getString(lblStart_Date);
String End_Date = c.getString(lblEnd_Date);
String Frequency = c.getString(lblFrequency);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(lblListing_ID, Listing_ID);
map.put(lblEvent_ID, Event_ID);
map.put(lblVenue_ID, Venue_ID);
map.put(lblStart_Date, Start_Date);
map.put(lblEnd_Date, End_Date);
map.put(lblFrequency, Frequency);
jsonlist.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(GetData.this, jsonlist,
R.layout.list_item, new String[] { lblListing_ID , lblEvent_ID,
lblVenue_ID, lblStart_Date, lblEnd_Date, lblFrequency }, new int[] {
R.id.Listing_ID, R.id.Event_ID, R.id.Venue_ID,
R.id.Start_Date, R.id.End_Date, R.id.Frequency });
setListAdapter(adapter);
// select single ListView item
lv = getListView();
}
}
And here is my JSONParser class:
public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
JSONObject object = new JSONObject( builder.toString());
jarray = object.getJSONArray("listings");
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
}
When the url is standard like:
http://192.168.1.74/android_connect/get_venues.php
It works fine. However if i add parameters like:
http://192.168.1.74/android_connect/get_venues.php?Venue_Name=Venue Name
It gives the error saying activity has leaked window. Here is the logcat:
23915-23915/com.familiestvw.whatson E/WindowManager﹕ Activity com.familiestvw.whatson.GetData has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42f9a980 V.E..... R......D 0,0-1026,288} that was originally added here
android.view.WindowLeaked: Activity com.familiestvw.whatson.GetData has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42f9a980 V.E..... R......D 0,0-1026,288} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:450)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
at android.app.Dialog.show(Dialog.java:287)
at com.familiestvw.whatson.GetData$ProgressTask.onPreExecute(GetData.java:84)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.familiestvw.whatson.GetData.onCreate(GetData.java:77)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
Any ideas on what the problem is and how to fix it would be greatly appreciated.
Probably the error exists in the AsyncTask, which causes the Activity to shutdown, then when you try to open a dialog, the exception occurs. I suggest that check the earlier log, also try to print what you get from the URL.
I am making 3 fragments pages app, and have 2 diffrent fragments with http json but with same code. The app work normaly but when i go to fragment and to another then back i get force close
threadid=1: thread exiting with uncaught exception (group=0x411f42a0)
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.fddaaf.Fragment3.updateList(Fragment3.java:55)
at com.example.fddaaf.Fragment3$thirdDownloadFilesTask.onPostExecute(Fragment3.java:83)
at com.example.fddaaf.Fragment3$thirdDownloadFilesTask.onPostExecute(Fragment3.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
this is Fragment3 class
public class Fragment3 extends Fragment {
private ArrayList<thirdFeedItem> thirdfeedList;;
private ProgressBar progresssbar;
private ListView thirdfeedListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View thirdrootView = inflater.inflate(R.layout.third, container, false);
progresssbar = (ProgressBar)thirdrootView.findViewById(R.id.progresssBar);
String url = "";
new thirdDownloadFilesTask().execute(url);
return thirdrootView;
}
public void updateList() {
thirdfeedListView= (ListView)getActivity().findViewById(R.id.third_list);
thirdfeedListView.setVisibility(View.VISIBLE);
if (thirdfeedListView.isShown()) {
progresssbar.setVisibility(View.GONE);
}
thirdfeedListView.setAdapter(new thirdCustomListAdapter(getActivity(), thirdfeedList));
thirdfeedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = thirdfeedListView.getItemAtPosition(position);
thirdFeedItem thirdData = (thirdFeedItem) o;
Intent intent = new Intent(getActivity(), thirdFeedDetailsActivity.class);
intent.putExtra("thirdfeed", thirdData);
startActivity(intent);
}
});
}
public class thirdDownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onPostExecute(Void result) {
if (null != thirdfeedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// 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();
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 (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
thirdfeedList = new ArrayList<thirdFeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
thirdFeedItem item = new thirdFeedItem();
item.setthirdTitle(post.getString("title"));
item.setthirdDate(post.getString("description"));
item.setthirdId(post.getString("id"));
item.setthirdUrl(post.getString("url"));
item.setthirdContent(post.getString("description"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setthirdAttachmentUrl(attachment.getString("url"));
}
thirdfeedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I checked everything, what can be a problem? thank you