I am Listing all the Apps installed on device in Fragment which having gridview inside. what i want to do is, i want 4 col * 5 rows(20 App in one fragment only) , if i install new app (app count 21) it must set on the next fragment and set at the top left of new fragment , fragment should generate dynamically , and add to viewpager.
here is my code. MainActivity :
public class MainActivity extends FragmentActivity {
ViewPager pager;
AppViewAdapter adapter;
GridFrag gridFrag;
FragmentManager fragmentManager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
init();
addListener();
}
private void bindView() {
pager = (ViewPager) findViewById(R.id.slideingpager);
}
private void init() {
adapter = new AppViewAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
}
}
GridFragment.java :
public class GridFrag extends android.support.v4.app.Fragment implements
OnItemClickListener {
GridView gridView;
ViewAdapter viewAdapter;
PackageManager packageManager;
int columnsOfGridView;
public class AppDetails {
Drawable icon;
String label;
}
AppDetails packages[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridfrag, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
packageManager = getActivity().getPackageManager();
gridView = (GridView) getActivity().findViewById(R.id.grid);
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packList = packageManager.queryIntentActivities(
mainIntent, 0);
packages = new AppDetails[packList.size()];
for (int i = 0; i < packList.size(); i++) {
packages[i] = new AppDetails();
packages[i].icon = packList.get(i).loadIcon(packageManager);
packages[i].label = packList.get(i).loadLabel(packageManager)
.toString();
}
viewAdapter = new ViewAdapter(getActivity(), packages);
gridView.setAdapter(viewAdapter);
int totalApps = gridView.getCount();
Toast.makeText(getActivity(), "Total "+ totalApps + " App(s)Found",Toast.LENGTH_SHORT).show();
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"You Clicked on : " + packages[position].label,
Toast.LENGTH_SHORT).show();
}
}
ViewAdapter.java (GridAdapter)
public class ViewAdapter extends BaseAdapter {
private Context context;
AppDetails setPacksForAdapter[];
public ViewAdapter(Context c, AppDetails apps[]) {
context = c;
setPacksForAdapter = apps;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return setPacksForAdapter.length;
}
#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;
}
public static class ViewHolder {
ImageView imgDefaultAppIcon;
TextView tvDefaultAppLabel;
}
#Override
public View getView(int pos, View v, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = new ViewHolder();
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.grid_view, null);
holder.imgDefaultAppIcon = (ImageView) v
.findViewById(R.id.ivAppIcon);
holder.tvDefaultAppLabel = (TextView) v
.findViewById(R.id.tvAppLabel);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imgDefaultAppIcon.setImageDrawable(setPacksForAdapter[pos].icon);
holder.tvDefaultAppLabel.setText(setPacksForAdapter[pos].label);
return v;
}
}
AppViewAdepter.java (For ViewPager)
public class AppViewAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentsList;
public AppViewAdapter(FragmentManager fm) {
super(fm);
this.fragmentsList = new ArrayList<Fragment>();
for (int i = 0; i <= 2; i++) {
if (i % 2 == 0)
fragmentsList.add(new GridFrag());
else
fragmentsList.add(new FragTwo());
}
}
#Override
public Fragment getItem(int arg0) {
return fragmentsList.get(arg0);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragmentsList.size();
}
}
Set Layoutparams dynamically height of rootview of single grid in Adapter in getView() Method
(Device height / 5) - statusBarHieght
Some code : in getView() of Adapter
int grid_height = ((Helper.get_device_height(context)) / 5) - statusBarHeight;
GridView.LayoutParams layoutParams = (android.widget.AbsListView.LayoutParams) view.getLayoutParams();
layoutParams.height = grid_height;
view.setLayoutParams(layoutParams);
and,
gridview XML set columns=4
It will solve your problem.
Hope it will help you !
in your layout.xml by default <android:columnCount="auto_fit"> is set, you have to change it to as 4 by dong this <android:columnCount="4"> and to set rows similarly also in java you can do this like following setColumnCount(4) and setRowCount(5)
Related
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)
Below is the class where i am not able to get the resource of the image id. I am trying to fetch all the data from the web service. Here i have posted all the classes from where the images are fetched.I have all the images showing it in the gridView. I am not facing problem in that, however when I click on the image of the gridview it shows me the just the xml file which I have called. I guess I am doing wrong somewhere calling the id here in the FullImageAcitivity file.
DefaultGridView.java
public class DefaultGridView extends Activity {
//int position;
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.latestphotos);
gridView=(GridView)findViewById(R.id.grid_view);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
gridView.setAdapter(new ImageAdapter());
}
public class ImageAdapter extends BaseAdapter {
LayoutInflater inflater = LayoutInflater.from(context);
public ImageAdapter() {
// TODO Auto-generated constructor stub
imageLoader.init(ImageLoaderConfiguration.createDefault(DefaultGridView.this));
}
#Override
public int getCount() {
return Global.getPhotos_list().size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.other, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)items.get(i);
picture.setImageResource(item.getDrawable());
name.setText(item.name);
Log.d("position", position+"");
imageLoader.displayImage(Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name"), picture , options,null,context);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long a) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("idkey", position); // pass the id
startActivity(i);
}
});
return v;
}
}
}
FullImageActivity.java
public class FullImageActivity extends Activity {
Button download, setas;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
setas = (Button) findViewById(R.id.setas);
download = (Button)findViewById(R.id.download);
// get intent data
final Intent i = getIntent();
// Selected image id
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
int id = getIntent().getIntExtra("idkey",-1); //get id
imageView.setImageResource(id);
setas.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.full_image_view);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
List<Item> items;
public ImageAdapter(Context context,List<Item> items) {
inflater = LayoutInflater.from(context);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).drawable;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.other, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)items.get(i);
picture.setImageResource(item.getDrawable());
name.setText(item.name);
return v;
}
}
Items.java
public class Item {
String name;
int drawable;
public int getDrawable() {
return drawable;
}
public void setDrawable(int drawable) {
this.drawable = drawable;
}
public Item(String name, int id)
{
this.name= name;
this.drawable = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In gridView item click
Item item =(Item) items.get(position);
int id = item.getDrawable();
Intent i = new Intent(ActivityName.this, FullImageActivity.class);
i.putExtra("idkey", id); // pass the id
startActivity(i);
Then in FullImageActivity
int id = getIntent().getIntExtra("idkey"); //get id
imageview.setImageResource(id); // set the drawable to imageview
You can move the below to onCreate of DefaultFridView
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long a) {
Item item =(Item) items.get(position);
int id = item.getDrawable();
Intent i = new Intent(ActivityName.this, FullImageActivity.class);
i.putExtra("idkey", id); // pass the id
startActivity(i);
}
});
Also you need to have the List in DefaultGridView
List<Item> items = new ArrayList<Item>();
Then
items.add(new Item("One", R.drawable.abstact_one));
items.add(new Item("Two", R.drawable.abstract_three));
items.add(new Item("Three", R.drawable.image_two));
items.add(new Item("Four", R.drawable.image_four));
items.add(new Item("Five", R.drawable.image_five));
items.add(new Item("Six", R.drawable.image_nine));
items.add(new Item("Seven", R.drawable.image_ten));
Then
gridView.setAdapter(new ImageAdapter(),items);
Also i don't understand having the ImageAdapter as separate and as a inner class. WHy do you need both
Try this example my be it is usefull
Grieview Display Full Image
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 created custom adapter for listview which contain text and images, on click of particular list item I have to open another activity, but I am not able to fire listview click event, below is my code.
Thanks.
Adapter
public class ImageAndTextAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private Context myCtx;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public ImageAndTextAdapter(Context ctx, int viewResourceId,
String[] strings, TypedArray icons) {
super(ctx, viewResourceId, strings);
myCtx = ctx;
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public String getItem(int position) {
return mStrings[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
return convertView;
}
}
Main acitivity
public class OurWishingWellActivity extends ListActivity implements OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.list_view_image);
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.reg_item_names);
TypedArray icons = res.obtainTypedArray(R.array.reg_icons);
setListAdapter(new ImageAndTextAdapter(ctx, R.layout.list_item,
options, icons));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Respected Aafag#
You have write onclick of listview like below.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(AdvancedListViewActivity.this, "working", Toast.LENGTH_SHORT).show();
System.out.println("working!!!!!!!!!");
}
Add listener
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
convertView .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity();
}
});
return convertView;
}
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.