I am trying to update the content of my listview by adding stuff to it. Although the listview does update its contents the size still stays the same for some reason. So for example, if the original listview contains A, B, Y, Z and I add C and D to it, the updated list view will be: A, B, C, D. What am I doing wrong?
Here is some relavent code:
//in main activity...
//additionalSongs is an arraylist
addAdditionalSongs(additionalSongs);//add the additional songs to the main list
songTabFragment = new SongTabFragment();//update the list on the screen
...
private void addAdditionalSongs(ArrayList<Song> additionalSongs){
for(int i = 0; i < additionalSongs.size(); i++) {
songList.add(additionalSongs.get(i));
}
}
SongTabFragment class
public class SongTabFragment extends Fragment {
private ListView songView;
private Context context;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.song_tab_layout, container, false);
songView = (ListView) rootView.findViewById(R.id.song_list); //get a reference to the ListView created in song_tab_layout
SongAdapter theAdapter = new SongAdapter(context, MainActivity.getSongArray());
songView.setAdapter(theAdapter); //pass the ListView object the appropriate adapter
return rootView;
}
}
SongAdapter class
public class SongAdapter extends BaseAdapter {
private ArrayList<Song> songArray;
private LayoutInflater songInf;
public SongAdapter(Context c, ArrayList<Song> grabbedSongArray){
songArray = grabbedSongArray;
songInf = LayoutInflater.from(c);
}
#Override
public int getCount() {
return songArray.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = (LinearLayout)songInf.inflate(R.layout.song, parent, false);
//layout for each individual song in the list. Uses song.xml
TextView songView = (TextView)listLayout.findViewById(R.id.song_title);
TextView artistView = (TextView)listLayout.findViewById(R.id.song_artist);
Song currentSong = songArray.get(position);
songView.setText(currentSong.getTitle()); //pass data to textView objects in each list item
artistView.setText(currentSong.getArtist());
listLayout.setTag(position); //use the song's position in list as a tag
return listLayout;
}
}
It might be that the SongTabFragment is not being updated. Instead of accessing your song array via the MainActivity
MainActivity.getSongArray()
Why not add a method in your fragment to update the arraylist in the SongAdapter and then notify the list view that the data set has changed so that it will recreate the view based on the new array list.
Example
In fragment class
// Fragment code
public void updateAdapterArray(ArrayList<Songs> adapter) {
((SongAdapter) mListView.getAdapter()).setSongs(adapter);
}
In adapter class
//Adapter code
public void setSongs(ArrayList<Songs> adapter) {
this.songList = adapter;
notifyDataSetChanged();
}
In mainactivity
// your mainactivity code
SongTabFragment songFragment = (SongTabFragment) mFragmentManager.findFragmentById(R.id.fragContainer);
songFragment.updateAdapterArray(newSongList);
Check your getCount() method,
#Override
public int getCount() {
return list.getSize(); //it should return size of list. Not 4
}
Are you updating the item count in your list view? If the listview still only thinks there are 4 items in the list it will only display 4 items. You have to update the value the getCount() returns.
Related
What i am doing:: I have a horizontal listview as shown below for which i am populating items dynamically
What is happening:: Since its a dynamically created listview onorientation change the checked items are unchecked
Question: How can i collected the checked items from the adapter and recheck the selected things on orientation change
AdpBufTypeSearch.java
public class AdpBufTypeSearch extends BaseAdapter{
private HashMap<String, String> objHashBufType;
SparseBooleanArray mBufTypeArr = new SparseBooleanArray();
private ArrayList<HashMap<String, String>> objListBufType;
Context mContext;
public AdpBufTypeSearch(Context _mContext,ArrayList<HashMap<String, String>> _objListBufType) {
mContext=_mContext;
objListBufType=_objListBufType;
}
#Override
public int getCount() {
return objListBufType.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
//LOGIC:: result will be a set on which ones are selected Ex:: 0,1,2,4
public String getSelectedBuffetType() {
//This final value(strBufTypeId) is returned when we access from class
String strBufTypeId="";
for(int i=0;i<objListBufType.size();i++) {
HashMap<String, String> objHashBufType = objListBufType.get(i);
if(objHashBufType.get("selected")=="1") {
strBufTypeId=strBufTypeId+objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_ID);
strBufTypeId=strBufTypeId+",";
}
}
//remove the last "," in the string
if(strBufTypeId.lastIndexOf(",")>0)
strBufTypeId=strBufTypeId.substring(0, strBufTypeId.lastIndexOf(","));
return strBufTypeId;
}
/*LOGIC:: <HashMapObject(objHashBufType)> ==> their value of key(selected) is updated to "1" else key(selected) is updated to 0 */
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.adp_meal_type, null);
final TextView buf_type_name = (TextView) retval.findViewById(R.id.buf_type_name);
TextView buf_type_id=(TextView) retval.findViewById(R.id.buf_type_id);
ImageView buf_type_image=(ImageView) retval.findViewById(R.id.buf_type_image);
final LinearLayout imgBkgSelector=(LinearLayout) retval.findViewById(R.id.imgBkgSelector);
imgBkgSelector.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//LOGIC:: If Selected unselect it and if it is unselected select it
if(mBufTypeArr.get((Integer) imgBkgSelector.getTag())==true){
//INNER-LOGIC:: Background not selected
mBufTypeArr.put((Integer) imgBkgSelector.getTag(), false);
objHashBufType = objListBufType.get((Integer) imgBkgSelector.getTag());
objHashBufType.put("selected", "0");
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlack)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
else{
//INNER-LOGIC:: Background selected
mBufTypeArr.put((Integer) imgBkgSelector.getTag(), true);
objHashBufType = objListBufType.get((Integer) imgBkgSelector.getTag());
objHashBufType.put("selected", "1");
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlue)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
}
});
imgBkgSelector.setTag(position);
//Essential code for retain the Background check part on scroll of images
if(mBufTypeArr.get(position)==true){
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlue)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}else{
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlack)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
// Get the position
objHashBufType = objListBufType.get(position);
// Capture position and set results to the TextViews
//Capitilize the names
String capitalizedBufTypeName = WordUtils.capitalizeFully(objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_NAME), ' ');
buf_type_name.setText(capitalizedBufTypeName);
buf_type_id.setText(objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_ID));
Picasso.with(mContext)
.load(mContext.getString(R.string.URL_BUFFET_TYPE_IMAGE).trim()+objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_IMAGE).trim()).resizeDimen(R.dimen.filter_image_width,R.dimen.filter_image_height).centerCrop().into(buf_type_image);
return retval;
}
}
FrgMdSearch .java
public class FrgMdSearch extends Fragment {
private HashMap<String, String> objHashBufType;
private ArrayList<HashMap<String, String>> objListBufType=null;
private AdpBufTypeSearch bufTypeAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setting the adapter for buf images<---DYNAMIC VIEWS--->
setAdapterBufImages();
}
private void setAdapterBufImages() {
bufTypeAdapter=new AdpBufTypeSearch(getActivity(),objListBufType);
hListView.setAdapter(bufTypeAdapter);
}
}
You need to save the position of the checked item when orientation change occurs in your onSaveInstanceState method also create a getter method in your AdpBufTypeSearch adapter that returns the current position of the checked item and setter method to set the checked item.
sample:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", bufTypeAdapter.getCheckedPosition()); //getCheckedPosition must return the checked item position
}
In oncreateView of the fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setting the adapter for buf images<---DYNAMIC VIEWS--->
setAdapterBufImages(savedInstanceState);
}
private void setAdapterBufImages(Bundle savedInstanceState) {
bufTypeAdapter=new AdpBufTypeSearch(getActivity(),objListBufType);
if(savedInstanceState != null)
{
bufTypeAdapter.setCheckedItem(savedInstanceState.getInt("position")); //will set the checked item
}
hListView.setAdapter(bufTypeAdapter);
}
i have parsed Json data from the server. On which im showing all the data in listview and i have Load more option below the ListView. Now when i click load more option, this application reload whole list and did not show previous list data. Please help me find out the solution. Here is footer view click listener :
lFooter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
page += 1;
new ParseIssues().execute();
listView.removeFooterView(v);
}
});
in above code ParseIssues class parse json values and displays all the data in ListView Here is code for onPostExecute of AsynkTask class :
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(page < totalPage){
listView.addFooterView(v);
}
listAdapter = new ListAdapterForSearch(activity, mainList);
listView.setAdapter(listAdapter);
// get listview current position - used to maintain scroll position
int currentPosition = listView.getFirstVisiblePosition();
listView.setSelection(currentPosition);
}
Here is BaseAdapter class:
public class ListAdapterForSearch extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ListAdapterForSearch(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = LayoutInflater.from(activity);
}
#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(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.list_row_item, null);
}
TextView title = (TextView)vi.findViewById(R.id.title);
HashMap<String, String> hash = new HashMap<String, String>();
hash = data.get(position);
title.setText(hash.get("title"));
return vi;
}
}
The answer to your question lies with the variable "mainList", which the adapter uses. You need to add the new data to it, basically this list needs to contain all the data you want to show in your ListView.
You should set adapter on create, after that first add loaded data to mainlist(add new loaded data) & then after loading notify adapter like listadapter.notifydatachange()
Edit: Because every time you are creating adapter that's why you are facing this problem, instead after loading just notify your adapter..
Check in your code you may have clear your mainList.
I have ListView with items. I'm using XML to parse data. In that moment I parse data for one item in DetailsView. When I clicked on item, how to make DetailsView for items with SwipeViews beetween items? How to implement with ViewPager? I try to develop some examples, but didn't work. I would be grateful if someone help me.
So first create a Fragment for your detail. This is for a single detail. The detail that you'll swipe. So apply your layout to this.
#SuppressLint("ValidFragment")
public class Detail extends Fragment {
private final String detail;
public DetailView(String detail) {
this.detail = detail;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detailfragment, container, false);
TextView textView = (TextView) view.findViewById(R.id.detailText);
textView.setText(detail);
return view;
}
}
Now create your Activity. This is the Activity that you will go when you clicked. Now the code adds a Fragment for every detail.
public class Main extends FragmentActivity {
public static ViewPager mPager;
private MyAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPager = (ViewPager) findViewById(R.id.viewPager1);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
//The count of details. This will return 5 swipeable views.
return 5;
}
#Override
public Fragment getItem(int position) {
return new Detail("I'm a detail!");
}
}
}
This will create 5 details with text "I'm a detail!". Now, i assume you are using ArrayList that storing details. Then you can get the details like this:
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm, ArrayList<HashMap<String, String>> d) {
super(fm);
data = d;
}
#Override
public int getCount() {
return 5;
}
#Override
public Fragment getItem(int position) {
HashMap<String, String> map = new HashMap<String, String>();
map = data.get(position);
Log.d("", data.get(position).toString());
return new Detail(map.get('KeyForYourDetail'));
}
}
Also on your MainActivity change
mAdapter = new MyAdapter(getSupportFragmentManager());
to this
mAdapter = new MyAdapter(getSupportFragmentManager(), yourArrayList);
EDIT
Let's start from the beginning. First, you have your MainActivity which contains a ListView. In the ListView, you are calling items from ArrayList. When you click a item, you get the detail about it from (?). Now my above code can't do that. You have to do that your own first. After you get the detail, just replace the title part below. To summarize, the code i post should work if you can get the "detail", if you don't know how to get detail, then you should create another question.
return new Detail(title);
EDIT 2
OK, here is the other part. Below code is for FragmentActivity.
First, we need to declare our adapter and ViewPager.
public static ViewPager mPager;
private MyAdapter mAdapter;
ArrayList<HashMap<String, String>> detailList= new ArrayList<HashMap<String, String>>();
MyAdapter is the adapter that puts the details into ViewPager. To hold details, we also need an ArrayList as i declared above. Now, you said you don't have problem with parsing. So I'm skipping that part. While you're parsing, I assume you are using NodeList(i took that part from here)
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes
for (int i = 0; i < nl.getLength(); i++) {
String name = parser.getValue(e, KEY_NAME); // name child value
String cost = parser.getValue(e, KEY_COST); // cost child value
String description = parser.getValue(e, KEY_DESC); // description child value
}
Inside of your for loop, create a HashMap like this
HashMap<String, String> map = new HashMap<String, String>();
Remember while we were creating our ArrayList? It's object was HashMap. Now we are going to fill our data to map, then add map to ArrayList. (Again, this goes inside of for loop)
map.put(TAG_DETAIL, detail);
detailList.add(map);
Now this part is over, only thing left is setting the adapter.
mAdapter = new MyAdapter(getSupportFragmentManager(), detailList);
mPager.setAdapter(mAdapter);
And we are done! Let me explain what's going to happen next. Do you remember our adapter?
public MyAdapter(FragmentManager fm, ArrayList<HashMap<String, String>> d) {
super(fm);
data = d;
}
Here as you see, it takes a FragmentManger and an ArrayList with Hashmap inside of it. we set those with getSupportFragmentManager() and detailList. Adapter takes the detailList with details inside of it, then creates Fragments with it. I hope it was clear enough. If wasn't, ask again.
This is the code of MyAdapter.java:
public class MyAdapter extends ArrayAdapter {
ImageLoader imageLoader;
DisplayImageOptions options;
public MyAdapter(Context ctx, int textViewResourceId, List<NewsFeed> sites) {
super(ctx, textViewResourceId, sites);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
/*
* (non-Javadoc)
* #see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*
* This method is responsible for creating row views out of a StackSite object that can be put
* into our ListView
*/
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("Feed", "getView pos = " + pos);
// if(null == row){
// //No recycled View, we have to inflate one.
// LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// row = (RelativeLayout)inflater.inflate(R.layout.list_item, null);
// }
if (pos != 0){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.list_item, null);
}
else
{
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.list_first_item, null);
}
//Get our View References
final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
TextView titleTxt = (TextView)row.findViewById(R.id.titleTxt);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
//Initially we want the progress indicator visible, and the image invisible
indicator.setVisibility(View.VISIBLE);
iconImg.setVisibility(View.INVISIBLE);
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
indicator.setVisibility(View.INVISIBLE);
iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
imageLoader.displayImage(getItem(pos).getImgUrl(), iconImg,options, listener);
//Set the relavent text in our TextViews
titleTxt.setText(getItem(pos).getTitle());
return row;
}
}
Summary: I need a way to trigger my calculate() function within my main activity when an item is added or removed from my ListView
Background:
My android application fills a listview with list items. A list item contains a textview and an imagebutton (delete) that removes the item from the list on click. I use a custom adapter to keep track of changes in the list. This all works fine.
In my main acticity, some calculations take place based on the values in the list in a function called calulate(). I want to call this function whenever an item is added or deleted from the list. However, I don't know if this is possible and how to implement such a function.
I noticed that it is possible to add an observer using registerDataSetObserver() that will be notified when notifyDataSetChanged() is called. However, I'm not sure if this is what I need and how to implement this. Any help or suggestions are more than welcome.
Here is my CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
static final String TAG = "CustomListAdapter";
private Context context;
ArrayList <String> listArray;
LayoutInflater inflater;
public CustomListAdapter(Context context, List <String> inputArray) {
super();
this.context = context;
this.listArray = (ArrayList<String>) inputArray;
}
#Override
public int getCount() {
return listArray.size(); // total number of elements in the list
}
#Override
public String getItem(int i) {
return listArray.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View V = convertView;
if(V == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
V = vi.inflate(R.layout.selected_drug_list_item, null);
}
//place text in textview
String listItem = listArray.get(position);
TextView textView = (TextView) V.findViewById(R.id.selectedDrugName);
textView.setText(listItem);
ImageButton deleteSelectedDrugButton = (ImageButton) V.findViewById(R.id.deleteSelectedDrugButton);
deleteSelectedDrugButton.setTag(position);
//Listener for the delete button. Deletes item from list.
deleteSelectedDrugButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//re
Integer index = (Integer) view.getTag();
listArray.remove(index.intValue());
notifyDataSetChanged();
}
});
return V;
}
public void add(String input) {
listArray.add(input);
notifyDataSetChanged();
Log.v(TAG, input + " added to list");
}
public void remove(String input){
listArray.remove(input);
notifyDataSetChanged();
Log.v(TAG, input + " added to list");
}
}
Here is how my ListView is initialized in my onCreate() method.
selectionListView = (ListView) findViewById(R.id.selectionListView);
selectionAdapter = new CustomListAdapter(this,myListItems);
selectionListView.setAdapter(selectionAdapter);
If any other code fragment is required, I'll happily provide it.
You may create Interfece that will be implemented by Your Main Activity and passed to Adapter (eg. in constructor)
public interface SomeInterface
{
public void foo();
}
Add SomeInterface object in Your Adapter
SomeInterface responder=null;
public CustomListAdapter(Context context, List <String> inputArray, SomeInterface responder) {
super();
this.context = context;
this.listArray = (ArrayList<String>) inputArray;
this.responder=responder;
}
public void add(String input) {
listArray.add(input);
notifyDataSetChanged();
Log.v(TAG, input + " added to list");
responder.foo();
}
public void remove(String input){
listArray.remove(input);
notifyDataSetChanged();
Log.v(TAG, input + " added to list");
responder.foo();
}
and implements SomeInterface in Your MainActivity
public class MainActivity extends Activity implements SomeInterface
{
...
public void foo()
{
//do whatever
}
private initializeAdapter()
{
CustomListAdapter adapter=new Adapter(this, someArray, this);
}
}
You can create a callback interface with a simple method, like stuffHappened(). Then, let your activity implement that interface. Now you can add a constructor argument which has as type the callback interface, pass the activity in, keep it as a member variable on the adapter and call the stuffHappened() method whenever you need to send feedback to your activity.
I've listview in an activity and I want to append data at the top of it.When the activity loads the listview is populated.Now when the user clicks a button i am bringing additional data but i want this data to append at the top of the listview.How can I accomplish this?
I've the custom listview made using the baseAdapter .Heres my baseAdapter class:
public class LazyAdapterUserAdminChats extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String,String>> hashmap;
private static LayoutInflater inflater=null;
public LazyAdapterUserAdminChats(Activity activity,ArrayList<HashMap<String,String>> hashMaps)
{
this.activity=activity;
this.hashmap=hashMaps;
LazyAdapterUserAdminChats.inflater=(LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return hashmap.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
if(convertView==null)
view=inflater.inflate(R.layout.useradminchat,null);
TextView username=(TextView)view.findViewById(R.id.UAC_userNametext);
TextView messagetext=(TextView)view.findViewById(R.id.UAC_messagetext);
TextView messageDate=(TextView)view.findViewById(R.id.UAC_dates);
HashMap<String,String> map=hashmap.get(position);
username.setText(map.get(HandleJSON.Key_username));
messagetext.setText(map.get(HandleJSON.Key_messageText));
messageDate.setText(map.get(HandleJSON.Key_messageDate));
return view;
}
}
Here's how I set the adapter for listview function from my activity.
private void ShowListView(ArrayList<HashMap<String,String>> chat)
{
try
{
ListView lv=(ListView)findViewById(android.R.id.list);
adapter = new LazyAdapterLatestChats(this,chat);
lv.setAdapter(adapter);
}
catch(Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
First of all, don't use a hashmap to hold your data. You'd much rather use an ArrayList, because you're going to be iterating. Hashmaps are usually used for fast information retrieval, and usually not for iteration (this can be done, though, with an Iterator).
Next, create a method on LazyAdapterUserAdminChats to add things to the head of your arraylist.
Lastly, call notifyDataSetChanged when you add to the head of the arraylist.
Example:
public class LazyAdapterUserAdminChats extends BaseAdapter{
private Activity activity;
private ArrayList<MyObj> al;
private static LayoutInflater inflater=null;
public LazyAdapterUserAdminChats(Activity activity,ArrayList<MyObj> al)
{
this.activity=activity;
this.al=al;
LazyAdapterUserAdminChats.inflater=(LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// other methods
....
public void addToHead(MyObj m)
{
this.al.add(m, 0);
notifyDataSetChanged();
}
}
Your custom class can be anything you want. e.g.,
public class MyObj
{
String hashMapKey, hashMapValue;
}