I try to use HashMap<String, String>() to populate ListView. I'm supposed to fetch my site API to get the latest news json representation. By now I basically try to simulate dynamic data and put the news manually. The problem I faced is that it won't add news as expected but just repeats them. Sorry for bad explanation. Here's my code to clarify
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "ru.rateksib.sendmessage.MESSAGE";
EditText editText;
ListView newsList;
Map<String, String> map;
ArrayList<HashMap<String, String>> NewsArrayList;
NewsArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.news_dialog, null);
builder.setView(convertView);
builder.setTitle("Новости компании");
// set up list view inside alertDialog
newsList = (ListView) convertView.findViewById(R.id.dialogNewsList);
// map
NewsArrayList = new ArrayList<HashMap<String, String>>();
map = new HashMap<String, String>();
map.put("title", "New branch opened!");
map.put("date", "28.03.2014");
NewsArrayList.add((HashMap<String, String>) map);
map.put("title", "Second one!");
map.put("date", "28.03.2014");
NewsArrayList.add((HashMap<String, String>) map);
// custom adapter
arrayAdapter = new NewsArrayAdapter(NewsArrayList, this);
newsList.setAdapter(arrayAdapter);
So when I run the app the list is populated twice with the last set of title and date.
My custom adapter code is
public class NewsArrayAdapter extends BaseAdapter {
ArrayList<HashMap<String,String>> names;
Context ctxt;
LayoutInflater inflater;
public NewsArrayAdapter(ArrayList<HashMap<String,String>> newsArrayList, Context c) {
names = newsArrayList;
ctxt = c;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return names.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return names.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
// TODO Create the cell (View) and populate it with an element of the array
if (view == null) {
// view = inflater.inflate(android.R.layout.simple_list_item_1, viewGroup, false);
view = inflater.inflate(R.layout.dialog_news_list_item, viewGroup, false);
}
TextView title = (TextView) view.findViewById(R.id.title);
TextView date = (TextView) view.findViewById(R.id.date);
title.setText(names.get(position).get("title"));
date.setText(names.get(position).get("date"));
return view;
}
}