This question already has answers here:
How to parse JSON Array (Not Json Object) in Android
(11 answers)
Closed 6 years ago.
JSON LInk - http://jsonviewer.stack.hu/#http://www.saveme.ie/api/savings/
Im trying to fetch a JSON to fill a listview in Android with this background task but its saying there is a problem with the JSON. It seems to be because the array has no name.
How would i modify the code so it can fetch the array with no name?
private class GetSavings extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
**JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray savings = jsonObj.getJSONArray("savings");
// looping through All Contacts
for (int i = 0; i < savings.length(); i++) {
JSONObject c = savings.getJSONObject(i);
String title = c.getString("title");
}**
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, savingsList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
Instead of casting it in JSONObject, cast it into JSONArray.
JSONArray jsonObj = new JSONArray(jsonStr);
and then traverse your array.
Related
So I want to add custom view markers in my android application, I am fetching the coordinates from an API request and I want to display the logo of the places on their respective marker. I am getting the URL of the marker from the same API request. Moreover, I want all the markers to be a part of the single symbol layer because I want to cluster those markers as well. Image credits: Google Image Search.
I have solved this problem.
First You Have to create a private class which will fetch a data for you then you store it in an array.
private class getgeo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Poi_View.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject JO = (JSONObject) contacts.get(i);
/* if(JO.has("devices"))
{
Toast.makeText(Index.this,"No Data Found",Toast.LENGTH_LONG).show();
}*/
JSONObject jb = (JSONObject) JO.get("ro");
String name = jb.getString("name");
String center = jb.getString("center");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contact.put("center", center);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Internet Connection is Weak. Try Reloading Your Page",
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Check Your Internet Connection",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
After that you have to execute it in your mapbox onStyleloaded() method
public void onStyleLoaded(#NonNull Style style) {
for(int a=0;a<contactList.size();a++)
{
HashMap<String, String> hashmap = contactList.get(a);
pump_name= hashmap.get("name");
pump_center= hashmap.get("center");
String fullname = pump_center;
String[] names = fullname.split(",", 3); // "1" means stop splitting after one space
String firstName = names[0];
String lastName = names[1];
double lat = Double.parseDouble(firstName);
double lng = Double.parseDouble(lastName);
System.out.println(lat);
System.out.println(pump_name);
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title(pump_name));
//onMapReady(mapboxMap);
}
}
Check out https://docs.mapbox.com/android/maps/examples/symbol-layer-info-window. GenerateViewIconTask in that example, uses a View to create a Bitmap. The Bitmap(s) are added to the map for usage as SymbolLayer icons.
Alternatively, you could use the Mapbox Annotation Plugin for Android: https://docs.mapbox.com/android/plugins/overview/annotation/
The JSON is simple as,
[{"kw":"48.90","kva":"51.20","pf":"-0.96"}]
The error I get is,
08-26 02:28:49.130 13605-13641/com.whatever.emshive E/MainActivity:
Response from url: [{"kw":"48.90","kva":"51.20","pf":"-0.96"}]
Json parsing error: Value [{"kw":"48.90","kva":"51.20","pf":"-0.96"}] of type org.json.JSONArray
cannot be converted to JSONObject 08-26 02:28:49.130
13605-13641/com.whatever.emshive E/JSON Parser: Error parsing data
org.json.JSONException: Value
[{"kw":"48.90","kva":"51.20","pf":"-0.96"}] of type org.json.JSONArray
cannot be converted to JSONObject
Code is,
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://simpleasthat.com/s.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(0);
String kw = c.getString("kw");
String kva = c.getString("kva");
String pf = c.getString("pf");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("kw", kw);
contact.put("kva", kva);
contact.put("pf", pf);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Log.e("JSON Parser", "Error parsing data " + e.toString());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"kw", "kva",
"pf"}, new int[]{R.id.kw,
R.id.kva, R.id.pf});
lv.setAdapter(adapter);
}
}
}
I have tried looking at other similar answers in StackOverflow, couldn't get it. Help is much appreciated. Thank You
Please change the code in GetContacts.doInBackground from
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
to
JSONArray contacts = new JSONArray(jsonStr);
As the message says, you're trying to cast a JSON array into a JSON object. Your JSON is an array...
This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 4 years ago.
I have a code where i should pass an static user id for authentication and then fetch the JSON response from the URL and display it in listview. But i get an error that says "JSON Parsing error: No value in (JSON array)". Please help
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "url";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "2"));
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("SignUpRsp", String.valueOf(result));
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
}
}
public String PostData(String[] valuse) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "value"));
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse= httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try {
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
}
JSON Response:
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
},
]
}
Your JSON parsing is correct
You need to parse your JSON if your response status response code is 1
SAMPLE CODE
Try this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// check here of your status of response
// is status is 0 USER NOT FOUND
if(jsonObj.getString("status").equals("0")){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
}
});
// is status is 1 PARSE YOUR JSON
}else {
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
Your json also has an issue, can you try with this output json. Last comma(,) in an array is not required.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
JSONArray throw error because promotion_lists with a item but has needless comma.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
Your JSON parse looks fine. The issue is with the your JSON response. It is not a valid JSON Response as there is a unnecessary comma after the JSON Array "promotion_lists". Try removing the comma.
You can use this solution
public class GetContacts extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg0) {
try {
URL url = new URL(URL HERE);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
JSONObject postDataParams = new JSONObject();
postDataParams.put("user_id", user_id);
Log.i("JSON", postDataParams.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(postDataParams.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
conn.disconnect();
return sb.toString();
} else {
conn.disconnect();
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String jsonStr) {
try {
pDialog();
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Log.e(TAG, "Couldn't get json from server.");
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
One more thing you dont need to use runOnUiThread in Asynctask because
both are helper threads , which are used to Update UI,you dont have to
use runOnUIThread in it , just simple show toast without using it, it
will show it , read the documentation
https://developer.android.com/guide/components/processes-and-threads
Hi i need to save json data in sqlite. But iam getting following error.
Can't create handler inside thread that has not called
Looper.prepare().
This is my code. It is shwoing database open/database created...
/**
* Async task class to get json by making HTTP call
* */
private class GetDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#SuppressLint("NewApi")
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Create an array to populate the spinner
branchlist = new ArrayList<String>();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
// System.out.println("response"+jsonStr);
if (jsonStr != null) {
try {
// jsonString is a string variable that holds the JSON
JSONArray itemArray=new JSONArray(jsonStr);
for (int i = 0; i < itemArray.length(); i++) {
value=itemArray.getString(i);
Log.e("json", i+"="+value);
dbhelper=new DataBaseHepler(getApplicationContext());
sqLiteDatabase=dbhelper.getWritableDatabase();
dbhelper.addinnformation(value,sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show();
dbhelper.close();
branchlist.add(itemArray.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ArrayAdapter<String> stringadapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
branchlist);
spinner1.setAdapter(stringadapter);
// spinner1
// .setAdapter(new ArrayAdapter<String>(MainActivity.this,
// android.R.layout.simple_spinner_dropdown_item,
// branchlist));
}
}
This error is due to Toast inside doInBackground(Void... arg0) method:
Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show();
Clearly the Android OS wont let threads other than the main thread change UI elements. Follow this link for more details on this: https://dzone.com/articles/android-%E2%80%93-multithreading-ui
I want to get an url from this link:
"http://graph.facebook.com/10202459285618351/picture?type=large&redirect=false"
it gives result:
{
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/t1.0- 1/s200x200/10342822_10202261537234765_3194866551853134720_n.jpg",
"is_silhouette": false
}
}
I tried,
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(AccountActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(fbPicURL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
fbRealURL = jsonObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single contact
}
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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
}
}
But returning null and its not crashing..
You have to get the data object first like this:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
fbRealURLObj = jsonObj.getJSONObject("data");
fbRealURL = fbRealURLObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single contact
}