TextView on LazyAdapter display wrong data - android

i already success build up an app using ListView with LazyAdapter based on this link
but there's anomali on my listview.
each listview have 1 imageview and 2 textview.
so the lazy adapter will display "thumbnail" to imageview and "name" to Textview1 and "address" to Textview2...
the ImageView is coorect...it can display the image thumbnail from database...
but the problem here is, the BOTH TEXTVIEW didnt display the correct data!
instead displaying the "name" and the "address" from database... they display LINK for THUMBNAIL IMAGE.
so, maybe anyone can help me.
thanks b4.
here's my json :
{
"listresto": [
{
"nama_resto": "CIE RASA LOOM",
"alamat_resto": "JL. BUAH BATU No.154 Bandung",
"thumb_img": "http://10.0.2.2/culigui/images/resto_thumb/cierasaloom.JPG"
},
{
"nama_resto": "AYAM GORENG SUHARTI",
"alamat_resto": "Jl. Lodaya No. 1",
"thumb_img": "http://10.0.2.2/culigui/images/resto_thumb/ayamgorengsuharti.JPG"
},
{
"nama_resto": "BAKSO ENGGAL MALANG",
"alamat_resto": "JL. BURANGRANG 12 BANDUNG",
"thumb_img": "http://10.0.2.2/culigui/images/resto_thumb/baksoenggal.JPG"
},
{
"nama_resto": "ATMOSPHERE",
"alamat_resto": "Jl.Lengkong Besar No.97",
"thumb_img": "http://10.0.2.2/culigui/images/resto_thumb/atmosphere.JPG"
},
{
"nama_resto": "WARUNG STEAK AND SHAKE",
"alamat_resto": "Jl. Jend Gatot Subroto 28",
"thumb_img": "http://10.0.2.2/culigui/images/resto_thumb/warungsteak.JPG"
}
]
}
and here's my main activity :
public class MenuViewAll extends Activity {
// url to make request
private static String url = "http://10.0.2.2/culigui/getdataresto.php";
public static String KEY_ID,KEY_NAME,KEY_ADDRESS,KEY_THUMB;
ListView Listview;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_view_all);
// Hashmap for ListView
ArrayList<HashMap<String, String>> userList = 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 JSONArray of listresto
JSONArray listresto = json.getJSONArray("listresto");
// looping through All listresto
for(int i = 0; i < listresto.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject list = listresto.getJSONObject(i);
// insert String to Local Variable
//map.put(KEY_ID, list.getString("id_resto"));
map.put(KEY_NAME, list.getString("nama_resto"));
map.put(KEY_ADDRESS, list.getString("alamat_resto"));
map.put(KEY_THUMB, list.getString("thumb_img"));
userList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
//this is new custom adapter
Listview = (ListView) findViewById (R.id.list);
adapter = new LazyAdapter(this, userList);
Listview.setAdapter(adapter);
and here's my LaxyAdapter class :
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listitemviewall, null);
TextView namaresto = (TextView)vi.findViewById(R.id.name); // resto name
TextView alamatresto = (TextView)vi.findViewById(R.id.address); // resto address
ImageView thumb_image=(ImageView)vi.findViewById(R.id.defaultthumb); // thumb image
HashMap<String, String> resto = new HashMap<String, String>();
resto = data.get(position);
// Setting all values in listview
namaresto.setText(resto.get(MenuViewAll.KEY_NAME));
alamatresto.setText(resto.get(MenuViewAll.KEY_ADDRESS));
imageLoader.DisplayImage(resto.get(MenuViewAll.KEY_THUMB), thumb_image);
return vi;
}
}

i solved this problem...
the problem is in this code
// insert String to Local Variable
//map.put(KEY_ID, list.getString("id_resto"));
map.put(KEY_NAME, list.getString("nama_resto"));
map.put(KEY_ADDRESS, list.getString("alamat_resto"));
map.put(KEY_THUMB, list.getString("thumb_img"));
userList.add(map);
when i check on logcat with
//for checking value
//System.out.println("output: " +map);
the value is null and only sent the last value which is KEY_THUMB...
and the correct code is :
// insert String to Local Variable
//map.put("KEY_ID", list.getString("id_resto"));
map.put("KEY_NAME", list.getString("nama_resto"));
map.put("KEY_ADDRESS", list.getString("alamat_resto"));
map.put("KEY_THUMB", list.getString("thumb_img"));
userList.add(map);
that will do perfectly.thanks.

Related

Show the Elements from ArrayList of map ,in list form in Android

I have a A data stored in ArrayList< HashMap< String, String> > retrieved from JSON
in the form (i.e.)
[{price: =1685 name: =Monographie Der Gattung Pezomachus (Grv.) by Arnold F. Rster}]
And I need to show the all map elements into list form in Android.
I've tried many ways but I'm unable to do it .
Also help me to know about the layouts to use in it
EDITED:
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(myarr_list);
setListAdapter(adapter);
And in the MySimpleArrayAdapter Class, in Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
LayoutInflator inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
The control does not proceed after this,
MySimpleArrayAdapter Class
public class MySimpleArrayAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> ProductList = new ArrayList<HashMap<String, String>>();
LayoutInflater inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
this.ProductList = pl;
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
if (convertView == null) {
myview = inflater.inflate(R.layout.show_search_result, null);
}
TextView price = (TextView) myview.findViewById(R.id.price);
TextView name = (TextView) myview.findViewById(R.id.name);
HashMap<String, String> pl = new HashMap<String, String>();
pl = ProductList.get(position);
//Setting
price.setText(pl.get("price"));
name.setText(pl.get("name"));
return myview;
}
}
I am editing here a onPostExecute class from SearchResultsTask extended by AsyncTask
protected void onPostExecute(JSONObject json) {
if (json != null && json.length() > 0) {
try {
JSONArray json_results = (JSONArray)(json.get("results"));
String parsedResult = "";
System.out.println("-> Size ="+ json_results.length());
for(int i = 0; i < json_results.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_i = json_results.getJSONObject(i);
map.put("name: ",json_i.getString("name") + "\n");
map.put("price: ",json_i.getString("price") + "\n");
arr_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println("-> Size =====arr_llist ="+ arr_list.size());
// CustomListAdapter adapter = new CustomListAdapter (arr_list);
//final StableArrayAdapter adapter = new StableArrayAdapter(this, R.id.result, arr_list);
// listview.setAdapter(adapter);
MyListActivity obj1 = new MyListActivity();
Bundle icicle = null;
obj1.onCreate(icicle);
}
public class MyListActivity extends Activity {
public void onCreate(Bundle icicle) {
// System.out.println("In my list Activity");
// super.onCreate(icicle);
//populate list
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this,arr_list);
// System.out.println("in 2");
adapter.getView(0, listview, listview);
listview.setAdapter(adapter);
}
}
#Override
public int getCount() {
return ProductList.size() ;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl, Context c) {
this.ProductList = pl;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
getSystemService() is method of context, you are calling it on instance of adapter.

Returning null value in base adapter class while appending to list view

Hello all I am new to android, am trying to display a list of json data in listview my class is extended with SherlockFragment fetched the data succesfully but unable to append the data in a list. for displaying of data I created a class which extending with baseadapter class. i have found that value is returning null at View group
Can any one help in fixing the issue thanks in advance
public class AboutMeFragment extends Fragment {
ListViewAdapter la;
String add_users;
View rootView;
ArrayList<HashMap<String, String>> contactList;
static String idStr,getMaxAnsLengthStr,userIdStr,userRankStr,de;
static String getQuestionsStr = "GetQuestion";
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_aboutme,
container, false);
la = new ListViewAdapter(getActivity(), contactList);
list = (ListView)rootView.findViewById(R.id.listView1);
contactList = new ArrayList<HashMap<String, String>>();
new CheckLoginAboutmen().execute();
return rootView;
}
private class CheckLoginAboutmen extends AsyncTask<Void,Void,Void>{
String json;
String outputData = null;
JSONArray jsonArray;
#Override
protected Void doInBackground(Void... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
// params.add(new BasicNameValuePair("LoginName", loginStr));
params.add(new BasicNameValuePair("UserID", "195"));
ServiceHandler sh = new ServiceHandler();
add_users = getString(R.string.about_me);
json = sh.makeServiceCall(add_users, ServiceHandler.POST,params);
Log.d("Create Prediction Request: ", "> " + json);
System.out.println("The returned JSON Value is..."+json);
try{
jsonArray = new JSONArray(json);
if(json != null){
HashMap<String, String> contact = null;
System.out.println("The Length of JSON Array is..."+jsonArray.length());
for(int i =0;i<jsonArray.length();i++){
contact = new HashMap<String, String>();
JSONObject c = jsonArray.getJSONObject(i);
getQuestionsStr = c.getString("GetQuestion");
idStr = c.getString("_id");
getMaxAnsLengthStr = c.getString("MaxAnswerLength");
userIdStr = c.getString("UserId");
userRankStr = c.getString("UserRank");
System.out.println("The Fetched Id is...."+idStr+"\n"+getQuestionsStr+"\n"+getMaxAnsLengthStr+"\n"+userIdStr+"\n"+userRankStr);
contact.put("getQuestionsStr", getQuestionsStr);
}
contactList.add(contact);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// ListViewAdapter la = new ListViewAdapter(getSherlockActivity().getBaseContext(),contactList);
// ListViewAdapter la = new ListViewAdapter(getActivity().getBaseContext(),contactList);
//list.setAdapter(la);
list.setAdapter(new ListViewAdapter(getActivity().getBaseContext(),contactList));
}
}}
And my Base adapter class follows here.....
public class ListViewAdapter extends BaseAdapter{
int tempI =0;
int tempII = 7;
Context context;
ArrayList<HashMap<String, String>> data;
LayoutInflater inflater;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context baseContext,
ArrayList<HashMap<String, String>> contactList) {
// TODO Auto-generated constructor stub
this.context = baseContext;
data = contactList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
System.out.println("The Item Value is..."+data.get(position));
return 0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View itemView = null;
TextView textView1_lv_123;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.list_item_view, parent,false);
resultp = data.get(position);
textView1_lv_123 = (TextView)itemView.findViewById(R.id.textView1_lv_123);
// facing issue from here, data is retuning null unable to append the value to text view
String s1 = resultp.get("GetQuestion");
System.out.println("The demo String is....1234 "+s1);
textView1_lv_123.setText(resultp.get("GetQuestion"));
// if I am printing only resultp value it is returning the value/result which is an last value of array
System.out.println("The Result value is "+resultp);
return itemView;
}
}
You should change when you create your ListAdapter , you should create in AsyncTask onPostExecute. Try this:
AboutMeFragment.class:
public class AboutMeFragment extends Fragment {
ListViewAdapter la;
String add_users;
View rootView;
ArrayList<HashMap<String, String>> contactList;
static String idStr,getMaxAnsLengthStr,userIdStr,userRankStr,de;
static String getQuestionsStr = "GetQuestion";
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_aboutme,
container, false);
list = (ListView)rootView.findViewById(R.id.listView1);
contactList = new ArrayList<HashMap<String, String>>();
new CheckLoginAboutmen().execute();
return rootView;
}
private class CheckLoginAboutmen extends AsyncTask<Void,Void,Void>{
String json;
String outputData = null;
JSONArray jsonArray;
#Override
protected Void doInBackground(Void... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
// params.add(new BasicNameValuePair("LoginName", loginStr));
params.add(new BasicNameValuePair("UserID", "195"));
ServiceHandler sh = new ServiceHandler();
add_users = getString(R.string.about_me);
json = sh.makeServiceCall(add_users, ServiceHandler.POST,params);
Log.d("Create Prediction Request: ", "> " + json);
System.out.println("The returned JSON Value is..."+json);
try{
jsonArray = new JSONArray(json);
if(json != null){
HashMap<String, String> contact = null;
System.out.println("The Length of JSON Array is..."+jsonArray.length());
for(int i =0;i<jsonArray.length();i++){
contact = new HashMap<String, String>();
JSONObject c = jsonArray.getJSONObject(i);
getQuestionsStr = c.getString("GetQuestion");
idStr = c.getString("_id");
getMaxAnsLengthStr = c.getString("MaxAnswerLength");
userIdStr = c.getString("UserId");
userRankStr = c.getString("UserRank");
System.out.println("The Fetched Id is...."+idStr+"\n"+getQuestionsStr+"\n"+getMaxAnsLengthStr+"\n"+userIdStr+"\n"+userRankStr);
contact.put("getQuestionsStr", getQuestionsStr);
}
contactList.add(contact);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// ListViewAdapter la = new ListViewAdapter(getSherlockActivity().getBaseContext(),contactList);
// ListViewAdapter la = new ListViewAdapter(getActivity().getBaseContext(),contactList);
//list.setAdapter(la);
if(contactList!=null && contactList.size()>0{
la =new ListViewAdapter(getActivity().getBaseContext(),contactList));
list.setAdapter(la);
}else{
// handle no data Example:show toast "contactList have no data"
}
}}
And you should change in adapter the method getItem(). Try this:
BaseAdapter.class:
public class ListViewAdapter extends BaseAdapter{
int tempI =0;
int tempII = 7;
Context context;
ArrayList<HashMap<String, String>> data;
LayoutInflater inflater;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context baseContext,
ArrayList<HashMap<String, String>> contactList) {
// TODO Auto-generated constructor stub
this.context = baseContext;
data = contactList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
System.out.println("The Item Value is..."+data.get(position));
return data.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View itemView = null;
TextView textView1_lv_123;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.list_item_view, parent,false);
resultp = data.get(position);
textView1_lv_123 = (TextView)itemView.findViewById(R.id.textView1_lv_123);
// facing issue from here, data is retuning null unable to append the value to text view
String s1 = resultp.get("GetQuestion");
System.out.println("The demo String is....1234 "+s1);
textView1_lv_123.setText(resultp.get("GetQuestion"));
// if I am printing only resultp value it is returning the value/result which is an last value of array
System.out.println("The Result value is "+resultp);
return itemView;
}
Hi Aditya check the string declaration in AboutmeFragment page I hope they are overlapping your code

Dynamic Separator in ListView

I want to parse json into list view.
{
"Submenus": [
{
"MenuName": "Pizza",
"SubMenu": [
"Pizza Margherita ",
"Pizza al Prosciutto",
"Pizza al Peperoncino "
]
},
{
"MenuName": "Bøffer",
"SubMenu": [
"Oksekødmørbrad"
]
},
{
"MenuName": "Dessert",
"SubMenu": [
"Chokolade kage"
]
}
]
}
My class is as follows.
public class MenuTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
// Getting JSON String from URL..............
JSONObject jsonObject = jParser.makeHttpRequest(
"http://smartaway.dk/json/submenu.php?resid=" + res_id,
"POST", params);
try {
bestdeal = jsonObject.getJSONArray(TAG_MENU);
// / LOOping through AllEvents........
for (int i = 0; i < bestdeal.length(); i++) {
JSONObject e = bestdeal.getJSONObject(i);
String resname = e.getString(TAG_MENUNAME);
String city_state = e.getString(TAG_PRICE);
// Creating New HAsh Map.........
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_ID, id);
map.put(TAG_MENUNAME, resname);
map.put(TAG_PRICE, city_state);
/*
* map.put(TAG_STREET, street); map.put(TAG_COUSINE,
* cousine); map.put(TAG_RES_LOGO, reslogo);
*/
// adding HashList to ArrayList
bestdeal_list.add(map);
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
MenuAdapter menuAdapter=new MenuAdapter(RestaurantDetails.this.getParent(),bestdeal_list);
//setListAdapter(menuAdapter);
list.setAdapter(menuAdapter);
}
});
}
// }
}
Custom Adapter class is as follows.
public class MenuAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public MenuAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.menu_list, null);
TextView menuname = (TextView) vi.findViewById(R.id.textView1); // title
TextView price = (TextView) vi.findViewById(R.id.textView3);
HashMap<String, String> events = new HashMap<String, String>();
events = data.get(position);
String menustr = events.get(RestaurantDetails.TAG_MENUNAME);
String pricestr = events.get(RestaurantDetails.TAG_PRICE);
menuname.setText(menustr);
price.setText(pricestr);
return vi;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return super.getItemViewType(position);
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return super.getViewTypeCount();
}
}
I just want to separate the listview from Menuname. Each Menuname should appear on some textview with background then its respective submenus must be shown under that, then another mainmenu and so on. Please suggest how to implement that and how to modify adapter class.
What you basically want to do is to use a custom adapter, most likely derived from BaseAdapter. You will need to override getViewTypeCount() and return the number of different kinds of list items that you have in the list. In your case it's 2 since you have menu names and normal list items.
You will also have to override getItemViewType(position) and return either a 0 if the item at the specified position is a normal list item or a 1 if it's a menu name.
Finally you'll also have to override getView() and return a list item of the appropriate type (menu name or normal list item), based on getItemViewType().
There should be several snippets of code that already does this if you Google a bit. I wrote a SectionedAdapter that does this as well. It's a generic class and it handles sections/heading of a certain type (can be String or some specific class such as Section, Header or MenuName) and section contents as another type. Subclass it and implement the getSectionView() and getItemView(). Add sections and items using addSection() and addItem().

Android LazyAdapter - displaying same data on two TextViews and an ImageView

In my ListView there are 2 TextViews and an ImageView.
I am using a LazyAdapter to load images from JSON file according to this link.
I am successfully loading data but i am facing the problem that each list item shows in both TextViews the link of the image while the image itself is shown correctly.
Here is the adapter:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView name = (TextView)vi.findViewById(R.id.name);
TextView price = (TextView)vi.findViewById(R.id.price);
ImageView image=(ImageView)vi.findViewById(R.id.image);
HashMap<String, String> smart = new HashMap<String, String>();
smart = data.get(position);
id.setText(smart.get(SmActivity.KEY_ID));
name.setText(smart.get(SmActivity.KEY_NAME));
price.setText(smart.get(SmActivity.KEY_PRICE));
imageLoader.DisplayImage(smart.get(SmActivity.KEY_THUMB), image);
return vi;
}
}
And here is the activity:
public class SmActivity extends ListActivity {
static String url = "url-php to get json";
public static String KEY_PRICE, KEY_NAME, KEY_THUMB;
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> smList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJson(url);
try {
JSONArray smJArray = json.getJSONArray("sm");
for(int i = 0; i < smJArray.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObj = smJArray.getJSONObject(i);
map.put(KEY_NAME, jsonObj.getString("product_name"));
map.put(KEY_PRICE, jsonObj.getString("price")+"€");
map.put(KEY_THUMB, jsonObj.getString("image_main"));
smList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
list = (ListView)getListView().findViewById(android.R.id.list);
adapter=new LazyAdapter(this, smList);
list.setAdapter(adapter);
}
}
I can understand that ListView shows at all items the value of the last map.put(...) i am using.
For example, if the last put in HashMap is map.put(KEY_PRICE, jsonObj.getString("price")+"€");
i get the price value not only on price, but on name TextView as well. And of course i get no image.
I would be grateful in any help.
Thanks in advance.
Ok. i got it. i replaced:
public static String KEY_PRICE, KEY_NAME, KEY_THUMB;
by
static final String KEY_NAME = "product_name";
static final String KEY_PRICE = "price";
and
map.put("product_name", jsonObj.getString(KEY_NAME));
map.put("price", jsonObj.getString(KEY_PRICE));

not able to populate list from json android

I am trying to populate list object from an api.
This is one method jsonresult.
protected void onPostExecute(String result)
{
JSONArray con;
//String tag_name="tests";
//String tag_id="ID";
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try
{
JSONObject jsonObject = new JSONObject(result);
if("success".equals(jsonObject.getString("result")))
{ Toast.makeText(getBaseContext(),jsonObject.getString("tests"),Toast.LENGTH_SHORT).show();
//String nKey=jsonObject.getString("nKey");
// switchActivity(nKey);
//Toast.makeText(getBaseContext(),nKey,Toast.LENGTH_SHORT).show();
try{
con = jsonObject.getJSONArray("tests");
for(int i = 0; i < con.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = con.getJSONObject(i);
map.put("EXAM", "" + c.getString("exam"));
map.put("ID", "" + c.getString("id"));
mylist.add(map);
}}catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
else
{
Toast.makeText(getBaseContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
giving error at
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });
ERROR:
The constructor SimpleAdapter(examlist.ReadJSONResult, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined
Create a Custom Adpater for inflating the ListView.
public class MyListAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> data;
Activity a;
private static LayoutInflater inflater=null;
public MyListAdapter(Activity act, ArrayList<HashMap<String, String>> UserAndMessage)
{
data = UserAndMessage;
inflater = (LayoutInflater)act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
a = act;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup parent) {
View vi = convertview;
if(null == vi)
{
vi = inflater.inflate(R.layout.listitem, null);
TextView ID= (TextView) vi.findViewById(R.id.ID);
TextView Exam= (TextView) vi.findViewById(R.id.exam);
HashMap<String,String> item = data.get(position);
ID.setText(item.get("name"));
EXAM.setText(item.get("message"));
}
return vi;
}
}
from onPostExecute() set ListView's Adapter as below:
myList = (ListView) findViewById(R.id.listView1);
myList.setAdapter(new MyListAdapter(this, UserAndMessage));
It's because there's not such constructor for ListAdapter as you use it. As a Context (first parameter) you're passing examlist.ReadJSONResult and you should pass a Context of a Activity in which the View which uses this ListAdapter is placed.
If the class in which you're setting ListAdapter is not an Activity, then you should pass the Activity's Context to this class and store it for example as a member field for further use.
For example your class is named ReadJSONResult. Create a constructor which takes Context as a parameter:
public ReadJSONResult(Context context) {
m_context = context; // There needs to be a field member in ReadJSONResult class called m_context
}
Thanks to that, in the Activity where you create ReadJSONResult object, you pass the Activity's Context to constructor and then you can create your ListAdapter like this:
ListAdapter adapter = new SimpleAdapter(m_context, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });

Categories

Resources