How do i add search functionality in gridview in android? - java

My android app consists of a gridview with an image and a text below it. I am passing a array of strings into the textview. I want the edittext field to act as a search bar and filter the results.I have seen other questions relating this but they seem to filter an arraylist which is passed into a Listview. How do i filter an array of strings in a gridview?
I know i should add a a TextWatcher to listen for text changes on the EditText but after that how do i filter my data?
Here is my code
Mainactivity.java
public class MainActivity extends Activity {
EditText inputSearch;
GridView grid;
public static String[] Sname = {
"one",
"two",
"three",
"four",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGrid adapter = new CustomGrid(MainActivity.this, Sname);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + Sname[+position], Toast.LENGTH_SHORT).show();
}
});
inputSearch = (EditText) findViewById(R.id.editText);
}
}
CustomGrid.java
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] Sname;
public CustomGrid(Context c,String[] Sname) {
mContext = c;
this.Sname = Sname;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Sname.length;
}
#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 view, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(Sname[position]);
imageView.setImageResource(R.mipmap.image1);
return grid; }}

You can add your adapter ie CustomGrid a filter(String) method.
You also add a field String [] toDisplay in your adapter.
In your constructor you add toDisplay = Sname and in all your other methos you replace Snameby toDisplay
In the filter method create a new string array with only the string from Sname that match the desired string. Set this new array to toDisplay.
Then call the notifyDataSetChanged method on your CustomGrid
Example of filtering method :
public void filter(String toMatch) {
List<String> matches = new ArrayList<String>();
for (String string : Sname) {
if (string.matches(toMatch)) {//on whatever mathcing you feel to use
matches.add(string);
}
}
toDisplay = new String[matches.size()];
toDisplay = matches.toArray(toDisplay);
notifyDataSetChanged(); //update your grid view
}

Related

Start chronometer on each row of Listview in android

I have list items on one list layout among items i have there is a chronometer that i need to start on each row ,other items come from database, but when activity launches Chronometer stays on 00:00. Please help me , i did many research some tell me that in can use adapter but i am not familiar with it, i don't know if there is not another way to do it without using adapter .
MainActivity .java:
private ArrayList<HashMap<String, String>> userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView)findViewById(R.id.listView);
inflatedView =
getLayoutInflater().inflate(R.layout.payement_timing_list_adapter_view, null);
chronometer = (Chronometer)
inflatedView.findViewById(R.id.chronometer);
if (userList.size() != 0) {
//Set the User Array list in ListView
adapter = new SimpleAdapter(getApplicationContext(), userList, R.layout.payement_timing_list_adapter_view,
new String[]{"Driver_fullname", "plate_no", "parking_name"},
new int[]{R.id.drivername, R.id.plateno, R.id.pname});
myList.setAdapter(adapter);
}
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Log.d("My POSITION",""+position);
((Chronometer)inflatedView.findViewById(R.id.chronometer)).myList.
(position).start();
chronometer.start();
}
});
You will need to use a custom adapter for your ListView, and declare the Chronometer in the getView method for each row.
A custom adapter could be onle like this:
public class CustomAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> users;
Context context;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, ArrayList<HashMap<String, String>> usersList) {
// TODO Auto-generated constructor stub
users = usersList;
context=mainActivity;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
...
Chronometer cr;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
//Create a custom layout for your row view with the chronometer on it and get it here
rowView = inflater.inflate(R.layout.custom_row_item, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
...
holder.cr=(Chronometer) rowView.findViewById(R.id.chronometer);
cr.start();
holder.tv.setText("GET THE TEXT YOU NEED FROM USERS LIST HERE");
return rowView;
}
}
Then declare and use your custom adapter like:
CustomAdapter myAdapter = new CustomAdapter(YourActivity.this, userList);
myList.setAdapter(myAdapter);
Hope it helps :)

Can not identify the cause of Application crash

I have this following class which when runs and comes to a certain line in the class the application crashes. If i comment out that line the application runs well. When i look at the logcat i don't find any CausedBy Text. So can not figure out the cause of this crash. Someone please help me out to solve this.
public class Secondscreen extends Activity {
int total=0;
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter =null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
//Addition of item to arraylist
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
String pName = aController.getCart().getProducts(i).getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int pQuantity = aController.getCart().getProducts(i).getProductQuantity();
String pDisc = aController.getCart().getProducts(i).getProductDesc();
total = total + pPrice;
Listitem item=new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", ""+pQuantity);
Log.e("Intem's quantity", ""+item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""+arrayList.get(i).getQuantity());
}
showtotal.setText(""+total);
}
adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
TextView tv4=(TextView) view.findViewById(R.id.quantityView);
Button btn=(Button) view.findViewById(R.id.patternButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore=arrayList.get(position).getPrice();
total=total-tempstore;
arrayList.remove(position);
showtotal.setText(""+total);
ModelProducts tempProductObject = aController.getProducts(position);
aController.getCart().removeProducts(tempProductObject);
adapter.notifyDataSetChanged();
int cartSize2 = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText(""+arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(arrayList.get(position).getQuantity()); //<-this is the line which when gets executed causes the application to crash.
return view;
}
};
lv.setAdapter(adapter);
}
}
yes getQuantity() returns an int value
So change this
tv4.setText(arrayList.get(position).getQuantity());
to
tv4.setText(String.valueOf(arrayList.get(position).getQuantity()));
What happens is setText(int) looks for a Resource with the int value if not found you end up getting ResourceNotFoundException
What you want is setText(CharacterSequence) so you need use String.valueof(intvalue)

How to send ArrayList into BaseAdapter Android

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;
}

How to access elements in a ListView when long clicked

I am working on an application that has a ListView of movies. The list is declared as an array in strings.xml. It has elements, Title, Gross and Date Released. When a row is long clicked, it brings up a context menu that allows the user to edit said row or delete it. When the user picks Edit, he/she is brought to a 2nd screen with 3 Edit Text corresponding to Title, Gross and Date. The EditText fields are initialized with the data from the clicked row. Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] titleList = getResources().getStringArray(R.array.title_array);
String[] grossList = getResources().getStringArray(R.array.gross_array);
String[] dateList = getResources().getStringArray(R.array.date_array);
results = new ArrayList<Lab8_082588FetchDetails>();
for (int i = 0; i < titleList.length; i++) {
Lab8_082588FetchDetails sr = new Lab8_082588FetchDetails();
sr.setTitle(titleList[i]);
sr.setGross(grossList[i]);
sr.setDate(dateList[i]);
results.add(sr);
}
adapter = new SampleCustomAdapter(results);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
// places the contents of the XML to the menu
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
results.remove(info.position);
adapter.notifyDataSetChanged();
return true;
case R.id.edit:
System.out.println(info.id);
System.out.println(info.position);
Intent newData = new Intent(Lab8_082588.this, Lab8_082588Edit.class);
results.get(info.position);
TextView movieTitle = (TextView) findViewById(R.id.title);
TextView movieGross = (TextView) findViewById(R.id.gross);
TextView movieDate = (TextView) findViewById(R.id.date);
String startTitle = movieTitle.getText().toString();
String startGross = movieGross.getText().toString();
String startDate = movieDate.getText().toString();
newData.putExtra(Lab8_082588Edit.TITLE_STRING, startTitle);
newData.putExtra(Lab8_082588Edit.GROSS_STRING, startGross);
newData.putExtra(Lab8_082588Edit.DATE_STRING, startDate);
startActivityForResult(newData, Lab8_082588.EDIT_MOVIE);
return true;
default:
return super.onContextItemSelected(item);
}
}
For the Edit screen:
public class Lab8_082588Edit extends Activity {
public static final String TITLE_STRING = "TITLE_STRING";
public static final String GROSS_STRING = "GROSS_STRING";
public static final String DATE_STRING = "DATE_STRING";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addedit);
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
Intent prepopulate = getIntent();
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String startTitle = prepopulate.getStringExtra(Lab8_082588Edit.TITLE_STRING);
String startGross = prepopulate.getStringExtra(Lab8_082588Edit.GROSS_STRING);
String startDate = prepopulate.getStringExtra(Lab8_082588Edit.DATE_STRING);
movieTitle.setText(startTitle);
movieGross.setText(startGross.replaceAll(",", "").replace("$", ""));
movieDate.setText(startDate);
}
My FetchDetails class
public class Lab8_082588FetchDetails implements Comparable<Lab8_082588FetchDetails> {
private String title;
private String gross;
private String date;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGross() {
return gross;
}
public void setGross(String gross) {
this.gross = gross;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public int compareTo(Lab8_082588FetchDetails another) {
// TODO Auto-generated method stub
return title.compareTo(another.title);
}
}
My Adapter:
private class SampleCustomAdapter extends BaseAdapter {
public SampleCustomAdapter(ArrayList<Lab8_082588FetchDetails> movies) {
internalList = movies;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return internalList.size();
}
#Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return internalList.get(index);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View view;
if (convertView == null) {
view = inflater.inflate(R.layout.row, null);
} else {
view = convertView;
}
// extract the views to be populated
TextView title = (TextView) view.findViewById(R.id.title);
TextView gross = (TextView) view.findViewById(R.id.gross);
TextView date = (TextView) view.findViewById(R.id.date);
// extract the object that will fill these
Lab8_082588FetchDetails movie = internalList.get(position);
title.setText(movie.getTitle());
date.setText(movie.getDate());
gross.setText(movie.getGross());
// return the view
return view;
}
}
My problem is that, indeed, the Edit Texts get populated, but only with the data from the first item in the entire list (e.g. Titanic is first on the list, and is the only one being populated). Even if I click the nth row movie in the listview, Titanic is still the one being retrieved. How do I solve this?
Edit: I realize that somehow, the code is only considering the first element of the list. How do I access the elements of the other rows?
I realize that somehow, the code is only considering the first
element of the list. How do I access the elements of the other rows?
You should never do a search with findViewById for items which are in a ListView row. In the onContextItemSelected callback you have the position of the element clicked so you could use it to get the data associated with this row:
case R.id.edit:
Intent newData = new Intent(Lab8_082588.this, Lab8_082588Edit.class);
// I hope you implemented the adapter correctly
Lab8_082588FetchDetails item = (Lab8_082588FetchDetails) getListView().getItemAtPosition(info.position);
String startTitle = item.getTitle();
String startGross = item.getGross();
String startDate = item.getDate();
newData.putExtra(Lab8_082588Edit.TITLE_STRING, startTitle);
newData.putExtra(Lab8_082588Edit.GROSS_STRING, startGross);
newData.putExtra(Lab8_082588Edit.DATE_STRING, startDate);
startActivityForResult(newData, Lab8_082588.EDIT_MOVIE);
return true;

Custom ListView is not updated when items are inserted

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.

Categories

Resources