I'm looking to some way for sort my items inside my listview. Which is a multi values Listview with 3 items for each row. I use a Custom ListViewAdapter to achieve this, but they are sorted in order of introduction inside the ArraysList. Something like:
1-2-3-4-5-6....
I want to inverse this order, having in top of my Listview the last item introduced:
6-5-4-3-2-1....
Here is my Custom ListViewAdapter:
public class ListViewAdapter extends BaseAdapter {
static class ViewHolder {
TextView number;
TextView elapsedTime;
TextView totalTime;
}
public static final String FIRST_COLUMN="First";
public static final String SECOND_COLUMN="Second";
public static final String THIRD_COLUMN="Third";
public ArrayList<HashMap<String, String>> list;
Activity activity;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.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
LayoutInflater inflater=activity.getLayoutInflater();
final ViewHolder viewHolder;
if(convertView == null){
convertView = inflater.inflate(R.layout.timer_row, null);
viewHolder = new ViewHolder();
viewHolder.number = (TextView) convertView.findViewById(R.id.number);
viewHolder.elapsedTime = (TextView) convertView.findViewById(R.id.elapsed_time);
viewHolder.totalTime =(TextView) convertView.findViewById(R.id.total_time);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map=list.get(position);
viewHolder.number.setText(map.get(FIRST_COLUMN));
viewHolder.elapsedTime.setText(map.get(SECOND_COLUMN));
viewHolder.totalTime.setText(map.get(THIRD_COLUMN));
return convertView;
}
}
And here is how I call it in my activity:
//ListView Adapter
mListviewLayout = (RelativeLayout)v.findViewById(R.id.listview_times_layout);
mTimesListview = (ListView)v.findViewById(R.id.times_listview);
mTimesArrayList = new ArrayList<HashMap<String,String>>();
mListViewAdapter= new ListViewAdapter(mActivity, mTimesArrayList);
mTimesListview.setAdapter(mListViewAdapter);
Finally, here is how I introduce items inside the Hashmap:
btnNextCicle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isTimerPaused()) {
onTimerStop();
} else {
mListviewLayout.setVisibility(View.VISIBLE);
mCiclesCounter++;
HashMap<String, String> newEntry = new HashMap<String, String>();
newEntry.put(ListViewAdapter.FIRST_COLUMN, "#" + mCiclesCounter);
newEntry.put(ListViewAdapter.SECOND_COLUMN, Util.getTimeForTimer(mElapsedCicleTime));
newEntry.put(ListViewAdapter.THIRD_COLUMN, Util.getTimeForTimer(mTimeInMilliseconds));
mCicleStartTime = SystemClock.elapsedRealtime();
mTimesArrayList.add(newEntry);
}
}
});
You can subclass HashMap<String, Sting> and make it implements Comparable. Then you can use Arrays.sort(yourComparable) to sort the array the way you want.
Related
Hi i have problem with my adapter, i don't know how to refresh my data in ListView when i use adapter.notifyDataSetChanged() after data changing nothing happen. I wonder if i have to override notifyDataSetChanged() in this class. I hope you will help me.
Here is my adapter class:
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth;
public static final String FIRST_COLUMN="First";
public static final String SECOND_COLUMN="Second";
public static final String THIRD_COLUMN="Third";
public static final String FOURTH_COLUMN="Fourth";
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.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
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.lista_wlasnych_spolek, null);
txtFirst=(TextView) convertView.findViewById(R.id.nazwa_spolki);
txtSecond=(TextView) convertView.findViewById(R.id.wartosc_akt);
txtThird=(TextView) convertView.findViewById(R.id.wartosc_kupna);
txtFourth=(TextView) convertView.findViewById(R.id.wartosc_calosci);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));
txtFourth.setText(map.get(FOURTH_COLUMN));
return convertView;
}
}
here im adding my fragment class which use this adapter:
public class Tab2Fragment extends Fragment {
private ArrayList<HashMap<String, String>> list;
public static final String FIRST_COLUMN="First";
public static final String SECOND_COLUMN="Second";
public static final String THIRD_COLUMN="Third";
public static final String FOURTH_COLUMN="Fourth";
public ListViewAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.spolki_portfel, container, false);
ListView listView=(ListView) v.findViewById(R.id.listView1);
list=new ArrayList<HashMap<String,String>>();
LayoutInflater inflater1 = getActivity().getLayoutInflater();
View header = inflater1.inflate(R.layout.naglowek_wlasne_spolki, listView, false);
listView.addHeaderView(header);
for(int i = 0 ; i < MainActivity.zmienne.lista_moich_spolek.size();i++){
dodaj_spolke(MainActivity.zmienne.lista_moich_spolek.get(i).nazwa,MainActivity.zmienne.lista_moich_spolek.get(i).wartosc_aktualna,MainActivity.zmienne.lista_moich_spolek.get(i).ilosc,MainActivity.zmienne.lista_moich_spolek.get(i).cena_kupna);
}
adapter=new ListViewAdapter(getActivity(), list);
listView.setAdapter(adapter);
//THIS INCREASE VALUE
MainActivity.zmienne.lista_moich_spolek.get(0).cena_kupna++;
adapter.notifyDataSetChanged();
//CHECKING IF VALUE IS HIGHER
System.out.println("cena " + MainActivity.zmienne.lista_moich_spolek.get(0).cena_kupna);
return v;
}
Not exactly, but you're probably not actually updating the adapter's list. Make a method in your adapter that looks like this
public void updateItems(ArrayList<HashMap<String, String>> newList) {
list.clear();
list.addAll(newList);
this.notifyDataSetChanged();
}
Then call this from wherever you have the adapter set up
mAdapter.updateItems(newList)
Your problem might be because you don't have the right Adapter class. Try this one, I didn't had time to test it but it should work, also call notifiyDataSetChanged() after adding new elements to that list.
public class ListViewAdapter extends ArrayAdapter<HashMap<String, String>> {
public ArrayList<HashMap<String, String>> list;
private Activity activity;
public static final String FIRST_COLUMN="First";
public static final String SECOND_COLUMN="Second";
public static final String THIRD_COLUMN="Third";
public static final String FOURTH_COLUMN="Fourth";
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
super(activity, R.layout.lista_wlasnych_spolek, list);
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public HashMap<String, String> getItem(int position) {
// TODO Auto-generated method stub
return list.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) {
ListViewHolder listViewHolder;
if(convertView == null){
listViewHolder = new ListViewHolder();
convertView = activity.getLayoutInflater().inflate(R.layout.lista_wlasnych_spolek, null);
listViewHolder.txtFirst = (TextView) convertView.findViewById(R.id.nazwa_spolki);
listViewHolder.txtSecond = (TextView) convertView.findViewById(R.id.wartosc_akt);
listViewHolder.txtThird = (TextView) convertView.findViewById(R.id.wartosc_kupna);
listViewHolder.txtFourth = (TextView) convertView.findViewById(R.id.wartosc_calosci);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ListViewHolder) convertView.getTag();
}
HashMap<String, String> map=list.get(position);
listViewHolder.txtFirst.setText(map.get(FIRST_COLUMN));
listViewHolder.txtSecond.setText(map.get(SECOND_COLUMN));
listViewHolder.txtThird.setText(map.get(THIRD_COLUMN));
listViewHolder.txtFourth.setText(map.get(FOURTH_COLUMN));
return convertView;
}
public class ListViewHolder {
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth;
}
}
Ok, im sorry for wasting your time it was my fault i missed that i was changing source of data but no exacly ListView I should change list.get(0).put("Fourth", "5"); but i was changing MainActivity.zmienne.lista_moich_spolek.get(0).cena_kupna++; and I wondered why it didn't work.
Please any one help how to sort images by name.Here am sharing my code.please any one help.
Here am showing images with grid and list .How to sort images by name in grid and list view.Here am using menu by selecting sort by name and sort by size.
// Main Activity
public class MainActivity extends ActionBarActivity {
public RelativeLayout mainLayout;
View gridView,listView;
CountryAdapterList customListAdapter;
CountryAdapter cutomArrayAdapter;
public int swithNo=0;
public String[] country_Names;
public RelativeLayout relativeLayout;
public int[] country_Images = {R.drawable.banglades, R.drawable.bangladesh,
R.drawable.brazi, R.drawable.brazil, R.drawable.chin,
R.drawable.china, R.drawable.indi, R.drawable.india,
R.drawable.indonesi, R.drawable.indonesia, R.drawable.japa,
R.drawable.japan, R.drawable.nigeri, R.drawable.nigeria,
R.drawable.pakista, R.drawable.pakistan, R.drawable.russi,
R.drawable.russia, R.drawable.unitedstate,
R.drawable.unitedstates };
public String[] country_Name_Sort = { "Bangladesh A", "Pakistan",
"Brazil A", "Brazil", "China A","Bangladesh", "China", "India A", "India",
"Indonesia A", "Russia","Indonesia", "Japan A", "Japan", "Nigeria A",
"Nigeria", "Pakistan A", "Russia A",
"UnitesStates A", "UnitesStates" };
public float[] country_Image_size = {1.36f , 1.36f, 4.12f, 4.12f, 1.47f,
1.47f, 1.79f, 1.79f, 0.299f, 0.299f, 1.50f, 1.50f, 0.285f, 0.285f,
1.85f, 1.85f, 0.330f, 0.330f, 3.42f, 3.42f };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
relativeLayout = new RelativeLayout(this);
customListAdapter = new CountryAdapterList(getApplicationContext(),
country_Name_Sort, country_Image_size, country_Images);
cutomArrayAdapter=new CountryAdapter(getApplicationContext(), country_Name_Sort, country_Image_size, country_Images);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
relativeLayout.setLayoutParams(rlp);
gridView = getLayoutInflater().inflate(R.layout.activity_deatails_grid,
null);
listView = getLayoutInflater().inflate(R.layout.activity_main_listview,
null);
setViewUpdate(swithNo);
((AdapterView<ListAdapter>) gridView).setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i=new Intent(getApplicationContext(),CountryDetailsScreen.class);
i.putExtra("Position", position);
i.putExtra("Country_Name", country_Name_Sort);
i.putExtra("Country_image", country_Images);
i.putExtra("Country_Image_size", country_Image_size);
startActivity(i);
}
});
((AdapterView<ListAdapter>) listView).setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),CountryDetailsScreen.class);
i.putExtra("Position", position);
i.putExtra("Country_Name", country_Name_Sort);
i.putExtra("Country_image", country_Images);
i.putExtra("Country_Image_size", country_Image_size);
startActivity(i);
}
});
}
private void sortAscending () {
List<String> sortedMonthsList = Arrays.asList(country_Name_Sort);
Collections.sort(sortedMonthsList);
country_Name_Sort = (String[]) sortedMonthsList.toArray();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menu.add(1, 1, 0, "Grid View");
menu.add(1, 2, 1, "List View");
menu.add(2, 3, 2, "Sort By Name");
menu.add(2, 4, 3, "Sort By Size");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case 1:
Log.d("SwithNo", "One");
swithNo=0;
setViewUpdate(swithNo);
break;
case 2:
Log.d("SwithNo", "Two");
swithNo=1;
setViewUpdate(swithNo);
break;
case 3:
Log.d("SwithNo", "Three");
sortAscending();
for(int i=0;i<country_Name_Sort.length;i++)
{
Log.e("Assending ", " "+country_Name_Sort[i]);
}
((ListView) listView).setAdapter(customListAdapter);
listView.invalidate();
setViewUpdate(swithNo);
break;
case 4 : Log.d("Switch", "Four");
}
return true;
}
public void setViewUpdate(int k)
{
((GridView) gridView).setAdapter(cutomArrayAdapter);
((ListView) listView).setAdapter(customListAdapter);
relativeLayout.removeAllViews();
if(k==0)
{
relativeLayout.addView(gridView);
}
else
{
relativeLayout.addView(listView);
}
setContentView(relativeLayout);
}
}
class Country {
int imageId;
String countryName;
Country(int imageId, String countyName) {
this.imageId = imageId;
this.countryName = countyName;
}
}
class CountryAdapter extends BaseAdapter {
ArrayList<Country> list;
Context context;
String[] country_Name_Sort;
CountryAdapter(Context context,String[] country_Name_Sort,float[] country_Image_size,int[] country_Images) {
this.context = context;
this.country_Name_Sort=country_Name_Sort;
list = new ArrayList<Country>();
/*Resources resource = context.getResources();
String[] country_Names = resource.getStringArray(R.array.coutry_names);*/
for (int i = 0; i < country_Name_Sort.length; i++) {
Country country = new Country(country_Images[i], country_Name_Sort[i]);
list.add(country);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
class ViewHolder {
ImageView county_Image;
TextView country_Name;
ViewHolder(View v) {
county_Image = (ImageView) v.findViewById(R.id.imageView);
country_Name = (TextView) v.findViewById(R.id.countryName);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View row = convertView;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.single_item, parent, false);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
}
Country cntry = list.get(position);
viewHolder.county_Image.setImageResource(cntry.imageId);
viewHolder.country_Name.setText(cntry.countryName);
return row;
}
}
class CountryAdapterList extends BaseAdapter {
ArrayList<Country> list;
Context context;
String[] country_Name_Sort;
int[] country_Images;
CountryAdapterList(Context context,String[] country_Name_Sort,float[] country_Image_size,int[] country_Images) {
this.context = context;
this.country_Name_Sort=country_Name_Sort;
this.country_Images=country_Images;
list = new ArrayList<Country>();
for (int i = 0; i < country_Name_Sort.length; i++) {
Country country = new Country(country_Images[i], country_Name_Sort[i]);
list.add(country);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
class ViewHolder {
ImageView county_Image;
TextView country_Name;
ViewHolder(View v) {
county_Image = (ImageView) v.findViewById(R.id.imageViewList);
country_Name = (TextView) v.findViewById(R.id.countryNameList);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View row = convertView;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.single_item_listview, parent, false);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
}
Country cntry = list.get(position);
viewHolder.county_Image.setImageResource(cntry.imageId);
viewHolder.country_Name.setText(cntry.countryName);
return row;
}
}
you should implement Java's Comparator.
ListView list;
//fill list here.
Collections.sort(list, new Comparator<String>() {
public int compare(final String a, final String b) {
return a.compareTo(b));
}
});
you can compare objects too, using their properties.
public int compare(final LatLong a, final LatLong b) {
return a.latitude.compareTo(b.latitude));
}
By using array sorting you can sort your image names in your application
//String array
String[] strNames = new String[]{"John", "Alex", "Chris", "Williams", "Mark", "Bob"};
sort String array using sort method
Arrays.sort(strNames);
Output of above given Java Sort String Array example would be
String array sorted (case sensitive)
Alex
Bob
Chris
John
Mark
Williams
In the same way, before setting your array data to your lisyt view you can sort it by using Arrays.sort(strNames);
hope it helps
I have a LinkedList HashMap List<HashMap<String, String>>that I have created, I'm trying to send it to a custom adapter that I found but it is for a Map. What the best way to convert it to accept LinkedList Hashmap?
public class CustomListOutageAdapter extends BaseAdapter {
private final ArrayList mData;
public CustomListOutageAdapter( List<HashMap<String, String>> map) {
mData = new ArrayList();
mData.add(map);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public HashMap.Entry<String, String> getItem(int position) {
return (HashMap.Entry) mData.get(position);
}
#Override
public long getItemId(int position) {
// TODO implement you own logic with ID
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View result;
if (convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.mylistoutagedetails, parent, false);
} else {
result = convertView;
}
HashMap.Entry<String, String> item = getItem(position);
// TODO replace findViewById by ViewHolder
((TextView) result.findViewById(R.id.name)).setText(item.getKey());
((TextView) result.findViewById(R.id.item)).setText(item.getValue());
return result;
}
}
I want to display my JSON into gridview, before it.. i displayed my JSON into ListView, and it works. but in BaseAdapter, i don't know how to send my JSON that I have put into ArrayList into Base Adapter
so this is my source code :
Activity :
public class MainActivity extends ListActivity {
List AgenList = new ArrayList();
boolean boolStatusKoneksi=true;
private ProgressDialog Dialog;
protected Context applicationContext;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AgenAsyncTask().execute();
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new AgenAdapter(this));
}
public class AgenAsyncTask extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
Dialog = new ProgressDialog(MainActivity.this);
Dialog.setMessage("Mohon Tunggu sebentar...");
Dialog.setIndeterminate(false);
Dialog.setCancelable(true);
Dialog.show();
}
protected String doInBackground(String... args) {
String url = ("http:10.10.2/selectAgent.htm");
try{
JSONParser j=new JSONParser();
JSONArray jsonArray = j.takeJson(url);;
for(int i =0; i<jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
if (c.has("atasan"))
map.put("atasan", c.get("atasan").toString());
if (c.has("nama_agen"))
map.put("nama_agen", c.get("nama_agen").toString());
if (c.has("kode_agen"))
map.put("kode_agen", c.get("kode_agen").toString());
if (c.has("no_aaji"))
map.put("no_aaji", c.get("no_aaji").toString());
if (c.has("jenis"))
map.put("jenis", c.get("jenis").toString());
AgenList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
}
}
This is my BaseAdapter :
public class AgenAdapter extends BaseAdapter {
public AgenAdapter(MainActivity mainActivity) {
}
#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;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layout = getLayoutInflater();
View view= layout.inflate(R.layout.list_item,parent,false);
TextView ATASAN = (TextView) findViewById(R.id.atasan);
TextView NAMA_AGEN= (TextView) findViewById(R.id.nama_agen);
TextView KODE_AGEN= (TextView) findViewById(R.id.kode_agen);
TextView NO_AAJI= (TextView) findViewById(R.id.no_aaji);
TextView JENIS= (TextView) findViewById(R.id.jenis);
return view;
}
}
}
As you see, i have ArrayList named as = AgenList but i haven't put it into my BaseAdapter.
make a parametrized constructor and pass your array list into its paramerts. so your class will be like
public class AgenAdapter extends BaseAdapter {
List<yourObj> list;
Activity a;
public AgenAdapter(Activity activity,List<yourObj> list) {
this.a=activity;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();///////return size of list
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;///// dont return null here
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;/////////return position as itemID
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layout = getLayoutInflater();
View view= layout.inflate(R.layout.list_item,parent,false);
TextView ATASAN = (TextView) findViewById(R.id.atasan);
TextView NAMA_AGEN= (TextView) findViewById(R.id.nama_agen);
TextView KODE_AGEN= (TextView) findViewById(R.id.kode_agen);
TextView NO_AAJI= (TextView) findViewById(R.id.no_aaji);
TextView JENIS= (TextView) findViewById(R.id.jenis);
return view;
}
}
try this.
gridview.setAdapter(new AgenAdapter(this), AgenList);
and use this line in your onPostExecute() instead of onCreate()
Like this:
#Override
protected void onPostExecute(String file_url) {
gridview.setAdapter(new AgenAdapter(this), AgenList);
}
Have a look at ArrayAdapter. It contains all of the implementation for an Adapter based on an ArrayList.
Make your adapter a subclass of ArrayAdapter, giving a parametrised type. Yours in this case being Map<String, String>
public class ResultAdapter extends ArrayAdapter<Map<String,String>> {
private int mResource;
/**
* #param context
* #param resource
*/
public ResultAdapter(Context context, int resource, ArrayList<Map<String,String>> dataList) {
super(context, resource, dataList);
this.mResource = resource;
}
...
}
Override the getView method of the ArrayAdapter to use to set the data given to the views.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
// If the view is already inflated, reuse it.
// Else inflate the view
if (convertView != null) {
view = convertView;
} else {
//inflate view
final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(mResource, parent, false);
}
TextView ATASAN = (TextView) findViewById(R.id.atasan);
...
//Get data here
Map<String, String> item = getItem(position);
//Set data to the View's e.g.
ATASAN.setText(item.get("ATASAN"));
...
return view;
}
I have a custom listview with custom adapter extending BaseAdapter if i add items to this list view in OnCreate method they show up in list, but if i add them from other methods like a packet listener method then items do not show up , on the screen below this listview there is a textbox if i select textbox to entertext using virtual keyboard immediately the listview gets populated with previousely inserted items which didnt show up. This activity is a chat window basically
I have tried calling notifyDataSetChanged, invalidate on Layout or on listview but nothing helped.
What i think is i need to have a way to refresh activity , as same thing must be happening when the virtual keyboard pops up .
Help will be highly appreciated
Thanks
Code:
package com.arounds;
public class ChatActivity extends Activity implements OnClickListener,PacketListener{
private ListView chatView;
private ChatListViewCustomAdapter adapter;
private String user;
private XMPPConnection connection;
private Conversation conv;
private ChatActivity selfRef = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_win);
AroundApplication app = (AroundApplication) this.getApplicationContext();
connection = app.getConnection();
chatView = (ListView) findViewById(R.id.conversationList);
adapter = new ChatListViewCustomAdapter(this);
chatView.setAdapter(adapter);
// set send btn listener
ImageButton send = (ImageButton)findViewById(R.id.imgBtnSend);
send.setOnClickListener(this);
ImageButton smiley = (ImageButton)findViewById(R.id.imgBtnSmiley);
smiley.setOnClickListener(this);
// get the parameter passed by previouse activity
Bundle b = this.getIntent().getExtras();
String temp = b.getString("user");
user = temp;
TextView v = (TextView)this.findViewById(R.id.txtViewTitle_chat);
v.setText(temp);
v = (TextView)this.findViewById(R.id.txtViewDescription_chat);
temp = b.getString("status");
v.setText(temp);
//chatView.setOnItemClickListener(this);
HashMap convs = app.getConversations();
if(convs.containsKey(user) == true)
conv = (Conversation) convs.get(user);
else {
conv = new Conversation();
convs.put(user,conv);
}
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(this,filter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgBtnSend)
{
EditText msg = (EditText)this.findViewById(R.id.editChat);
String s = msg.getText().toString();
Message message = new Message(user, Message.Type.chat);
message.setBody(s);
connection.sendPacket(message);
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(s,currentDate));
adapter.addItem("I said",s,currentDate,Constants.SEND_LIST_TYPE);
//adapter.notifyDataSetChanged();
}
else
{
//View view = this.findViewById(R.id.linerLayoutChat);
chatView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("in");
Message message = (Message) packet;
if (message.getBody() != null) {
System.out.println("in1");
String fromName = StringUtils.parseBareAddress(message.getFrom());
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(message.getBody(),currentDate));
adapter.addItem(fromName+" said",message.getBody(),currentDate,Constants.REC_LIST_TYPE);
//chatView.postInvalidate();
}
}
}
Adapter class:
public class ChatListViewCustomAdapter extends BaseAdapter
{
public ArrayList<ChatListItem> items;
public Activity context;
public LayoutInflater inflater;
public Boolean temp=false;
public ChatListViewCustomAdapter(Activity context) {
super();
this.context = context;
this.items = new ArrayList<ChatListItem>();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#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;
}
public static class ViewHolder
{
TextView txtViewTitle;
TextView txtViewDescription;
TextView txtViewDate;
}
public void addItem(String title,String desc,String d,int type)
{
ChatListItem item = new ChatListItem(title,desc,d,type);
items.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ChatListItem item = items.get(position);
ViewHolder holder;
System.out.println("Title:"+item.title+" type:"+item.type);
if(convertView==null)
{
holder = new ViewHolder();
int type = this.getItemViewType(position);
if(type == 0)
{
convertView = inflater.inflate(R.layout.list_item_even, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleEven);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionEven);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateEven);
}
else
{
convertView = inflater.inflate(R.layout.list_item_odd, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleOdd);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionOdd);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateOdd);
}
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(item.title);
holder.txtViewDescription.setText(item.desc);
holder.txtViewDate.setText(item.date);
return convertView;
}
#Override
public int getItemViewType(int position) {
ChatListItem item = items.get(position);
return item.type;
}
#Override
public int getViewTypeCount() {
return 2;
}
}
Handle all the updates within your Adapter and ensure you invoke notifyDataSetChanged() after you update it (within your Adapter)?
In cases where notifyDataSetChanged() does not work, re-set the adapter on the ListView by calling ListView.setAdapter() with the same Adapter again. This should refresh the view.
the only thing I can see not right are these methods:
#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;
}
These methods should return proper values.
items.get(position) and position respectively.