Can anyone help here. I'm trying to populate a listview from a json response. the response is posting, for some reason it isn't showing the list? anything helps
Also it is stopping on the list view, just not seeing anything.
extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> ideasList;
// url to get all products list
private static String url_all_products = "http://theideavault.no-ip.org//android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "ideas";
private static final String TAG_IID = "iid";
private static final String TAG_NAME = "idea";
// products JSONArray
JSONArray ideas = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_idea);
// Hashmap for ListView
ideasList = 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 iid = ((TextView) view.findViewById(R.id.iid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditIdeaActivity.class);
// sending pid to next activity
in.putExtra(TAG_IID, iid);
// 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(AllIdeasActivity.this);
pDialog.setMessage("Reteiving Ideas from database. Wooooooo...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// 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 Ideas: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
ideas = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < ideas.length(); i++) {
JSONObject c = ideas.getJSONObject(i);
// Storing each json item in variable
String iid = c.getString(TAG_IID);
String idea = 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_IID, iid);
map.put(TAG_NAME, idea);
// adding HashList to ArrayList
ideasList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewIdeaActivity.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(
AllIdeasActivity.this, ideasList,
R.layout.list_idea, new String[] { TAG_IID,
TAG_NAME},
new int[] { R.id.iid, R.id.idea });
// updating listview
setListAdapter(adapter);
}
});
}
}}
The great mistake you did is while initialize TAG_PRODUCTS variable.
Mistake:
private static final String TAG_PRODUCTS = "ideas";
Correct value:
private static final String TAG_PRODUCTS = "products";
BTW, are you fetching ideas or products? because your response is of products and your code describes Idea :)
Related
I am trying to get data from a database(phpmyadmin) so far I used this code:
Main Activity:
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/gIndex";
// 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) {
// 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);
}
});
}
}
}
But I get following error message:
Error parsing data org.json.JSONException: Value
[{"id":1,"name":"dasdasdasdasdasdasd","description":"","video_url":"","platform":"111111111111","logo":"","avaible":0,"token":"","created_at":"2016-03-25
23:44:35","updated_at":"2016-03-25
23:44:35","release_at":"2016-04-10"},
This gives the correct json which I created in my php, so it works somehow I think.
Further I get this error message in the logs:
java.lang.RuntimeException: An error occurred while executing
doInBackground() ...
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.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:147)
at
com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:122)
I've made an activity that gets jsonarray and puts it in a list. Next i've assigned an AutoCompleteTextView to a field witch fleches the json objects im using.
in my jsonarray its 3 objects: ItemID,ItemDescription and ItemVolume. My AutoCompleteTextView field contains jsonObject: ItemDescription.
I need to get the itemID when the itemDescription is selected in my onItemClickListner.
Heres the code
ArrayAdapter<String> adp = new ArrayAdapter<String>(shoppingcart.this,
android.R.layout.simple_dropdown_item_1line, responseList);
autocomplete.setAdapter(adp);
autocomplete.setThreshold(1);
private class GetContacts extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(shoppingcart.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(urlget);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
autocomplete.setThreshold(1);
try {
// Getting JSON Array from URL
AllItems = json.getJSONArray(TAG_GETALL);
for(int i = 0; i < AllItems.length(); i++) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getString(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getString(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Edit:
This is what i did for the List parts.
HashMap<String,Integer> ItemAndID= new HashMap<String,Integer>();
List<String> responseList = new ArrayList<String>();
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
AllItems = json.getJSONArray(TAG_GETALL);
for(int i = 0; i < AllItems.length(); i++) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getInt(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getInt(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
ItemAndID.put(Name, ID);
}
For OnClick I did this.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedName = (String) parent.getItemAtPosition(position);
// if you used a HashMap
ResultID = ItemAndID.get(selectedName);
}
See this example you are not saving ItemId anywhere. If you don't want to create a new Object, you can create a new list to save ItemIds or you can create a HaspMap<String, String> like ["name1":"id1","name2":"id2"] and then depending on what you use to save ItemId
setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedName = (String) parent.getItemAtPosition(position);
// if you used a HashMap
String ID = exampleHashMap.get(selectedName);
}
}
Create a new list like responseListItemId and pares it along side responseList:
List<Integer> responseListItemId = new ArrayList<Integer>();
.....
#Override
protected void onPostExecute(JSONObject json) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getString(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getString(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
responseListItemId.add(ID);
}
Now get the index value of the description from the responseList and use it in the responseListItemId to get your itemID.
My suggestion would be to create a custom class for your data type like Product and ten create a custom adapter see https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView
I am loading my data in a listview from my localhost server. I want to display the count in a textview (locationCount). Any ideas?
My listview has id/list which is referenced for an async class that loads the products. Hence I am bit confused if you treat as a normal listview or is it slightly different?
I have 20 entries in my DB that show, so count should be 20, but when I delete an entry the count should be 19, or 21 if I add. Please explain?
Class:
public class ViewAllLocations extends ListActivity {
String id;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> profileList;
// url to get all products list
private static String url_all_profile = "http://MYIP:8888/android_connect/get_all_location.php";
// url to delete product
private static final String url_delete_profile = "http://MYIP:8888/android_connect/delete_location.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_LOCATION = "Location";
private static final String TAG_ID = "id";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";
// products JSONArray
JSONArray userprofile = null;
TextView locationCount;
int count = 0;
Button deleteLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_locations);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
deleteLocation = (Button) findViewById(R.id.deleteLocation);
// Loading products in Background Thread
new LoadAllLocation().execute();
deleteLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DeleteLocation().execute();
}
});
// Get listview
ListView lo = getListView();
getListAdapter().getCount();
locationCount.setText(getListAdapter().getCount());
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteLocation extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Deleting Location...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
// Intent i = getIntent();
// send result code 100 to notify about product deletion
//setResult(100, i);
Toast.makeText(getApplicationContext(), "Location Deleted",
Toast.LENGTH_SHORT).show();
finish();
}
} 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();
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllLocation extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Loading Locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_LOCATION);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
UserLocation.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(
ViewAllLocations.this, profileList,
R.layout.locationitem, new String[] { TAG_ID,
TAG_LATITUDE, TAG_LONGITUDE},
new int[] { R.id.id, R.id.latitude, R.id.longitude});
// updating listview
setListAdapter(adapter);
}
});
}
}
Log: "It gets the profiles and then when it reaches the final end it crashes"
04-19 19:09:48.665 26876-27452/com.example.ankhit.saveme D/All Profiles:﹕ {"success":1,"Location":[{"id":"26","longitude":"-0.5509257","latitude":"51.4276462"},{"id":"27","longitude":"-0.5509387","latitude":"51.4277023"},{"id":"28","longitude":"-0.5509387","latitude":"51.4277023"},{"id":"29","longitude":"-0.550991","latitude":"51.4275759"}]}
04-19 19:09:48.675 26876-26876/com.example.ankhit.saveme D/AndroidRuntime﹕ Shutting down VM
04-19 19:09:48.675 26876-26876/com.example.ankhit.saveme W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x42008ac8)
04-19 19:09:48.675 26876-26876/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation$1.run(ViewAllLocations.java:260)
at android.app.Activity.runOnUiThread(Activity.java:4843)
at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation.onPostExecute(ViewAllLocations.java:246)
at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation.onPostExecute(ViewAllLocations.java:165)
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:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Override the get count() method in your adapter or post it here and I'll give you some code.
Call adapter.get count() whenever you add or remove an item.
The first thing that happens once a user navigates to this page is the app populates a listview with a list of states from a remote database. Then the user selects a state and the app goes back to the database and gets a list of county's in that state.
The states load fine, the problem is the countys don't load. In the log it shows that the page is returning an empty array. if i just go to the page http://photosbychristian.com/ems/get_countys.php?state=PA
it works fine. I'm not sure were the problem is because no errors are thrown and it worked fine the first time for getting the states.
Here is my code:
package com.example.hospitals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Add extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog cDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
JSONParser jParserCo = new JSONParser();
ArrayList<HashMap<String, String>> statesList;
ArrayList<HashMap<String, String>> countyList;
// urls
private static String url_states = "http://photosbychristian.com/ems/get_states.php";
String url_countys;
// JSON Node names for states
private static final String TAG_STATES = "states";
private static final String TAG_TB_NAME = "tbname";
private static final String TAG_NAME = "name";
private static final String TAG_ABBR = "Abbr";
//JSON Node names for countys
private static final String TAG_COUNTYS = "countys";
private static final String TAG_NAME_COUNTY = "name";
// JSONArrays
JSONArray states = null;
JSONArray countys = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
//path.setText("");
// Hashmap for ListView
statesList = new ArrayList<HashMap<String, String>>();
countyList = new ArrayList<HashMap<String, String>>();
// Loading states in Background Thread
new LoadAllStates().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 abbr = ((TextView) view.findViewById(R.id.abbr)).getText().toString();
String cf = ((TextView) view.findViewById(R.id.comingFrom)).getText().toString();
TextView path = (TextView)findViewById(R.id.path);
Log.d("Coming From",cf);
if (cf == "1"){//countys
path.append(abbr + " > ");
url_countys = "http://photosbychristian.com/ems/get_countys.php?state="+abbr;
Log.d("url", url_countys);
new LoadAllCountys().execute();
}else if(cf == "2"){//citys
path.append(abbr + " > ");
}else if (cf == "3"){//hospitals
path.append(abbr);
}
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllStates extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Add.this);
pDialog.setMessage("Loading states. Please wait.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting all staets from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_states, "GET", params);
// Check your log cat for JSON reponse
Log.d("All States: ", json.toString());
try {
// products found
// Getting Array of Products
states = json.getJSONArray(TAG_STATES);
// looping through All Products
for (int i = 0; i < states.length(); i++) {
JSONObject c = states.getJSONObject(i);
// Storing each json item in variable
String table = c.getString(TAG_TB_NAME);
String name = c.getString(TAG_NAME);
String abbr = c.getString(TAG_ABBR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TB_NAME, table);
map.put(TAG_NAME, name);
map.put(TAG_ABBR, abbr);
map.put("ComingFrom", "1");
// adding HashList to ArrayList
statesList.add(map);
}
} 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(
Add.this,
statesList,
R.layout.hospital_items,
new String[] { TAG_TB_NAME, TAG_ABBR, TAG_NAME, "ComingFrom"},
new int[] { R.id.id, R.id.abbr, R.id.name, R.id.comingFrom }
);
// updating listview
setListAdapter(adapter);
}
});
}
}
class LoadAllCountys extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
cDialog = new ProgressDialog(Add.this);
cDialog.setMessage("Loading countys. Please wait.");
cDialog.setIndeterminate(false);
cDialog.setCancelable(false);
cDialog.show();
}
/**
* getting all staets from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject jsonCo = jParserCo.makeHttpRequest(url_countys, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Countys: ", jsonCo.toString());
try {
// products found
// Getting Array of Products
countys = jsonCo.getJSONArray(TAG_COUNTYS);
// looping through All Products
for (int i = 0; i < countys.length(); i++) {
JSONObject c = countys.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME_COUNTY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME_COUNTY, name);
map.put("ComingFrom", "2");
// adding HashList to ArrayList
countyList.add(map);
}
} 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
cDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Add.this,
countyList,
R.layout.hospital_items,
new String[] {TAG_NAME, "ComingFrom"},
new int[] { R.id.name, R.id.comingFrom }
);
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Also once i figure this out after the user selects a county the listview will populate with citys and then hospitals so if there is a better way to do this i'd be willing to learn.
Something like this works for me. I download the file first and then create json object using it:
mJsonString = downloadFileFromInternet(urls[0]);
if(mJsonString == null)
return false;
JSONObject jObject = null;
jObject = new JSONObject(mJsonString);
----
private String downloadFileFromInternet(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
new IllegalArgumentException("url is empty/null");
StringBuilder sb = new StringBuilder();
InputStream inStream = null;
try
{
url = urlEncode(url);
URL link = new URL(url);
inStream = link.openStream();
int i;
int total = 0;
byte[] buffer = new byte[8 * 1024];
while((i=inStream.read(buffer)) != -1)
{
if(total >= (1024 * 1024))
{
return "";
}
total += i;
sb.append(new String(buffer,0,i));
}
}catch(Exception e )
{
e.printStackTrace();
return null;
}catch(OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
private String urlEncode(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
return null;
url = url.replace("[","");
url = url.replace("]","");
url = url.replaceAll(" ","%20");
return url;
}
I am not sure if I understood your question correctly. But still...
You can change the data set for an adapter to a listview and refresh it. This way ths list view will start to show the new set of data items.
In onItemClick of the list view, you can do something like this:
mAdapter.setListData(mSubMenu);
mAdapter.notifyDataSetChanged();
where your mSumMenu can be county's arraylist.
Need help on android =( been stuck on this for ages! My codes are as shown.
public class AllUsersActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
// url to get all users list
private static String url_all_users = "http://10.0.2.2/android_connect/get_all_users.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UID = "UserID";
private static final String TAG_FIRSTNAME = "FirstName";
// users JSONArray
JSONArray users = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_users);
// Hashmap for ListView
usersList = new ArrayList<HashMap<String, String>>();
// Loading users in Background Thread
new LoadAllusers().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String uid = ((TextView) view.findViewById(R.id.uid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
UserDetailsActivity.class);
// sending uid to next activity
in.putExtra(TAG_UID, uid);
// 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 LoadAllusers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUsersActivity.this);
pDialog.setMessage("Loading users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All users from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
// Check your log cat for JSON reponse
Log.d("All users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// users found
// Getting Array of users
users = json.getJSONArray(TAG_USERS);
// looping through All users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_FIRSTNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, id);
map.put(TAG_FIRSTNAME, name);
// adding HashList to ArrayList
usersList.add(map);
}
}
} 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 users
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllUsersActivity.this, usersList,
R.layout.list_item, new String[] { TAG_UID,
TAG_FIRSTNAME},
new int[] { R.id.uid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
Can anyone please help me! The error i've been getting is Error Parsing Data Org.json.JSONException: Value cannot be converted to JSONObject
Heres the JSON string
Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
Is the error lying in the JSON parser class?
EDIT: here the code for the php script that outputs the array above. can anyone tell me what's wrong with the php script that outputs the word array before the json string? Sorry for the trouble. I'm new to coding. Been following online tutorials but stuck on this for a few days now.
<?php
/*
* Following code will list all the Users
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all Users from Users table
$result = mysql_query("SELECT * FROM Users") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// Users node
$response["Users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$user[] = array();
$user["UserID"] = $row["UserID"];
$user["FirstName"] = $row["FirstName"];
$user["Email"] = $row["Email"];
$user["Password"] = $row["Password"];
// push single User into final response array
array_push($response["Users"], $user);
}
// success
$response["success"] = 1;
echo $response;
// echoing JSON response
echo json_encode($response);
}
else {
// no Users found
$response["success"] = 0;
$response["message"] = "No Users found";
// echo no users JSON
echo json_encode($response);
}
?>
Use GSON library instead, it is official Google and works like a charm. No HashMaps etc, immediate objects.
Take a look at it here.
As the error suggests, your JSON string does not represent a valid JSON object.
Try like this(without Array in the beginning):
{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
You can check the validity of your JSON String here: http://jsonlint.com/