parse JSON data into listView - java

How do I get my JSON data into my listview? All I am trying to do is loop through the JSON data and grab the first two elements and add them to my two text fields in my listview.
BUT when I do the code below it just puts the whole array element into both list views brackets and all. It increments but just the main array not the sub items. (if that makes sense)?
Below is my json data the magic happens after " //Loop the Array":
[["Ace Tattooing Co","80260","(303) 427-3522 ","461 W 84th Ave",""],["Think Tank Tattoo","80209","(720) 932-0124","172 S Broadway",""]]
This is my script so far:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowShop extends ListActivity {
private static final String TAG = "MyApp";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ziplist_layout);
Bundle bundle = getIntent().getExtras();
String shop_data = bundle.getString("shopData");
Log.v(TAG, shop_data);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
try{
//Get the element that holds the earthquakes ( JSONArray )
JSONArray jsonShopArray = new JSONArray(shop_data);
**//Loop the Array**
for(int i=0;i < jsonArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONArray e = jsonShopArray.getJSONArray(i);
Log.v(TAG, e.toString(i));
map.put("id", String.valueOf(1));
map.put("name", "Store name:" + e.toString(2));
map.put("zipcode", "Zipcode: " + e.toString(3));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.shop_list,
new String[] { "name", "zipcode" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
/**Toast.makeText(ShowShop.this, zipReturn, Toast.LENGTH_LONG).show(); */
}
}

e.toString is incorrect http://developer.android.com/reference/org/json/JSONArray.html#toString(int)
You should use getString or getInt or getWhatever

Related

how to get listview data from parseJson

hi please answer my question
i have this code in eclipse for Android Developing.
i am using mysql and php for database and get data with JSON . But i dont know how can i use JSONparse data in listview . please edit my codes.
public class ViewAllPersons extends Activity {
String url = "http://192.168.1.206/androhp/view_all_persons.php";
ArrayList<String> result;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_all_person);
result = new ArrayList<String>();
LoadAllPersons lap = new LoadAllPersons();
lap.execute(url);
}
class LoadAllPersons extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
InputStream jsonStream = getStreamFromURL(args[0], "GET");
String jsonString = streamToString(jsonStream);
parseJSON(jsonString);
return null;
}
void parseJSON(String JSONString) {
try {
JSONObject jo = new JSONObject(JSONString);
JSONArray allpersons = jo.getJSONArray("allpersons");
for (int i = 0; i < allpersons.length(); i++) {
JSONObject object = allpersons.getJSONObject(i);
String objString = "";
objString = object.getString("name") + " , "
+ object.getString("name2") + " : "
+ object.getInt("iconlink");
result.add(objString);
}
} catch (JSONException e) {
}
}
protected void onPostExecute(String file_url) {
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
CustomList adapter = new
CustomList(ViewAllPersons.this, web, imageUrl);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
How can I use parseJSON data instead of web listview :
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
You have got both data as well as list, now you need to combine them.
first you have to convert your json result into list, where values are your json values.
final ArrayList<String> listdata = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
listdata .add(values[i]);
}
then you have to assign adapter to your list. You can use following code.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.yourlistlayout, listdata );
list.setAdapter(adapter);
More details
http://www.vogella.com/tutorials/AndroidListView/article.html

Binding data through PHP to Android using JSON

I am developing an android application using PHP and mysql as external database. Now in my activity page whole JSON data are there but not bind in listview. I tried a lot and search on google as well.
My activity.java is below:
private void getdatalatlog(double latitude, double longitude) {
String link = "http://192.168.0.104/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'";
aq.progress(R.id.progressBar1).ajax(link, JSONObject.class, this,"jsonCallback");
}
public void jsonCallback(String link, JSONObject json, AjaxStatus status) throws JSONException {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
json = jParser.getJSONFromUrl(link);
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE,TAG_USERNAME ,TAG_MESSAGE
}, new int[] { R.id.shop_name,R.id.address,R.id.distance
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
My getdatalatlong() method is called in onCreate() method. And in jsonCallback() method's json object, I got all data of my database.
Check whether you are getting the JSON Object from the server.
if you got means do this. Store that JSON Result in an string(usually i call it JSONString).
For example :
{
"username":"Vignesh";
"title" : "Check My Site";
"content" : "vickytechy.hol.es"
}
Then use this to get the values by the index
JSONObject jsonObject = new JSONObject(JSONString);//JSONString is the JSON result;
Name = jsonObject.optString("username");//Name = Vignesh
Title = jsonObject.optString("title");//Title = Check My Site
Content = jsonObject.optString("content");//Content = vickytechy.hol.es

How to use Array-list in String array?

I am creating an image-view from JSON URL where I am pushing the URL in a array-list. Here is the code.
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(AnotherActivity.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);
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for (int i = 0; i < android.length(); i++)
{
map = new ArrayList<HashMap<String, String>>();
JSONObject c = android.getJSONObject(i);
// Storing each json item in variable
String flag = c.getString("flag");
HashMap<String, String> map = new HashMap<String, String>();
map.put("url",flag);
arraylist.add(i,"\"" + map.toString().substring(5).replace("}", "\""));
}
final String[] imageUrl= arraylist.toArray(new String[arraylist.size()]);
Log.v("url", "Creating view..." + imageUrl);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Now I want to use this array-list in a string array.
String[] IMAGES = new String[]{
};
How can I do that?? When I tried something like this
String[] imageUrl= arraylist.toArray(new String[arraylist.size()]);
I got the the log as
Creating view...[Ljava.lang.String;#41450ea0
Use Arrays.toString(array[]) method to print array as here you are getting [Ljava.lang.String;#41450ea0 Which isObject reference for array.
String[] imageUrl= arraylist.toArray(new String[arraylist.size()]);
Log.v("url", "Creating view..." + Arrays.toString(imageUrl));
Which will print array like this
[element1,element2...]
You can remove [ ] by the use of indexOf
String s= Arrays.toString(imageUrl);
s = s.substring(1, s.length()-1)

Android listview adapter in listview (json children)

Sorry.... I'm new in android....
I have done such schema:
i created listview in my activity, and put on it adapter with own activity as in all tutorials...
But now i must to go further and create more complicated activity: on every my listview adapter view i must put another loop with data => other listview with adapter... Is it real?
Here is my code(i do it in education goal):
protected void onCreate(Bundle savedInstanceState) {
String bank;
bank = this.getIntent().getStringExtra("Bank_id");
url = "http://192.168.1.4:3000/exchanger_lists/get_bank_exchanger_list/"+bank+".json";
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_exchangers_list);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
banks = json.getJSONArray(TAG_Exchangers);
// looping through All Contacts
for(int i = 0; i < banks.length(); i++){
JSONObject c = banks.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_address);
String location_name = c.getString(TAG_location_name);
String latitude = c.getString(TAG_latitude);
String longitude = c.getString(TAG_longitude);
String exchanger_type_name = c.getString(TAG_exchanger_type_name);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_address, address);
map.put(TAG_location_name, location_name);
map.put(TAG_latitude, latitude);
map.put(TAG_longitude, longitude);
map.put(TAG_exchanger_type_name, exchanger_type_name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.bank_exchanger_list_element,
new String[] { TAG_NAME, TAG_location_name, TAG_address, TAG_exchanger_type_name, TAG_latitude, TAG_longitude }, new int[] {
R.id.bank_e_n, R.id.nas_punkt_e_n , R.id.adress_obm_e_n , R.id.tip_obm_e_n , R.id.shirota_e_n , R.id.dolgota_e_n });
setListAdapter(adapter);
}
i need to parse json children for each TAG_Exchangers and add in as an adapter for adapter listAdapter adapter = new SimpleAdapter(this, contactList, .......
Is it real? And how to do it?
why not using BaseAdapter , where you rule everything related to how it looks and how it uses the data? just implement getCount,getItem, and getView .
for more information about listView, watch "the world of listView" lecture.

Populate a ListView from an ArrayList<HashMap<String, String>>

I have an ArrayList<HashMap<Contact, Name>> and I want to populate a ListView with it. Here's my attempt (which is not working)
ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String, String>>();
// Array of strings "titulos"
String titulos[] = { "Dolar (Transferencia)", "Euro (Transferencia)",
"Dolar (Efectivo)", "Euro (Efectivo)", "Dolar (cĂșcuta)",
"Euro (cucuta)" };
try {
JSONObject json = result; // result is a JSONObject and the source is located here: https://dl.dropbox.com/u/8102604/dolar.json
JSONObject root = json.getJSONObject("root");
JSONArray items = root.getJSONArray("item");
int j = 0;
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
String key = item.getString("key");
String mount = item.getString("mount");
if (key.equals("TS") || key.equals("TE") || key.equals("EE")
|| key.equals("CE") || key.equals("ES")
|| key.equals("CS")) { // i did this since i only need the items where the key is equal to TS, TE, EE, CE, ES or CS.
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", String.valueOf(i));
map.put(key, mount);
lista.add(map);
System.out.println(titulos[j] + "(" + key + "). BsF = " + mount); // just for debugging purposes
j++; // add 1 to j if key is equal to TS, TE, EE, CE, ES or CS. In this way i can associate the two arrays (item and titulos)
}
}
ListView lv = (ListView) myMainActivity.findViewById(R.id.listView1); // create a list view
lv.setAdapter(new ArrayAdapter<String>(contexto, android.R.layout.simple_list_item_1, lista)); // set adapter to the listview (not working)
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
That last line is throwing an error in eclipse:
The constructor ArrayAdapter<String>(Context, int, ArrayList<HashMap<String,String>>) is undefined
I've tried everything but I still couldn't make it work, could you help me please?
Thanks in advance.
PS: Full source: https://gist.github.com/4451519
Just use a SimpleAdapter.
String[] from = new String[] { /* all your keys */};
int[] to = new int[] { /* an equal number of android.R.id.text1 */};
ListAdapter adapter = new SimpleAdapter(contexto, lista, android.R.layout.simple_list_item_1, from, to);
It would be simple (and more logical) if each item of your list contained a similarly formed object, not a different key every time.
I would replace
map.put(key, mount);
by
map.put("key", key);
map.put("value", mount);
and then the from and to are simply:
String[] from = new String[] { "value" };
int[] to = new int[] { android.R.id.text1 };
You'll have to create your own adapter if you really want to pass the whole list of HashMaps, as the ArrayAdapter<String> expects the third parameter in your case to be of the type List<String>.
You should follow #Tomislav Novoselec's suggestion in the comments, and create a List<String> from the HashMap values.
You need to use your own CustomArrayAdapter like below and consume this class in your code.
public class CustomArrayAdapter extends BaseAdapter {
private JSONArray jsonArray = null;
public ImageAdapter(Context c, JSONArray jsonArray) {
context = c;
this.jsonArray = jsonArray;
}
public int getCount() {
return jsonArray.length();
}
public View getView(int position, View convertView, ViewGroup parent) {
//DO YOUR CODE HERE
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_view, null);
}else{
//Set values for your listview on the list item.
convertView.findViewById(R.id.someID).setText("GetJSONTEXT");
}
}
}
MY SUGGESTION FOR YOUR MAINACTIVITY
package com.kustomrtr.dolarparalelovenezuela;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.loopj.android.http.*;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.1.5/dolar.json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
try {
JSONObject json = new JSONObject(response); // result is a JSONObject and the source is located here: https://dl.dropbox.com/u/8102604/dolar.json
JSONObject root = json.getJSONObject("root");
JSONArray items = root.getJSONArray("item");
ListView lv = (ListView) myMainActivity.findViewById(R.id.listView1); // create a list view
lv.setAdapter(new CustomArrayAdapter<String>(contexto, android.R.layout.simple_list_item_1, items));
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You have to create you own Custom Adapter by Extending BaseAdapter in Android. Then you can set your custom adapter to the ListView by using the setAdapter method of the list view.
For your reference of please see the below small example of BaseAdapter. You need to pass your ArrayList< HashMaP > to the Adapter.
http://jimmanz.blogspot.in/2012/06/example-for-listview-using-baseadapter.html
Hope this helps.

Categories

Resources