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.
Related
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);
}
});
}
Its a really complicated question, but I hope someone can help me.
I want to make a custom adapter that can handle
Array List mentioned in the title
Currently I am doing this, but its not even going into getView(...) method.
public class EventsAdapter extends BaseAdapter{
ArrayList<HashMap<String, List<String>>> eventList;
private Context context;
private int resource;
private static final String TAG_TITLE = "e_title";
public EventsAdapter(Context context, int resId,ArrayList<HashMap<String, List<String>>> eventList)
{
this.context = context;
this.resource = resId;
this.eventList = eventList;
Log.v("chk", "1");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View event = convertView;
TextView title, desc, date, time, venue;
HashMap<String, List<String>> hm = eventList.get(position);
List<String> items = hm.get(TAG_TITLE);
Typeface font = Typeface.createFromAsset(context.getAssets(), "Ubahn.ttf");
if( event == null )
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
event = inflater.inflate( resource , parent, true );
event.setTag(items.get(position));
}
title = (TextView) event.findViewById( R.id.etitle);
desc = (TextView) event.findViewById( R.id.edesc );
date = (TextView)event.findViewById(R.id.edate);
time = (TextView)event.findViewById(R.id.etiming);
venue = (TextView)event.findViewById(R.id.elocation);
title.setTypeface(font);
System.out.print(items.get(0).toString());
title.setText(items.get(0).toString());
desc.setText(items.get(1).toString());
date.setText(items.get(2).toString());
time.setText(items.get(3).toString());
venue.setText(items.get(4).toString());
return event;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return eventList.get(position).get(position).get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
Any help would be greatly appreciated.
Here is how I am filling the data in the Array List
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String description = c.getString(TAG_DESC);
String date = c.getString(TAG_DATE);
String time = c.getString(TAG_TIME);
String venue = c.getString(TAG_VENUE);
// creating new HashMap
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> el = new ArrayList<String>();
el.add(title);
el.add(description);
el.add(date);
el.add(time);
el.add(venue);
// adding each child node to HashMap key => value
map.put(TAG_TITLE, el);
// map.put(TAG_DESC, description);
//muap.put(TAG_DATE, date);
// adding HashList to ArrayList
eventList.add(map);
}
and then here I am setting the adapter
EventsAdapter adapter = new EventsAdapter(getActivity(), R.layout.events_list_item, eventList);
lv.setAdapter( adapter);
I think it would be useful to consider when you are filling that list.
a good design pattern is to create the data as an empty hashmap, establish the adapter with that map, declare the listview( or whatever ) and then assign the adapter with the empty data set. later, fill the hashmap, and then adapter.notifydatasetchanged
I declare these feilds:
//array of places filtered by keyword
List<Place> places = new ArrayList<Place>( );
//spinner of places filtered by keyword
Spinner placesSpinner;
//adapter for spinner
private PlacesSpinnerAdapter placesSpinnerAdapter;
in onCreate:
//this is for a spinner, but same difference
placesSpinner = (Spinner)findViewById( R.id.placesSpinner );
placesSpinnerAdapter = new PlacesSpinnerAdapter( this,
android.R.layout.simple_spinner_dropdown_item, places );
placesSpinner.setAdapter( placesSpinnerAdapter );
and somewhere in the onPostExecute method of an AsyncTask you have no interest in
places.clear( );
places.addAll( result.results );
placesSpinnerAdapter.notifyDataSetChanged( );
placesSpinner.performClick( );
and lastly, here's a difference I see: adapters do Lists, I've never had a good time passing them hashmaps... do a map.keySet() or map.values(); as you hand the data over to the adapter; I know for certain the very standard pattern I just described does not work if the data set is hashmaps
gl hf
return list size from getCount method
#Override
public int getCount() {
return eventList.size();
}
As the array list inside the adapter does not have 5 items(it has only one item) so try return the size of the list
simply use this code for custom adapter java
public class CustomAdapter extends SimpleAdapter {
ArrayList<HashMap<String,String>> arrayList;
Context context;
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> arrayList, int resource, String[] from ,int[] to) {
super(context, arrayList, resource, from, to);
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
View view = super.getView(position,convertView,parent);
RelativeLayout container = (RelativeLayout)
view.findViewById(R.id.container);
return view;
}
}
and this is WelcomeActivity
ArrayList<HashMap<String, String>> userList = "Define your list here"
String[] from = new String[]{"name","phone"};
int[] to = new int[]{R.id.name,R.id.phone};
ListView lv = (ListView) findViewById(R.id.list);
CustomAdapter customAdapter = new CustomAdapter(this,userList,R.layout.user_list_f,from,to);
lv.setAdapter(customAdapter);
it has been working for me perfectly
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.
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);
I am trying to use secionIndexer with fast scroll in list view.
I have implemented but
on scroll of list it should popup the current letter at which we have scrolled,
but its not showing that.
on debug mode I came to know that getSectipons() and getPositionForSection() are never called in my case ,
but in any other simple example that i tried from web it does make a call to those functions.
Pelase suggest me what to do
//##################
here is code of my adapter
//#######################
public class MyListAdapter extends ArrayAdapter<Object> implements SectionIndexer {
Activity context;
Object[] listData;
HashMap<String, Integer> alphaIndexer;
String[] sections;
public MyListAdapter(Activity context, Object[] objects) {
super(context, R.layout.new_invest_row, objects);
this.context = context;
listData = objects;
alphaIndexer = new HashMap<String, Integer>();
//changes here
ArrayList myArrayList = new ArrayList();
for (int ix=0; ix<objects.length; ix++) {
myArrayList.add(objects[ix]);
}
Collections.sort(myArrayList, new Comparator<HashMap<String, String>>(){
public int compare(HashMap<String, String> one, HashMap<String, String> two) {
return one.get("Name").compareToIgnoreCase(two.get("Name"));
}
});
listData = myArrayList.toArray();
//Arrays.sort(listData);
for (int i = listData.length - 1; i >= 0; i--) {
final HashMap<String, String> obj = (HashMap<String, String>)listData[i];
String element = obj.get("Name");
alphaIndexer.put(element.substring(0, 1).toUpperCase(), i);
}
Set<String> keys = alphaIndexer.keySet(); // set of letters
// Copy into a List for sorting
Iterator<String> it = keys.iterator();
ArrayList<String> keyList = new ArrayList<String>();
while (it.hasNext()) {
String key = it.next();
keyList.add(key);
}
Collections.sort(keyList);
// Convert to array
sections = new String[keyList.size()];
keyList.toArray(sections);
for(int c=0;c < sections.length;c++)Log.e("secction<"+c+">","+"+sections[c]);
Log.e("alphaIndexer","+"+alphaIndexer);
}
static class ViewHolder {
TextView txtName;
TextView txtOwner;
TextView txtStartDate;
TextView txtEndDate;
TextView txtStatus;
ImageView imgIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.new_invest_row, null, true);
holder = new ViewHolder();
**holder.txtName = (TextView) rowView.findViewById(R.id.invest_row_name);**
//my custom code here
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
#SuppressWarnings("unchecked")
final HashMap<String, String> obj = (HashMap<String, String>)listData[position];
String str = obj.get("Name");
if(null == str){
str = "";
}
holder.txtName.setText(str);
//#################
//my custom code here
return rowView;
}
public int getPositionForSection(int section) {
String letter = sections[section];
Log.e("alphaIndexer.get(letter)","+"+alphaIndexer.get(letter));
return alphaIndexer.get(letter);
}
public int getSectionForPosition(int arg0) {
// TODO Auto-generated method stub
return 1;
}
public Object[] getSections() {
return sections;
}
}
//#######################
I assume that in adapter when I am passing the textViewId its not taking the currect textVewId as the sectionIndexer functions are never called.
In the Layout new_invest_row I am getting custom row which have an icon and few textViews.
I am sorting the list on the basis of name of the Object that I am displaying in each row.
i want indexer to work on the name of the object.
Please help me with exact solution