Custom list view not refreshing after changes - android

There are many questions on updating a custom list view, one common problems seems to be a reference issue with the ArrrayList as in this answer or a not calling update from the UI thread. Though I have not managed to fix my issue with those examples.
As far as I can tell, the Arraylist (nameScoresList) is being updated and the getView function in the adapter also appears to be called when notifyDatasetChanged is called. Looking at the logs in different locations in the code the Arraylist is changing with the new values.
However, the screen of the app remains with the original list view rendered and does not change with the altered values of nameScoresList.
Can anyone see the mistake I am making? Thanks
The code for my adapter is:
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
public ListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.list_row_name_score, null);
txtFirst=(TextView) convertView.findViewById(R.id.name);
txtSecond=(TextView) convertView.findViewById(R.id.score);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
Log.d("CHECK_UPDATE", map.get(SECOND_COLUMN));
return convertView;
}
// Two previous attempts at an update function
//
// public void refreshScores(float[] outputScores) {
// int count = 0;
// for(HashMap<String, String> entry : this.list) {
// entry.put(SECOND_COLUMN, Float.toString(outputScores[count]));
// count += 1;
// }
// this.notifyDataSetChanged();
// }
// public void refreshScores(ArrayList<HashMap<String, String>> nameScoresList) {
// list.clear();
// list.addAll(nameScoresList);
// this.notifyDataSetChanged();
// }
}
These are the sections which I think are relevant from the main activity (I can add more if needed):
private ArrayList<HashMap<String, String>> nameScoresList = new ArrayList<HashMap<String, String>>();
public class SpeechActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Put data in nameScoresList;
for (int i=0; i < speakerJson.entrySet().size(); i++){
nameScoresList.add(new HashMap<String, String>());
}
int ID_number;
for (Map.Entry<String, JsonElement> entry : speakerJson.entrySet()) {
speaker = entry.getKey();
ID_number = entry.getValue().getAsInt();
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(FIRST_COLUMN, speaker.replace("_", " "));
temp.put(SECOND_COLUMN, Float.toString(0));
nameScoresList.set(ID_number - 1, temp);
}
adapter = new ListViewAdapter(this, nameScoresList);
nameScoresLV.setAdapter(adapter);
record();
}
private void record() {
// Get outputScores
// Update Arraylist which ListView uses
int count = 0;
for (HashMap<String, String> entry : nameScoresList) {
entry.put(SECOND_COLUMN, Float.toString(outputScores[count]));
count += 1;
}
runOnUiThread(
new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
// These are calls which correspond to the commented functions in ListViewAdapter class
//adapter.refreshScores(outputScores);
//adapter.refreshScores(nameScoresList);
}
});
}

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.

Android. Using HashMap for listView

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;
}
}
I know this is old post, but I know what the question is asking ask he request for a loop, just put your hashMap into the loop as well and you will be fine. for your loop n count, count on your variables
for(int i = 0; i< n; i++){
HashMap<String, String> hashMap = new HashMap<>();
map.put("title", $title);
map.put("date", $date);
classList.add(hashMap);
}
It's because you add two times map which is a reference to the same object. After your first NewsArrayList.add((HashMap<String, String>) map);, you overwrite the values of title and date, that's why you end up with the same values twice.
To fix, just create another map like this:
// map
NewsArrayList = new ArrayList<HashMap<String, String>>();
map1 = new HashMap<String, String>();
map1 .put("title", "New branch opened!");
map1 .put("date", "28.03.2014");
NewsArrayList.add((HashMap<String, String>) map1);
map2 = new HashMap<String, String>();
map2.put("title", "Second one!");
map2.put("date", "28.03.2014");
NewsArrayList.add((HashMap<String, String>) map2);

Android Show autocomplete values within a HashMap

public class Select_outlet_sales extends Activity {
private AutoCompleteTextView select_outlet;
ArrayList<HashMap<String, String> > ar=new ArrayList<HashMap<String, String> >();
HashMap<String, String> x=new HashMap<String, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_outlet_sales);
select_outlet = (AutoCompleteTextView) findViewById(R.id.select_outlet);
select_outlet.setTextIsSelectable(true);
getValues();
ArrayAdapter<HashMap<String, String>> adapter = new ArrayAdapter<HashMap<String, String>>(
this, android.R.layout.simple_dropdown_item_1line, ar);
select_outlet.setAdapter(adapter);
}
public void getValues() {
x.put("id"," aaaaa");
ar.add(x);
}
}
Here I used the above code to show data stored in a Hashmap but i want to display only the value of id. But when i try that it shows the entire hash map.Can you help me to do that?
Don't use ar but do something like this
List<String> strings = new ArrayList<String>();
for(int i = 0; i < x.size(); i++)
{
strings.add(x.get("id"));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,strings);
select_outlet.setAdapter(adapter);
That's because inside ArrayAdapter created list of HashMaps. You should translate your HashMap into ArrayList<Pair<String, String>> for example and override method getView of ArrayAdapter.
class MyAdapter extends ArrayAdapter<Pair<String, String>>{
public MyAdapter (Context context, List<Pair<String, String>> data) {
super(context, android.R.layout.simple_list_item_1,data);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new TextView(getContext());
}
((TextView)view).setText(getItem(position).second);
return view;
}
}
Add this to your code:
select_outlet.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> hashMap = (HashMap<String, String>)parent.getItemAtPosition
(position);
Iterator<String> iterator = hashMap.keySet().iterator();
while(iterator.hasNext()) {
String key = (String) iterator.next();
String value = (String)hashMap.get(key);
select_outlet.setText(value);
}
}
});
This will show only "aaaaa"in AutoComplete textbox.

Items in listview not setting up using BaseAdapter and SimpleAdapter

I'm facing problem with setting up the items in ListView, I'm using an Async task for updating the items. Here is what I have done so far.
Async Task onPostExecute()
#Override
protected void onPostExecute(String result) {
notifyList = new ArrayList<HashMap<String, String>>();
try {
JSONObject rootObj = new JSONObject(result);
JSONObject jSearchData = rootObj.getJSONObject("notifications");
int maxlimit = 5;
for (int i = 0; i < maxlimit; i++) {
JSONObject jNotification0 = jSearchData.getJSONObject(""
+ i + "");
String text = jNotification0.getString("text");
String amount = jNotification0.getString("amount");
String state = jNotification0.getString("state");
System.out.println(text);
System.out.println(amount);
System.out.println(state);
HashMap<String, String> map = new HashMap<String, String>();
map.put("text", text);
map.put("amount", amount);
notifyList.add(map);
}
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is my CustomNotification class which extends BaseAdapter
public class CustomNotificationAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> notificationData = new ArrayList<HashMap<String, String>>();
public CustomNotificationAdapter(
ArrayList<HashMap<String, String>> notificationData) {
this.notificationData = notificationData;
}
#Override
public int getCount() {
return notificationData.size();
}
#Override
public Object getItem(int position) {
return notificationData.get(position).get("text").toString();
}
#Override
public long getItemId(int position) {
return notificationData.get(position).get("text").hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
LayoutInflater inflater = getLayoutInflater();
vi = inflater.inflate(R.layout.custom_notification_list, null);
TextView notificationText = (TextView) findViewById(R.id.notificationText);
TextView notificationAmount = (TextView) findViewById(R.id.notificationPoint);
notificationText
.setText(notificationData.get(position).get("text"));
notificationAmount.setText(notificationData.get(position).get(
"amount"));
return vi;
}
}
NotificationAdapter class which extends SimpleAdapter
public class NotificationAdapter extends SimpleAdapter {
List<Map<String, String>> cur_list = new ArrayList<Map<String, String>>();
public NotificationAdapter(Context context,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(context, data, resource, from, to);
}
}
I'm able to get all the data from JSONResponse but I'm not able to show it on the list. What am I missing?
Any kind of help will be appreciated.
Try replacing this:
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
with this:
notification_adapter = new CustomNotificationAdapter(notifyList);
notification_list.setAdapter(notification_adapter);
This will set the adapter to the new JSON data even if notification_adapter was previously null.
Call notification_adapter.notifyDataSetChanged() after updating your adapter's data or remove the if (notification_adapter != null) {if you want it easy and bad.
to update your data:
public void updateData(ArrayList<HashMap<String, String> notificationData){
this.notificationData = notificationData;
this.notifyDataSetChanged();
}
Inside your adapter, and call it like: notification_adapter.updateData(notifyList);

How to add data dynamically into the spinner from xml

Hello I'm downloading XML and parsing data. I want to add data to the spinner. The data updates every time I run the application.
public class Main extends ListActivity {
TextView valueTextView;
HashMap<String, String> name=null;
private HashMap<String, String> array_spinner[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main)
ArrayList<HashMap<String, String>>mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
NodeList nodes = doc.getElementsByTagName("Table");
Toast.makeText(Main.this, "ID '" + nodes.getLength(),Toast.LENGTH_LONG).show();
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", "Name:" + XMLfunctions.getValue(e, "name"));
map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
mylist.add(map);
}
valueTextView = (TextView)findViewById(R.id.selected);
Spinner s = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
Its incomplete code I don't know how to apply SpinnerAdapter Please anyone help me
Thank you
Abhishek
I would take your Hashmap and create an Array instead, without knowing how you want your Spinner to work I would combine Name and Score. Then make the call to the adapter like this:
String[] nameScore = (xml name score data in string array)
ArrayAdapter adapter= new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameScore);
s.setAdapter(adapter);
Anything more complex than that then you will have to make a custom adapter.
Answer:::
Here is what you do. Create a Class called NameData then set properties with ID, name and score.
public class NameData {
public int id;
public String name;
public int score;
public NameData(int i, String n, int s) {
this.id = i;
this.name = n;
this.score = s;
}
}
Next create a method to connect to your data parse it and put each item into this NameData Object
public List<NameData> getNameData() {
List<NameData> list = new LinkedList<NameData>();
//get data from url and parse it to your namedata object
// /.....for loop (psuedo coding here...
list.add(new NameData(id, name, score));
// end for loop
return list;
}
then you will need to make a custom List adapter that uses a layout you design for the rows.:
private class ItemsAdapter extends BaseAdapter {
NameData[] items;
public ItemsAdapter(Context context, int textViewResourceId, NameData[] md) {
this.items = md;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TextView text1;
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.yourRowForListlayout, null);
}
text1 = (TextView) view.findViewById(R.id.yourRowForListlayoutTextView);
text1.setText("" + (position+1));
return view;
}
#Override
public int getCount() {
return this.items.length;
}
#SuppressWarnings("boxing")
#Override
public Object getItem(int p) {
return p;
}
#Override
public long getItemId(int p) {
return p;
}
}
then in your creation code you can take this list and add it directly to the adapter:
List<NameData> list = getNameData();
adapter = new ItemsAdapter(this, R.layout.yourRowForListlayout, list.toArray(new NameData[list.size()]) );
setAdapter(adapter);
And thats the way I would do it for a custom list.

Categories

Resources