JSONException No value for..Android app - java

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.

Related

Json parsing errors at android

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.

Android Json Parse returns nothing

I have a Json Parser Class which looks like this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// 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 {
JSONArray jObj = new JSONArray(json);
System.out.println(jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Near the end at the last try and catch statement I print out the jsonObject as a string I correctly get the data in the console, the json looks like this:
[{"id":1,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":1100110011,"logo":"","avaible":0,"token":"","created_at":"2016-04-03
17:19:49","updated_at":"2016-04-03
17:19:49","release_at":"2016-05-08"},{"id":2,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":"11000000000","logo":"","avaible":0,"token":"","created_at":"2016-04-03
17:26:13","updated_at":"2016-04-03
17:26:13","release_at":"2016-05-08"}]
I used a validator and it is fine.
In my AllProducts activity I try to display that inside the android app.
It looks like this:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.155.27:8000/index";
// JSON Node names
private static final String TAG_SUCCESS = "id";
private static final String TAG_PRODUCTS = "name";
private static final String TAG_PID = "description";
private static final String TAG_NAME = "video_url";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
If I try to print out this json:
JSONObject json = new JSONObject();
I get no values (null), so my view keeps being empty.
I get follwing error message:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.toString()' on a null object
reference
at
com.example.androidhive.AllProductsActivity$LoadAllProducts$1.run(AllProductsActivity.java:150)
Line 150 is this :
Log.d("All Products: ", json.toString());
Thus Android Studio tells my that
jObj
here, in my jsonparser:
try {
JSONArray jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
is never used.
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
I am not really experienced with this so I really hope for some help, thanks.
With JSONObject json = new JSONObject(); you are creating an empty JSONObject,
the JSONObject returned by jParser.makeHttpRequest(url_all_products, "GET", params); is never used.
You have to do it like this:
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
so your JSONObject from the JParser will be stored in json.

JSONException: No value for (parsing a JSON IMAGE)

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.

NullPointerException error in android with json

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)

(Edited) I'm trying to display text on EditText from which obtain from JSONArray then get by JSONObject

This is my UserInfo.java (Edited)
public class UserInfo extends ActionBarActivity implements OnClickListener {
// Progress Dialog
private ProgressDialog pDialog;
EditText name, email, password, mobilenumber, address,
city, postcode, state;
Button update;
// private JSONArray userinfo = null;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String USERINFO_URL = "http://192.168.1.10:1234/PMSS/userinfo.php";
private static final String UPDATEUSERINFO_URL = "http://192.168.1.10:1234/PMSS/updateuserinfo.php";
// ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POSTS = "posts";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PASSWORD = "password";
private static final String TAG_MOBILENUMBER = "mobilenumber";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CITY = "city";
private static final String TAG_POSTCODE = "postcode";
private static final String TAG_STATE = "state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
// Show the Up button in the action bar.
update = (Button) findViewById(R.id.update);
name = (EditText) findViewById(R.id.nametext);
email = (EditText) findViewById(R.id.useridtext);
password = (EditText) findViewById(R.id.passwordtext);
mobilenumber = (EditText) findViewById(R.id.mobilenumbertext);
address = (EditText) findViewById(R.id.addresstext);
city = (EditText) findViewById(R.id.citytext);
postcode = (EditText) findViewById(R.id.postcodetext);
state = (EditText) findViewById(R.id.statetext);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String MobileNumber = mobilenumber.getText().toString();
String Address = address.getText().toString();
String City = city.getText().toString();
String PostCode = postcode.getText().toString();
String State = state.getText().toString();
new UpdateUser(Name, Email, Password, MobileNumber, Address,
City, PostCode, State).execute();
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new RetrieveUser().execute();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_info, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
String Name, Email, Password, MobileNumber, Address, City, PostCode, State;
public void updateJSONdata() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(UserInfo.this);
String post_username = sp.getString("username", "anon");
// String post_username = "jiaweitan05#gmail.com";
JSONParser jsonParser = new JSONParser();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", post_username));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(USERINFO_URL, "GET",
params);
// I know I said we would check if "Posts were Avail."
// (success==1)
// before we tried to read the individual posts, but I lied...
// mComments will tell us how many "posts" or comments are
// available
JSONArray userinfo = json
.getJSONArray(TAG_POSTS);
JSONObject c = userinfo.getJSONObject(0);
Name = c.getString(TAG_NAME);
Email = c.getString(TAG_EMAIL);
Password = c.getString(TAG_PASSWORD);
MobileNumber = c.getString(TAG_MOBILENUMBER);
Address = c.getString(TAG_ADDRESS);
City = c.getString(TAG_CITY);
PostCode = c.getString(TAG_POSTCODE);
State = c.getString(TAG_STATE);
name.setText(Name);
email.setText(Email);
password.setText(Password);
mobilenumber.setText(MobileNumber);
address.setText(Address);
city.setText(City);
postcode.setText(PostCode);
state.setText(State);
} catch (JSONException e) {
e.printStackTrace();
}
}
public class RetrieveUser extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UserInfo.this);
pDialog.setMessage("Loading User Info...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
class UpdateUser extends AsyncTask<String, String, Integer> {
boolean failure = false;
String res;
int success;
String Name, Email, Password, MobileNumber, Address, City, PostCode,
State, Position = "hahaha", CardBalance = "3456";
public UpdateUser(String Name, String Email, String Password,
String MobileNumber, String Address, String City,
String PostCode, String State) {
this.Name = Name;
this.Email = Email;
this.Password = Password;
this.MobileNumber = MobileNumber;
this.Address = Address;
this.City = City;
this.PostCode = PostCode;
this.State = State;
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UserInfo.this);
pDialog.setMessage("Updating User Info...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
// Check for success tag
try {
// Building Parameters
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
params2.add(new BasicNameValuePair("name", Name));
params2.add(new BasicNameValuePair("email", Email));
params2.add(new BasicNameValuePair("password", Password));
params2.add(new BasicNameValuePair("mobilenumber", MobileNumber));
params2.add(new BasicNameValuePair("address", Address));
params2.add(new BasicNameValuePair("postcode", PostCode));
params2.add(new BasicNameValuePair("city", City));
params2.add(new BasicNameValuePair("state", State));
params2.add(new BasicNameValuePair("state", Position));
params2.add(new BasicNameValuePair("state", CardBalance));
Log.d("request!", "starting");
// Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
UPDATEUSERINFO_URL, "POST", params2);
// full json response
Log.d("Update attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
res = json.getString(TAG_MESSAGE);
return success;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer success) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (success != null && success == 1) {
Log.d("User Updated!", res);
Intent r = new Intent(UserInfo.this, Login.class);
startActivity(r);
finish();
Toast.makeText(
UserInfo.this,
res == null ? "Please enter the require field that marked with **"
: res, Toast.LENGTH_LONG).show();
} else {
Log.d("Update Failure!", "res: " + res);
Toast.makeText(
UserInfo.this,
res == null ? "Please enter the require field that marked with **"
: res, Toast.LENGTH_LONG).show();
}
}
}
}
This is my logcat (Edited)
12-13 21:47:32.199: D/request!(1387): starting
12-13 21:47:35.629: E/JSON Parser(1387): Error parsing data org.json.JSONException: Value <h1>User of type java.lang.String cannot be converted to JSONObject
12-13 21:47:35.669: W/System.err(1387): org.json.JSONException: No value for name
12-13 21:47:35.679: W/System.err(1387): at org.json.JSONObject.get(JSONObject.java:354)
12-13 21:47:35.709: W/System.err(1387): at org.json.JSONObject.getString(JSONObject.java:510)
12-13 21:47:35.709: W/System.err(1387): at com.pmss.UserInfo.updateJSONdata(UserInfo.java:165)
12-13 21:47:35.709: W/System.err(1387): at com.pmss.UserInfo$RetrieveUser.doInBackground(UserInfo.java:203)
12-13 21:47:35.709: W/System.err(1387): at com.pmss.UserInfo$RetrieveUser.doInBackground(UserInfo.java:1)
12-13 21:47:35.709: W/System.err(1387): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-13 21:47:35.709: W/System.err(1387): at java.lang.Thread.run(Thread.java:1019)
12-13 21:48:09.449: W/IInputConnectionWrapper(1387): showStatusIcon on inactive InputConnection
What I'm trying to do is that When I click UserInfo interface, it will load the user details and place in every EditText provided in UserInfo interface. But somehow every EditText in my UserInfo interface does not display anything.
My coding don't have compilation error and runtime error
This is where I start my SharedPreferences in Login.java
if (success == 1) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("email", Username);
edit.commit();
}
Can anyone help me out? I check for 2 days but still don't know why EditText display nothing.
From the logcat it said, E/JSON Parser(971): Error parsing data org.json.JSONException: Value User of type java.lang.String cannot be converted to JSONObject ?? How should I solve it?
This is my JSONParser.java
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;
}
// 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;
}
public JSONObject makeHttpRequest(String registerUrl, String method,
String[] params) {
// TODO Auto-generated method stub
return null;
}
}
This is my userinfo.php
<?php
require("config.inc.php");
if (!empty($_POST)) {
//initial query
$query = "Select name, email, password, mobilenumber, address, city, postcode, state FROM user WHERE email = :email ";
$query_params = array(':email' => $_POST['email']);
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$row = $stmt->fetchAll();
if ($row) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
$post = array();
do {
// $post = $row["position"];
// $post = $row["state"];
// array_push($response["posts"], $post);
array_push($response["posts"], $row);
} while ($row = $stmt->fetch());
die(json_encode($response));
}
else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
}
else {
?>
<h1>User Info</h1>
<form action="userinfo.php" method="post">
Email:<br />
<input type="email" name="email" value="" />
<br /><br />
<input type="submit" value="Search User" />
</form>
<?php
}
You say you json
{ // json object
"success": 1,
"message": "Post Available!",
"posts": [ // json array posts
[ // json array node
{ // json object node
"name": "Jiawei", // string
"email": "jiaweitan05#gmail.com",
"password‌​": "123456abcd",
"mobilenumber": "0124331292",
"address": "Bunga Raya",
"city": "Bukit Beruang",
"postcode": "75450",
"state": "Melaka"
}
]
]
}
[ represents JSONArray node
{ represents JSONObject node
Assuming you have the above json
JSONObject json = jsonParser.makeHttpRequest(USERINFO_URL, "GET",
params);
Now To parse
String success =json.getString("success");
String message= json.getString("message");
JSONArray jar = json.getJSONArray("posts");
JSONArray jr = jar.getJSONArray(0);
JSONObject jb = jr.getJSONObject(0);
String name = jb.getString("name");
//similarly for email, password and so on.
Now the other json
[ // json array node
{ // json object node
"address": "Bunga Raya", // string
"mobilenumber": "0124331292",
"email": "jiaweitan05#gmail.com",
"name": "Jiawei",
"state": "Melaka",
"postcode": "75450",
"password": "123456abcd",
"city": "Bukit Beruang"
}
]
The log says
org.json.JSONArray cannot be converted to JSONObject
It means you are trying to convert a json array to json object.
Mistake:
Your response is JSONArray and you are trying to create a JSONObject with received response.
JSONObject json = jsonParser.makeHttpRequest(USERINFO_URL, "POST", params);
One more eye opening sentence exception is giving: "org.json.JSONArray cannot be converted to JSONObject".
Solution:
JSONArray arrayJSON = jsonParser.makeHttpRequest(USERINFO_URL, "POST", params);
this is actual json format
{"countrylist":[{"id":"241","country":" India"}]}
use json object like countylist

Categories

Resources