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

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.

Related

Displaying data in Recyclerview from a JSONobject single string with multiple values

I have a DataList jsonarray with a jsonobject as Data , the string has different values which is seprated by character "´" , the values are respectively corresponding
to the "Headers" object , i need to display this in a recycler view as SL.,InNo,etc., how can i achieve this by spliting the characher "´" which gives a string array,i
furthur need to display this data from adapter to different textview, any ideas would be really helpful.
"MainData": {
"Headers": "SL.>´InNo. - Supp<´InvNo.<´Date^´Value>´Disc.>´Rate´Others>´Amount>",
"FieldSeparator": "´",
"DataList": [
{
"Data": "1. ´19110 / Textiles´003220´01-sep-2019´70,605.00´0.00´530.25´982.75´118.00´",
"DataInputType": 1
},
{
"Data": "2. ´19111 / Textiles´7041´01-sep-2019´8,895.00´0.00´444.75´173.25´513.00´",
"DataInputType": 1
},
You have multiply approaches in order to preform that task,
first of all extract the needed information into string then you can use
replace function to change '`' into '' read more about string handling in java
extraction:
Converting JSON data to Java object
replace function: How to remove special characters from a string?
Assuming you want your data to be in a usable structure like that.
[
{
"SL" : "1"
"InNo": "19910"
...
},
{
"SL" : "2"
"InNo": "19911"
...
}
]
As others have mentioned the idea is to use the split("´") the rest are how you want to structure you data.
Use a class or a method to create the above structure:
public class DefineData {
// Assuming the below desired structure
// [
// {
// SL : 1
// InNo: 19910
// ...
// },
// {
// SL : 2
// InNo: 19911
// ...
// }
//
// ]
private ArrayList<HashMap<String, String>> dataArrayList;
// Helper method please use your own JsonObject instead of that method
public JSONObject getJsonObject() {
String json = "{ \"MainData\":{ \"Headers\":\"SL.>´InNo. - Supp<´InvNo.<´Date^´Value>´Disc.>´Rate´Others>´Amount>\", \"FieldSeparator\":\"´\", \"DataList\": [ { \"Data\": \"1. ´19110 / Textiles´003220´01-sep-2019´70,605.00´0.00´530.25´982.75´118.00´\", \"DataInputType\":1 }, { \"Data\":\"2. ´19111 / Textiles´7041´01-sep-2019´8,895.00´0.00´444.75´173.25´513.00´\", \"DataInputType\":1 }] } }";
try {
JSONObject obj = new JSONObject(json);
return obj;
} catch (Throwable tx) {
Log.e("TAG", "getJsonObject: ", tx.getCause());
throw new RuntimeException("");
}
}
public DefineData() throws JSONException {
dataArrayList = new ArrayList<>();
// Assuming everything is a String for now
JSONObject obj = getJsonObject();
JSONObject mainData = obj.getJSONObject("MainData");
String headers = mainData.getString("Headers");
// In your case "´" but it's a good practise to grab that from the JsonObject
String fieldSeparator = mainData.getString("FieldSeparator");
JSONArray dataList = mainData.getJSONArray("DataList");
// Loop through dataList and populate the data map and split the data using the FieldSeparator
String[] headersArray = headers.split(fieldSeparator);
for (int i = 0; i < dataList.length(); i++) {
JSONObject dataJsonObject = dataList.getJSONObject(i);
String dataString = dataJsonObject.getString("Data");
String[] dataArray = dataString.split(fieldSeparator);
// Loop through the dataArray
HashMap<String, String> dataMap = new HashMap<>();
for (int j = 0; j < dataArray.length; j++) {
String dataItem = dataArray[j];
String header = headersArray[j];
dataMap.put(dataItem, header);
}
dataArrayList.add(dataMap);
}
}
public ArrayList<HashMap<String, String>> getDataArrayList() {
return dataArrayList;
}
}
Your Adapter for the RecyclerView should look similar to that:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<HashMap<String, String>> dataArrayList;
public MyAdapter(ArrayList<HashMap<String, String>> dataArrayList) {
this.dataArrayList = dataArrayList;
}
#Override
public int getItemCount() {
return dataArrayList.size();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// Your root layout here instead of view..
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_item, parent, false);
// TextView txtView = view.findViewById(R.id.textView);
MyViewHolder vh = new MyViewHolder(view);
// vh.textView = txtView;
return vh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
// The position will be similar to DataList position but this time we have the
// information from the header
HashMap<String, String> key = dataArrayList.get(position);
//String slVal = key.get("SL");
//String inNoVal = key.get("InNo");
// Or simply iterate through them whatever works best
holder.textView.setText("The desired value");
// Do the same for the rest..
}
// VIEW HOLDER
public static class MyViewHolder extends RecyclerView.ViewHolder {
public View view;
public TextView textView;
// Views....
// Pass in your view or layout - RelativeLayout, ConstraintLayout
public MyViewHolder(View view) {
super(view);
this.view = view;
}
}
public ArrayList<HashMap<String, String>> getDataArrayList() {
return dataArrayList;
}
public void setDataArrayList(ArrayList<HashMap<String, String>> dataArrayList) {
this.dataArrayList = dataArrayList;
}
}
Then it should be as simple as:
MyAdapter myAdapter;
RecyclerView recyclerView;
// ...
// ...
DefineData defineData = null;
try {
// Don't forget to pass in the jsonObject you want!!
defineData = new DefineData();
} catch (Exception e) {
Log.e("TAG", "MyAdapter: ", e.getLocalizedMessage());
}
mAdapter = new MyAdapter(defineData.getDataArrayList());
recyclerView.setAdapter(mAdapter);
First get the datalist from the MainData JSON object by converting the JSON to POJO Class object. Then for each Data string in the datalist, split the Data string and store/copy each split value to respective variables (i.e. Sl. No., InNo., etc.).
For splitting the string into an array, use split function of Strings.
String data = "1. ´19110 / Textiles´003220´01-sep-2019´70,605.00´0.00´530.25´982.75´118.00´";
String[] dataArray = str.split("´", 0);
I would suggest you create a class named DataClass ( or some other name that suits it) and add all headers as data members. Once you have the dataArray, create a new DataClass object and add it to the recycler view list.

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

How to clear all items in a ListView while using List Adapter onTextChange?

I have been trying to find answers, but it has been hard to find a solution that works.
I tried setting the adapter to null, clearing the actual list but neither seems to work.
I am using a ListView with a ListAdapter and am trying to make it clear on a change of search Text when text is changed.
list.clear(); works but it does not occur on text change.
Here is my code:
private EditText search_input;
private Button search_button;
// progress bar for search results
private ProgressDialog search_loading;
private ListView wordSearchList;
private ListAdapter adapter;
// no result layout
private LinearLayout no_res;
// create list for adapter
ArrayList<HashMap<String, String>> list;
// database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary_search);
search_input = (EditText) findViewById(R.id.search_dictionary);
search_button = (Button) findViewById(R.id.search_button);
search_button.setOnClickListener(this);
// linear layout for no results
no_res = (LinearLayout) findViewById(R.id.search_result_ll);
// create hashmap list
list = new ArrayList<HashMap<String, String>>();
// remove views if they exist
search_input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// REMOVE LIST VIEW AND ADAPTER
// list.clear();
if (no_res.getChildCount() > 0) {
no_res.removeAllViews();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onClick(View v) {
if (v == search_button) {
// clear list for fresh start
list.clear();
no_res.removeAllViews();
// validate input and that something was entered
if (search_input.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please search for something!", Toast.LENGTH_LONG)
.show();
} else {
String search_data;
search_data = search_input.getText().toString();
// remove any current views on search again
// REMOVE THE LIST VIEW
// execute the query search
List<DatabaseWordsFTS> search_results = db
.getSingleWordSearch(search_data);
// if no search results returned
if (search_results.size() <= 0) {
TextView no_results_tv = new TextView(this);
no_results_tv.setText("No results found.");
no_res.addView(no_results_tv);
}
// setup listview
wordSearchList = (ListView) findViewById(R.id.wordSearchList);
for (DatabaseWordsFTS word_found : search_results) {
// have to create hashmap in loop
HashMap<String, String> map = new HashMap<String, String>();
// convert d id to long
Integer dictionary_id_convert = (int) (long) word_found._dictionaryId;
// extract dictionary from d-id - since it is not a list and
// just a variable
DatabaseDictionary dictionary_found = db
.getDictionary(dictionary_id_convert);
// extract languages to send below
Integer dln_1 = (int) dictionary_found._language1Id;
Integer dln_2 = (int) dictionary_found._language2Id;
Integer dln_3 = (int) dictionary_found._language3Id;
Integer dln_4 = (int) dictionary_found._language4Id;
// get languages for the words based on ids passed in
List<DatabaseLanguages> LanguagesForD = db
.getAllLanguagesWithId(dln_1, dln_2, dln_3, dln_4);
// add name to hashmap and rest of the data as strings
map.put("w_1", word_found.get_word1_fts());
map.put("l_1", LanguagesForD.get(0)._language_name);
map.put("d_id", String.valueOf(dictionary_id_convert));
map.put("w_id", String.valueOf(word_found.get_id()));
if (word_found.get_word2_fts() != null) {
map.put("w_2", word_found.get_word2_fts());
map.put("l_2", LanguagesForD.get(1)._language_name);
}
if (word_found.get_word3_fts() != null) {
map.put("w_3", word_found.get_word3_fts());
map.put("l_3", LanguagesForD.get(2)._language_name);
}
if (word_found.get_word4_fts() != null) {
map.put("w_4", word_found.get_word4_fts());
map.put("l_4", LanguagesForD.get(3)._language_name);
}
list.add(map);
// used to dismiss progress bar for searching
search_loading.dismiss();
}
String[] from = { "w_1", "w_2", "w_3", "w_4" }; // , "word3",
// "word4"
int[] to = { R.id.textName, R.id.textLanguage };
adapter = new SimpleAdapter(this, list,
R.layout.dictionary_row, from, to);
wordSearchList.setAdapter(adapter);
wordSearchList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
HashMap itemValue = (HashMap) wordSearchList
.getItemAtPosition(position);
String w_id = (String) itemValue.get("w_id");
String d_id = (String) itemValue.get("d_id");
String l_1 = (String) itemValue.get("l_1");
String l_2 = (String) itemValue.get("l_2");
String l_3 = (String) itemValue.get("l_3");
String l_4 = (String) itemValue.get("l_4");
String w_1 = (String) itemValue.get("w_1");
String w_2 = (String) itemValue.get("w_2");
String w_3 = (String) itemValue.get("w_3");
String w_4 = (String) itemValue.get("w_4");
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition
+ " ListItem : " + w_id,
Toast.LENGTH_LONG).show();
// creating bundle
Bundle d_data = new Bundle();
// add to bundle
d_data.putString("w_id", w_id);
d_data.putString("wd_id", d_id);
d_data.putString("w_1", w_1);
d_data.putString("l_1", l_1);
// get tags only if it exists
if (w_2 != null) {
d_data.putString("w_2", w_2);
d_data.putString("l_2", l_2);
}
if (w_3 != null) {
d_data.putString("w_3", w_3);
d_data.putString("l_3", l_3);
}
if (w_4 != null) {
d_data.putString("w_4", w_4);
d_data.putString("l_4", l_4);
}
// start new intent based on the tag -
Intent single_word_view = new Intent(
DictionaryWordSearch.this,
DictionarySingleWordView.class);
// call extras
single_word_view.putExtras(d_data);
// new_dictionary_view.putExtra("d_id",
// WhatAmISupposeToPassInHere);
startActivity(single_word_view);
}
});
}
EDIT: (Below worked for me)
Changed ListAdapter to SimpleAdapter
if(adapter != null){list.clear(); adapter.notifyDataSetChanged();}
Added the above code in onTextChange
Look if you want the TextView with no result you can implement this code
listView.setEmptyView(emptyView)
and pass your TextView to this method ,
for clearing the ListView you can clear your collection and call notifyChangeDataSet or set adapter with null try both and feed me back

How to populate a String Array from a JSONObject to use in a ListView

I have an android/java task where I want to get JSON values into a String array to display in a ListView and I am not sure where to begin? Thanks.
private String[] values;
...
// this is what is returned from the web server (Debug view)
// jObj = {"success":1,"0":"Mike","1":"message 1","2":"Fred","3":"message 2","4":"John","5":"message 3"};
try {
if (jObj.getInt("success") == 1) {
.
// what i'm trying to do here is iterate thru JObj and assign values to the
// values array to populate the ArrayAdapter so that the ListView displays this:
//
// Mike: Message 1
// Fred: Message 2
// John: Message 3
//
.
this.setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, android.R.id.text1, values));
ListView listView = getListView();
}
}
catch (JSONException e) {
Log.e(TAG, e.toString());
}
Use ArrayList instead of Array to add values retrieved from Json Obejct and then set ArrayList for ListView as data-source. change your code as:
ArrayList<String> array_list_values = new ArrayList<String>();
try {
if (jObj.getInt("success") == 1) {
array_list_values.add(jObj.getString("0"));
array_list_values.add(jObj.getString("1"));
array_list_values.add(jObj.getString("2"));
array_list_values.add(jObj.getString("3"));
array_list_values.add(jObj.getString("4"));
array_list_values.add(jObj.getString("5"));
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, array_list_values));
ListView listView = getListView();
}
}
catch (JSONException e) {
Log.e(TAG, e.toString());
}
EDIT :
if number of messages is not always the same it may 1 to a larger number then you can Iterate JsonObject as:
ArrayList<String> array_list_values = new ArrayList<String>();
try {
if (jObj.getInt("success") == 1) {
Iterator iter = jObj.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObj.getString(key);
array_list_values.add(value);
}
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, array_list_values));
ListView listView = getListView();
}
}
catch (JSONException e) {
Log.e(TAG, e.toString());
}
You should do something like that and use the awesome GSON library:
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
APIResponse response = gson.fromJson(reader, APIResponse.class);
With:
Public class APIResponse{
public String 0;
public String 1;
public String 2;
public String 3;
public String 4;
public String 5;
public String succes;
}
But this won't work as you need to find an other name that 0,1,2,3,4,5 for the variables.
Please change this on server side
JSONObject jsonObject = new JSONObject(jsonString);
String value0 = jsonObject.getString("0");
or
in for loop
String tempArray[] = new String[5];
just do
for(int i=0;condition;i++){
tempArray[i] = jsonObject.getString(String.ValueOf(i));
}
and pass the array to adapter

parse JSON data into listView

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

Categories

Resources