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

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));

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

List View Items Deleted When Back Button Pressed Android

I am new to android development. I have implemented an activity which is Loading Json data to a listview. I have two activities now. First one is login Activity.Second one is loading list view activity.the json data is loading perfectly. but my problem is, when i pressed back button, the list view data is removing one by one. i have no idea where the problem is.
here is my main activity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
ImageButton login;
public static ArrayList<HashMap<String, String>> oslist;
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
static final String TAG_OS = "android";
static final String TAG_VER = "ver";
static final String TAG_NAME = "name";
static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loging);
oslist = new ArrayList<HashMap<String, String>>();
login = (ImageButton)findViewById(R.id.imageButton1);
new ArrayList<HashMap<String, String>>();
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.title);
name = (TextView)findViewById(R.id.artist);
api = (TextView)findViewById(R.id.time);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParser jParser = new JsonParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
Intent reult = new Intent(MainActivity.this,ViewList.class);
//reult.putStringArrayListExtra("map", oslist);
//startActivity(reult);
reult.putExtra("arraylist", oslist);
startActivityForResult(reult, 500);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my Listview Activity
public class ViewList extends Activity {
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Intent getres = getIntent();
//HashMap<String, String> hashMap = (HashMap<String, String>)getres.getSerializableExtra("map");
final ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
ListView list=(ListView)findViewById(R.id.list);
/* ListAdapter adapter = new SimpleAdapter(ViewList.this, arl,
R.layout.row,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.title,R.id.artist, R.id.time});*/
NewsRowAdapter adapter = new NewsRowAdapter(ViewList.this, R.layout.row, arl);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(ViewList.this, "You Clicked at "+arl.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
this is my Adapter Class
public class NewsRowAdapter extends BaseAdapter {
/*//ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
//ArrayList<HashMap<String, String>> data;
private List<Item> items;
//private Item objBean;
private int row;*/
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/*public NewsRowAdapter(Activity act, int resource, HashMap<String, List<String>> listChildData)) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.data = arrayList;
}*/
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
TextView title = (TextView) vi.findViewById(R.id.title);
TextView artist = (TextView) vi.findViewById(R.id.artist);
TextView time = (TextView) vi.findViewById(R.id.time);
ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
title.setText(song.get(MainActivity.TAG_VER));
artist.setText(song.get(MainActivity.TAG_NAME));
time.setText(song.get(MainActivity.TAG_API));
//imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);
Button accept = (Button) vi.findViewById(R.id.btnaccept);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//CustomizedListView getlist = new CustomizedListView();
final int x = (int) getItemId(position);
Toast.makeText(parent.getContext(),"you clicked "+ x , Toast.LENGTH_SHORT).show();
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "view clicked: " , Toast.LENGTH_SHORT).show();
}
});
return vi;
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int possision) {
// TODO Auto-generated method stub
return possision;
}
#Override
public long getItemId(int possision) {
// TODO Auto-generated method stub
return possision;
}
}
please some one help me...
Yes it will do so, When you press back button your activity get finished , So the view inside the activity will get deleted , Either you must keep the data in a seperate class, outside activity or keep the activity alive.

footer view not displayed in listview (Custom adapter)

Footer view is not displayed at the end of the listview .
Pleas tell me where I am going wrong .The code for the footerview is :
footerView = ((LayoutInflater)getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.listfooter, null, false);
list.addFooterView(footerView);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Entire Code :
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "https://itunes.apple.com/us/rss/topalbums/limit=20/json";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
static ListView list;
static LazyAdapter adapter;
HashMap<String, String> map;
public static String message_receiver_str;
public static int deleteposition;
public static ArrayList<HashMap<String, String>> songsList;
View footerView ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
songsList = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL(URL);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray arr3 = e1.getJSONArray("im:image");
JSONObject arr8 = e1.getJSONObject("im:name");
JSONObject arr10 = e1.getJSONObject("im:artist");
JSONObject e12 = arr3.getJSONObject(0);
// creating new HashMap
map = new HashMap<String, String>();
map.put(KEY_THUMB_URL, e12.getString("label"));
map.put(KEY_ARTIST, arr8.getString("label"));
map.put(KEY_TITLE, arr10.getString("label"));
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
// Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o= (HashMap<String, String>) list.getItemAtPosition(position);
// Toast.makeText(CustomizedListView.this, "ID '" + o.get("title") + "' was clicked.", Toast.LENGTH_SHORT).show();
deleteposition=position;
message_receiver_str= o.get("title");
Intent ii= new Intent(getBaseContext(),openedmsg.class);
startActivity(ii);
}
});
footerView = ((LayoutInflater)getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.listfooter, null, false);
list.addFooterView(footerView);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data=new ArrayList<HashMap<String, String>>();
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public static HashMap<String, String> song;
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());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(CustomizedListView.KEY_TITLE));
artist.setText(song.get(CustomizedListView.KEY_ARTIST));
duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
return vi;
}
}
listfooter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:padding="13dp"
android:layout_height="fill_parent">
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="15dp"
android:text="Tap to Load"
android:textColor="#android:color/darker_gray"/>
</LinearLayout>
You must call addFooterView() before you call setAdapter() on the ListView. Same applies for addHeaderView().

TextView on LazyAdapter display wrong data

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.

Categories

Resources