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
Related
I have a listView that shows data that in sqlite, I'm using baseAdapter.
The list row contains text and button.
I press the button in each row to give me each data of the selected row from the database (not pressing the row itself)
This is code of listView:
tipsList = new ArrayList<HashMap<String, String>>();
list = (ListView) rootView.findViewById(R.id.tipList);
do {
map = new HashMap<String, String>();
map.put(DAO.TIP_ID, c.getString(c.getColumnIndex(c.getColumnName(0))));
map.put(DAO.TIP_CONTENT, c.getString(c.getColumnIndex(c.getColumnName(1))));
map.put(DAO.TIP_FAVORITE, c.getString(c.getColumnIndex(c.getColumnName(2))));
// adding HashList to ArrayList
tipsList.add(map);
} while (c.moveToNext());
tipsAdapter = new TipsAdapter(getActivity(), tipsList, tipType, db);
list.setAdapter(tipsAdapter);
And this is code of TipsAdapter.java
public class TipsAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
Context context;
Typeface tf;
String tipID;
String tipText;
String isFavorite;
DAO db;
HashMap<String, String> quote;
int selectedTipType;
public TipsAdapter(Activity a, ArrayList<HashMap<String, String>> d, int selectedTipType, DAO db) {
activity = a;
data = d;
context = a;
this.selectedTipType = selectedTipType;
this.db = db;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ==============================================================================
public int getCount() {
return data.size();
}
// ==============================================================================
public Object getItem(int position) {
return 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.tip_list_row, null);
TextView tipContent = (TextView) vi.findViewById(R.id.tip_text); // tip
final ImageView favStar = (ImageView) vi.findViewById(R.id.favorite_star);
tf = Typeface.createFromAsset(activity.getAssets(), "fonts/bauhausm_0.ttf");
tipContent.setTypeface(tf);
quote = new HashMap<String, String>();
quote = data.get(position);
tipText = quote.get(DAO.TIP_CONTENT).trim();
favStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want here get all data like tipId - tipText - tipFavotite of the current row in toast
}
});
return vi;
}
}
How to get the data of the current row when press the button?
Hope anyone got my mean.
Thanks in advance.
Maybe you can set the tag of your button.
favStar.setTag(position);
favStar.setOnClickListener (new OnClickListener()
{
#Override
public void onClick(View view) {
int position = (int) view.getTag();
HashMap<String, String>() quote = data.get(position);
String tipText = qout.get(DAO.TIP_CONTENT);
String tipContent = ......;
}
}
I Solved it by myself by making position as final and put quote = data.get(position); inside the listener of the button.
I have save about 6 rows saved in shared preference and each row contains name, description, price etc. I have List in which i have to populate name, description, price in each row retrieved from shared preferences. How to get all data in row and populate list?
I have done
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater=null;
private ArrayList<HashMap<String, Object>> data;
//public ImageLoader imageLoader;
int i=0;
public LazyAdapter(Activity a) {
activity = a;
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 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.order_list, null);
TextView orderDishDescription = (TextView)vi.findViewById(R.id.orderDishDescription);
TextView OrderDishName = (TextView)vi.findViewById(R.id.OrderDishName);
TextView OrderDishPrice = (TextView)vi.findViewById(R.id.OrderDishPrice);
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image_order);
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); /
//HashMap<String, Object> song = new HashMap<String, Object>();
// song = data.get(position);
Log.i("iiiiii "," " +i++);
// Log.i("objj.Get_O_Id() ",objj.Get_O_Id());
// Log.i("objj.GetProductName() ",objj.GetProductName());
// Log.i("objj.GetDescription() ",objj.GetDescription());
//
OrderDishPrice.setText(OrderSharedPrefences.getDish_Price(getApplicationContext()));
OrderDishName.setText(OrderSharedPrefences.getUserName(getApplicationContext()));
orderDishDescription.setText(OrderSharedPrefences.getDish_Description(getApplicationContext()));
//imageview.setImageBitmap(objj.GetImage());
return vi;
}
}
Your Adapter is Okay just make set data from your Activity class, something like that-
First get data from preference in set and set into array-list then set into list-view.
EDIT
Set prefrence as like that-
SharedPreferences.Editor sEdit = sPrefs
.edit();
sEdit.putString("NAME", content);
sEdit.putStringSet("args", listArraySet);
sEdit.commit();
And get any where like that-
sPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
listArraySet=new HashSet<String>();
listArraySet=sPrefs.getStringSet(name1,new HashSet<String>());
list=new ArrayList<String>(listArraySet);
ArrayAdapter<String> ao=new ArrayAdapter<String>(this, R.layout.songs_list_item, R.id.songTitle, list);
lv.setAdapter(ao);
whole code for set into listview-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs_list);
list = new ArrayList<String>();
lv=(ListView)findViewById(R.id.listView1);
sPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
listArraySet=new HashSet<String>();
listArraySet=sPrefs.getStringSet(name1,new HashSet<String>());
list=new ArrayList<String>(listArraySet);
ArrayAdapter<String> ao=new ArrayAdapter<String>(this, R.layout.songs_list_item, R.id.songTitle, list);
lv.setAdapter(ao);
//-------------------------CLICK ON LIST ITEM_-----------------------
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int index = parent.getPositionForView(view);
String filename = list.get(index);
}
});
}
}
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 });
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
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.