i have a custom listview and custom adapter. each row has multiple items inside it, when i click on like button it change the color of imageview but it also effect the 4th,7th and 10th row.
after searching on internet i learned that i have to use getTag and setTag but i dont know how to use it.
please help me in understanding the concept of getTag and setTag and solving this error.
here is my code:-
package rj.osmthemes;
import java.util.ArrayList;
import android.content.Context;
import android.os.Build;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import static android.R.attr.data;
import static rj.osmthemes.R.id.downlink;
import static rj.osmthemes.R.id.likebtn;
import static rj.osmthemes.R.id.likecount;
public class ListAdapter extends ArrayAdapter<DataModel> {
customButtonListener customListner;
private ArrayList<DataModel> dataSet;
public String temp1;
public interface customButtonListener {
public void onButtonClickListner(int position,String value);
public void onImageClickListner(int position,String value);
public void onlikeImageClickListner(int position,String value);
public void ondislikeImageClickListner(int position,String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
//private ArrayList<String> data = new ArrayList<String>();
public ListAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.list_layout, data);
this.dataSet = data;
this.context = context;
}
private int lastPosition = -1;
// public ListAdapter(Context context, ArrayList<String> dataItem) {
// super(context, R.layout.list_layout, dataItem);
// this.data = dataItem;
// this.context = context;
// }
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final DataModel dataModel = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_layout, null);
viewHolder = new ViewHolder();
viewHolder.themename = (TextView) convertView.findViewById(R.id.themename);
viewHolder.madeby = (TextView) convertView.findViewById(R.id.madeby);
viewHolder.downcount = (TextView) convertView.findViewById(R.id.downcount);
viewHolder.likecount = (TextView) convertView.findViewById(likecount);
viewHolder.dislikecount = (TextView) convertView.findViewById(R.id.dislikecount);
viewHolder.ss1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder.ss2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder.ss3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder.likebtn = (ImageView) convertView.findViewById(likebtn);
viewHolder.dislikebtn = (ImageView) convertView.findViewById(R.id.dislikebtn);
viewHolder.btndownload = (Button) convertView.findViewById(downlink);
convertView.setTag(viewHolder);
final String temp = getItem(position).toString();
viewHolder.likebtn.setTag(temp);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
lastPosition = position;
//final String temp = getItem(position).toString();
// viewHolder.tempid = Integer.parseInt(dataModel.getId());
final String ss1link,ss2link,ss3link,downlink;
viewHolder.themename.setText(dataModel.getTheme_name());
viewHolder.madeby.setText(dataModel.getMade_by());
viewHolder.downcount.setText(dataModel.getDown_count());
viewHolder.likecount.setText(dataModel.getLike_count());
viewHolder.dislikecount.setText(dataModel.getDislike_count());
ss1link = dataModel.getSs1();
ss2link = dataModel.getSs2();
ss3link = dataModel.getSs3();
downlink = dataModel.getDown_link();
// viewHolder.text.setText(temp);
viewHolder.btndownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
int downcounttmp = Integer.parseInt(dataModel.getDown_count());
downcounttmp++;
viewHolder.downcount.setText(""+downcounttmp);
String name = downlink + "#" + dataModel.getTheme_name() + "#" + dataModel.getId() + "#" + downcounttmp;
customListner.onButtonClickListner(position,name);
}
}
});
viewHolder.ss1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss1link);
}
}
});
viewHolder.ss2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss2link);
}
}
});
viewHolder.ss3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss3link);
}
}
});
viewHolder.likebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
// Toast.makeText(context, dataModel.getId() + " { " ,Toast.LENGTH_LONG).show();
if(viewHolder.check == 0){
int likecount = Integer.parseInt(dataModel.getLike_count());
likecount++;
viewHolder.likecount.setText(""+likecount);
String name = likecount + "#" + dataModel.getId();
// Toast.makeText(context,position + " " + temp,Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.likebtn.setImageResource(R.drawable.ic_thumb_up_red_24dp);
//viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp));
viewHolder.check = 1;
}
customListner.onlikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
viewHolder.dislikebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
if(viewHolder.check == 0) {
int dislikecount = Integer.parseInt(dataModel.getDislike_count());
dislikecount++;
viewHolder.dislikecount.setText(""+dislikecount);
String name = dislikecount + "#" + dataModel.getId();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp));
viewHolder.check = 1;
}
customListner.ondislikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
Glide
.with(context)
.load(ss1link)
.into(viewHolder.ss1);
Glide
.with(context)
.load(ss2link)
.into(viewHolder.ss2);
Glide
.with(context)
.load(ss3link)
.into(viewHolder.ss3);
return convertView;
}
public class ViewHolder {
TextView themename,madeby,downcount,likecount,dislikecount;
Button btndownload;
ImageView ss1,ss2,ss3,likebtn,dislikebtn;
int check = 0, tempid = 0;
}
}
This is because of object reuse in your list view.
You can manage separate ArrayList or HashMap to maintain your likes.
And based on that you should update in your getView like this,
if([already selected]) {
viewHolder.likebtn.setBackground([your selected drawable]);
} else {
viewHolder.likebtn.setBackground([your non selected drawable]);
}
Related
In my BaseAdpater I'm setting the visibility of a view to GONE in a row after some operation. All operation is fine but view remains visible in background while lower views are move up until i touch the screen. It means listview is updating the views and releasing the space on setting visibility to GONE but view is still visible in background. What could be the issue?
Code:
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.iu.foodbucket.BaseActivity;
import com.iu.foodbucket.R;
import com.iu.foodbucket.database.MyDataSource;
import com.iu.foodbucket.fragments.CartFragment;
import com.iu.foodbucket.models.Cart;
import com.iu.foodbucket.utils.AppGlobal;
import java.util.List;
public class CartAdapter extends BaseAdapter {
Fragment context;
List<Cart> data;
MyDataSource myDataSource;
boolean isOldOrder;
public CartAdapter(Fragment ctx, List<Cart> data, boolean orderStatus) {
this.context = ctx;
this.data = data;
this.isOldOrder = orderStatus;
myDataSource = new MyDataSource(ctx.getActivity());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_cart, parent, false);
holder.title_tv = (TextView) convertView.findViewById(R.id.title_tv);
holder.quantity_tv = (TextView) convertView.findViewById(R.id.quantity_tv);
holder.price_tv = (TextView) convertView.findViewById(R.id.price_tv);
holder.edit_iv = (ImageView) convertView.findViewById(R.id.edit_iv);
holder.thumbnail_iv = (ImageView) convertView.findViewById(R.id.thumbnail_iv);
holder.editPanel = (LinearLayout) convertView.findViewById(R.id.editPanel);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title_tv.setText(data.get(position).getMenu().getTitle());
holder.quantity_tv.setText(context.getString(R.string.quantity_abbr) + " " + data.get(position).getQuantity());
if (((BaseActivity) context.getActivity()).dataPreference.getIsImageEnabled())
Glide.with(context.getActivity()).load(data.get(position).getMenu().getThumbnail()).placeholder(R.drawable.ic_tag_face).centerCrop().into(holder.thumbnail_iv);
float price = Float.parseFloat(data.get(position).getMenu().getPrice());
price = (float) AppGlobal.round(price, 2);
holder.price_tv.setText(data.get(position).getMenu().getPriceUnit() + " " + price);
final View finalConvertView = convertView;
holder.edit_iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.editPanel.getVisibility() != View.VISIBLE) {
holder.editPanel.setVisibility(View.VISIBLE);
showEditablePanel(finalConvertView, position, holder.editPanel);
} else {
holder.editPanel.setVisibility(View.GONE);
}
}
});
return convertView;
}
private void showEditablePanel(View v, final int position, final LinearLayout editPanel) {
final TextView quantity_tv = (TextView) v.findViewById(R.id.quantityUpdated_tv);
final ImageButton minus_btn = (ImageButton) v.findViewById(R.id.minus_btn);
final ImageButton plus_btn = (ImageButton) v.findViewById(R.id.plus_btn);
ImageButton update_btn = (ImageButton) v.findViewById(R.id.update_btn);
ImageButton remove_btn = (ImageButton) v.findViewById(R.id.remove_btn);
final int[] quantity = {Integer.parseInt(data.get(position).getQuantity())};
quantity_tv.setText(quantity[0] + "");
minus_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity[0]--;
updateViews(quantity[0], minus_btn, quantity_tv);
}
});
plus_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity[0]++;
updateViews(quantity[0], minus_btn, quantity_tv);
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isOldOrder) // update cart item in DB
myDataSource.updateCartItem(data.get(position).getMenu().getId(), quantity[0] + "");
data.get(position).setQuantity(quantity[0] + "");
editPanel.setVisibility(View.GONE);
notifyDataSetChanged();
((CartFragment) context).updateTotalValues();
}
});
remove_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deletionConfirmationDialog(position, editPanel);
}
});
}
public void deletionConfirmationDialog(final int position, final LinearLayout editPanel) {
final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(context.getActivity());
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setTitle(context.getString(R.string.title_delete));
alertDialogBuilder.setMessage(context.getString(R.string.message_confirm_deletion));
alertDialogBuilder.setPositiveButton(context.getString(R.string.title_yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (!isOldOrder) // delete cart item from DB
myDataSource.deleteCartItem(data.get(position).getMenu().getId());
editPanel.setVisibility(View.GONE);
data.remove(position);
notifyDataSetChanged();
((CartFragment) context).updateTotalValues();
}
});
alertDialogBuilder.setNegativeButton(context.getString(R.string.title_no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
}
});
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void updateViews(int quantity, ImageButton minus_btn, TextView quantity_tv) {
if (quantity > 1) {
minus_btn.setEnabled(true);
minus_btn.setAlpha((float) 1.0);
} else {
minus_btn.setEnabled(false);
minus_btn.setAlpha((float) 0.4);
}
quantity_tv.setText(quantity + "");
}
private class ViewHolder {
TextView title_tv, quantity_tv, price_tv;
ImageView thumbnail_iv, edit_iv;
LinearLayout editPanel;
}
}
if you mean after setting visiblity gone of a row, that row remains blank and that gap is visible,the better way is to filter the adapter content by using getFilter() to display by excluding that row content and notifyadapter changed.
I want to add / remove the item into wishlist. I am getting one response from Api, so in that i have one tag is_wishlist=true/false, when I am launching an application based on that value I am showing its in wishlist by changing an icon, but now issue is if am changing that wishlist status like from adding to remobing to adding, in Api i am getting response sucessfully, but i am unable to change the icons. This is my code. can any one help me how to remove or add items into wishlist
package com.example.user.smgapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
public class Prd_grid_adapter extends BaseAdapter {
List<HashMap<String, String>> Category_listData;
HashMap<String, String> map;
Context context;
Typeface face;
String wishList_url, remove_wishList_url;
Cursor cursor;
NavigationDrawer nav = new NavigationDrawer();
private static LayoutInflater inflater = null;
public Prd_grid_adapter(Activity context, List<HashMap<String, String>> aList) {
// TODO Auto-generated constructor stub
Category_listData = aList;
/*/for(int i=1;i<aList.size();i++)
{
Category_listData.add(aList.get(i));
}*/
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Category_listData.size();
}
#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 name, price, original_price;
ImageView img, wish_list;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
final View rowView;
this.face = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
rowView = inflater.inflate(R.layout.grid_item_view, null);
holder.name = (TextView) rowView.findViewById(R.id.p_name);
holder.img = (ImageView) rowView.findViewById(R.id.p_img);
holder.wish_list = (ImageView) rowView.findViewById(R.id.wish_list);
holder.price = (TextView) rowView.findViewById(R.id.p_price);
holder.original_price = (TextView) rowView.findViewById(R.id.orginal_p);
map = Category_listData.get(position);
holder.name.setTypeface(face);
holder.name.setText(map.get("product_name"));
Log.e("wish list staus..", "wishlist status.." + map.get("is_wishlist"));
if (map.get("is_wishlist").equals("0")) {
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
} else {
holder.wish_list.setImageResource(R.drawable.wishlist);
}
holder.wish_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SingletonActivity.custidstr.isEmpty()) {
Toast.makeText(context, "Ur not logged in,Please Login", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert!");
builder.setMessage("Ur not logged in")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, Login.class);
context.startActivity(intent);
}
});
// Create the AlertDialog object and return it
builder.show();
} else {
wishList_url = SingletonActivity.API_URL + "api/add_wishlist.php?customer_id=" + SingletonActivity.custidstr + "&product_id=" + Category_listData.get(position).get("product_id");
remove_wishList_url = SingletonActivity.API_URL + "api/remove_item_wishlist.php?customerid=" + SingletonActivity.custidstr + "&productid=" + Category_listData.get(position).get("product_id");
Log.e("wishlist api..", "wish list api.." + wishList_url);
Log.e("remove wishlist api..", "remove wish list api.." + remove_wishList_url);
v.setActivated(!v.isActivated());
String wish_status = map.get("is_wishlist");
Log.e("wish status..", "wish status.." + wish_status);
int stat = Integer.parseInt(wish_status);
// notifyDataSetChanged();
/*if (wish_status=="Product already exists in wishlist"){
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}
else
{
nav.addTowishList(wishList_url);
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
}*/
if (stat == 0) {
nav.addTowishList(wishList_url);
Toast.makeText(context, "addedd..", Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
// notifyDataSetChanged();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
//
} else {
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
Toast.makeText(context, "removed....", Toast.LENGTH_SHORT).show();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
// notifyDataSetChanged();
}
/* v.setActivated(!v.isActivated());
if (v.isActivated()){
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
nav.addTowishList(wishList_url);
}
else {
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}*/
}
}
});
if (map.get("special_price").equals("0.00")) {
holder.price.setVisibility(View.INVISIBLE);
// holder.o_price.setVisibility(View.INVISIBLE);
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setTextAppearance(context, R.style.product_price_txt);
} else {
holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
/* holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs."+map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);*/
Picasso.with(context).load(map.get("product_image")).placeholder(R.drawable.loading)
.fit().into(holder.img);
return rowView;
}
}
Change this line
holder.wish_list.setImageResource(R.drawable.wishlist);
to this
Resources resources = getResources();
holder.wish_list.setImageDrawable(resources.getDrawable(R.drawable.wishlist));
and do the same in else part and check the output..
Note :
getResources().getDrawable is deprecated.
You can try ContextCompat.getDrawable:
holder.wish_list.setImageDrawable(ContextCompat.getDrawable(context,
R.drawable.wishlist));
UpDate :
check this way.
if(state == true){
// here is default icon and set api value and send it
}else{
// here is click wishlist icon and set api value and send it
}
UpDate 2 :
public class FragmentOne_Adapter extends CursorAdapter {
FragmentOne_DbAdapter dbHelper;
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
dbHelper = new FragmentOne_DbAdapter(context);
dbHelper.open();
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// TODO Auto-generated method stub
final ViewHolder holder = (ViewHolder) view.getTag();
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
holder.txtTitle.setText(title);
holder.txtArtist.setText(artist);
holder.txtVolume.setText(volume);
holder.txtNumber.setText(number);
if (favorite.matches("0")) {
holder.buttonHeart.setImageResource(R.drawable.heart);
} else {
if (favorite.matches("1")) {
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else {
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
holder.buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database = new FragmentOne_DbAdapter(context);
database.open();
if (favorite.matches("0")) {
database.updateItemFavorite(_id, "1");
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else if (favorite.matches("1")) {
database.updateItemFavorite(_id, "0");
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
FragmentOne_Adapter.this.changeCursor(dbHelper.fetchAllPlayer1());
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
// View rowView = ((LayoutInflater) context
// .getSystemService("layout_inflater")).inflate(
// R.layout.fragment_fragment_one_slview, parent, false);
View rowView = LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
ViewHolder holder = new ViewHolder();
holder.txtTitle = (TextView) rowView.findViewById(R.id.title);
holder.txtArtist = (TextView) rowView.findViewById(R.id.artist);
holder.txtVolume = (TextView) rowView.findViewById(R.id.volume);
holder.txtNumber = (TextView) rowView.findViewById(R.id.number);
holder.buttonHeart = (ImageButton) rowView.findViewById(R.id.heart);
rowView.setTag(holder);
return rowView;
}
class ViewHolder {
TextView txtTitle;
TextView txtArtist;
TextView txtVolume;
TextView txtNumber;
ImageButton buttonHeart;
}
}
I used a customized Gridview adapter in application. It contains textview items in a particular order. When i click on individual textviews, it always shows a constant value. Here code follows
Main_activity.java
public class MainActivity extends Activity implements GridAdapter.ItemSelectedListener
{
private TextView tv;
private GridView gv;
private GridAdapter ga;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.TextMsg);
gv = (GridView)findViewById(R.id.gridView);
ga = new GridAdapter(this);
ga.setItemSelectedListener(this);
gv.setAdapter(ga);
GridAdapter.Item item = new GridAdapter.Item();
item.set("Header1", "Item1_1", "Item1_2", "Item1_3");
ga.add(item);
item = new GridAdapter.Item();
item.set("Header2", "Item2_1", "Item2_2", "Item2_3");
ga.add(item);
item = new GridAdapter.Item();
item.set("Header3", "Item3_1", "Item3_2", "Item3_3");
ga.add(item);
}
#Override
public void onItemSelected(String strItem) {
Toast.makeText(this, strItem, Toast.LENGTH_LONG).show();
}
}
GridAdapter.java
package com.example.testapplication;
import android.content.Context;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GridAdapter extends ArrayAdapter<GridAdapter.Item> {
private LayoutInflater m_vi = null;
private GridAdapter.Item m_item = null;
private ViewHolderItem m_holderItem = null;
private ItemSelectedListener mItemSelectedListener = null;
public GridAdapter(Context context) {
super(context, 0);
m_vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
m_item = (GridAdapter.Item)getItem(position);
if (convertView == null || !convertView.getTag().equals(m_holderItem)){
convertView = m_vi.inflate(R.layout.mygrid, null);
m_holderItem = new ViewHolderItem();
convertView.setTag(m_holderItem);
}
else {
m_holderItem = (ViewHolderItem) convertView.getTag();
}
m_holderItem.tvHeader = (TextView)convertView.findViewById(R.id.gridhead);
m_holderItem.tvItem1 = (TextView)convertView.findViewById(R.id.gridtext1);
m_holderItem.tvItem1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mItemSelectedListener != null )
mItemSelectedListener.onItemSelected(m_holderItem.tvItem1.getText().toString());
}
});
m_holderItem.tvItem2 = (TextView)convertView.findViewById(R.id.gridtext2);
m_holderItem.tvItem2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mItemSelectedListener != null )
mItemSelectedListener.onItemSelected(m_holderItem.tvItem2.getText().toString());
}
});
m_holderItem.tvItem3 = (TextView)convertView.findViewById(R.id.gridtext3);
m_holderItem.tvItem3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mItemSelectedListener != null )
mItemSelectedListener.onItemSelected(m_holderItem.tvItem3.getText().toString());
}
});
m_holderItem.tvHeader.setText(m_item.getHeader());
m_holderItem.tvItem1.setText(m_item.getItem1());
m_holderItem.tvItem2.setText(m_item.getItem2());
m_holderItem.tvItem3.setText(m_item.getItem3());
return convertView;
}
public static class ViewHolderItem {
public TextView tvHeader;
public TextView tvItem1;
public TextView tvItem2;
public TextView tvItem3;
}
public static class Item {
public String Header, Item1, Item2, Item3;
public Item(){
this.Header = "";
this.Item1 = "";
this.Item2 = "";
this.Item3 = "";
}
public void set(String Header_i, String Item1_i, String Item2_i, String Item3_i) {
this.Header = Header_i;
this.Item1 = Item1_i;
this.Item2 = Item2_i;
this.Item3 = Item3_i;
}
public String getHeader(){
return this.Header;
}
public String getItem1(){
return this.Item1;
}
public String getItem2(){
return this.Item2;
}
public String getItem3(){
return this.Item3;
}
}
public interface ItemSelectedListener {
public void onItemSelected(String strItem );
}
public void setItemSelectedListener( ItemSelectedListener _listener){
mItemSelectedListener = _listener;
}
}
Above picture shows output of the screen. When i clicked on item1_1 or item2_1 or item3_1, it always shows item1_1.
How to solve this problem ?
thanks in advance
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: How to fire onListItemClick in Listactivity with buttons in list?
i have develop one app in which i have make ListActivity in which custome listview are going to display custom item list.all things are going to well but here i am confuse with itemOnClickListner. how can i add onclick listner in listActivity ? because there are not any listview that initialize and i can set listner trough that listview control... i have find out from here but its also not working for me
:Here is Code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update3
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends Activity implements OnClickListener, OnItemClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
lstFavrowlistv = (ListView)findViewById(R.id.lstFavrowlistv);
lstFavrowlistv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
});
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
lstFavrowlistv.setAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) lstFavrowlistv.getAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
use getListview() in list Activity to get List..........
in Oncreate
ListView lv = getListView();
http://www.mkyong.com/android/android-listview-example/
this link has both ways
1- overriding onListItemClick(
2- Setting you listener..
Try this way..
ListView lv = getListView();
lv. storelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
}
this are help you.
Thanks
Override the function onlistitemclick() for this. Here the integer position represents the postion of item that you had pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
.......
}
Try this one
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
}
});
I'm using an implementation of ViewFlow example for my application where I have to swipe images from SdCard. With the code I'm using I can swipe images, but it's showing only one and i'm trying to set the whole images from my SdCard specific folder in the ViewFlow, but that's the problem that I have. I'm getting the path to the image by an ID which I get from sqlite database and depending on that I want to add these images to the view. So this is the code which I'm using for now :
My Cards.class :
package com.stampii.stampii.cards;
import java.util.ArrayList;
import java.util.HashMap;
import com.stampii.stampii.R;
import com.stampii.stampii.comm.rpc.UserDatabaseHelper;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class Cards extends Activity {
public Cursor cursor;
int position;
int indexxx;
Bitmap b;
int objectId;
int cardsId;
ArrayList<HashMap<Integer, String>> imgpaths;
ArrayList<Integer> ids;
String path;
int mediaType=5001;
private ViewFlow viewFlow;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.circle_layout);
UserDatabaseHelper userDbHelper = new UserDatabaseHelper(this, null, 1);
userDbHelper.initialize(this);
imgpaths = new ArrayList<HashMap<Integer, String>>();
HashMap<Integer, String> hm = new HashMap<Integer, String>();
ids = new ArrayList<Integer>();
final int cardId = getIntent().getIntExtra("card_id",0);
Log.i("Card Id ","Card Id : "+cardId);
final int collId = getIntent().getIntExtra("collection_id",0);
Log.i("Collection Id ","Collection Id : "+collId);
position = getIntent().getIntExtra("position",0);
Log.i("position","position : "+position);
String cardSQL = "SELECT cm.cardId, cm.objectId "+
"FROM cardmedias AS cm "+
"INNER JOIN cards AS cd "+
"ON (cm.cardId = cd.objectId) "+
"WHERE cd.collectionId="+collId +" AND cm.mediaType="+mediaType;
Cursor cards = userDbHelper.executeSQLQuery(cardSQL);
if (cards.getCount() == 0) {
Log.i("", "No Image file");
cards.close();
} else if (cards.getCount() > 0) {
for (cards.move(0); cards.moveToNext(); cards.isAfterLast()) {
cardsId = Integer.parseInt(cards.getString(cards
.getColumnIndex("objectId")));
//Log.i("", "cards objectId : " + cardsId);
String path = Environment.getExternalStorageDirectory()
+ "/.Stampii/MediaCard/" + cardsId + ".png";
//Log.i("", "path : " + path);
ids.add(cardsId);
hm.put(cardsId, path);
}
}
String sql = "SELECT objectId FROM cardmedias WHERE cardId=" + cardId
+ " LIMIT 1";
Cursor cursor = userDbHelper.executeSQLQuery(sql);
if (cursor.getCount() == 0) {
Log.i("", "No Image file");
cursor.close();
} else if (cursor.getCount() > 0) {
cursor.moveToFirst();
objectId = Integer.parseInt(cursor.getString(cursor
.getColumnIndex("objectId")));
Log.i("", "objectId : " + objectId);
path = hm.get(objectId);
Log.i("","path : "+hm.get(objectId));
Log.i("","hm size : "+hm.size());
}
Button info = (Button) findViewById(R.id.info_button);
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cards.this, SingleCardInfo.class);
intent.putExtra("card_id", cardId);
intent.putExtra("collection_id", collId);
startActivity(intent);
}
});
Button back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
final ArrayList<Bitmap> images = new ArrayList<Bitmap>();
for(int i=0;i<=2;i++){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Bitmap b = BitmapFactory.decodeFile(hm.get(objectId), options);
Log.i("","path : "+hm.get(objectId));
images.add(b);
}
viewFlow = (ViewFlow) findViewById(R.id.viewflow);
viewFlow.setAdapter(new ImageAdapter(this, images),position);
ImageButton prevBtn = (ImageButton) findViewById(R.id.previous_button);
prevBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()-1;
if (indexxx>=0) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
ImageButton nextBtn = (ImageButton) findViewById(R.id.next_button);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()+1;
if (indexxx<images.size()) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
viewFlow.onConfigurationChanged(newConfig);
}
}
And my ImageAdapter class :
package com.stampii.stampii.cards;
import java.util.ArrayList;
import com.stampii.stampii.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Bitmap> ids = new ArrayList<Bitmap>();
//private Bitmap bitmap;
public ImageAdapter(Context context, ArrayList<Bitmap> images) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ids = images;
}
#Override
public int getCount() {
return ids.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) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.image_item, null);
}
((ImageView) convertView.findViewById(R.id.imgView)).setImageBitmap(ids.get(position));
return convertView;
}
}
So my question is how can I add all images from my SdCard folder to this ViewFlow example when I had the path to these images. I've tried to load all of them, but in some cases the images are too much and it's throwing me an outofmemoryException, that's why I think it's better just to set the paths to them. So any help or suggestions are welcomed!
Thanks in advance!
Here is code of ViewFlow.class : ViewFlow
You can try something like this :
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> ids = new ArrayList<String>();
//private Bitmap bitmap;
public ImageAdapter(Context context, ArrayList<String> images) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ids = images;
}
#Override
public int getCount() {
return ids.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) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.image_item, null);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[8*1024];
Bitmap ops = BitmapFactory.decodeFile(ids.get(position), options);
((ImageView) convertView.findViewById(R.id.imgView)).setImageBitmap(ops);
return convertView;
}
}
And :
public class Cards extends Activity {
public Cursor cursor;
int position;
int indexxx;
Bitmap b;
int objectId;
int cardsId;
ArrayList<Integer> ids;
String path;
int mediaType=5001;
ArrayList<String> images;
int card;
private ViewFlow viewFlow;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.circle_layout);
UserDatabaseHelper userDbHelper = new UserDatabaseHelper(this, null, 1);
userDbHelper.initialize(this);
//imgpaths = new ArrayList<HashMap<Integer, String>>();
HashMap<Integer, String> hm = new HashMap<Integer, String>();
ids = new ArrayList<Integer>();
images = new ArrayList<String>();
final int cardId = getIntent().getIntExtra("card_id",0);
Log.i("Card Id ","Card Id : "+cardId);
final int collId = getIntent().getIntExtra("collection_id",0);
Log.i("Collection Id ","Collection Id : "+collId);
position = getIntent().getIntExtra("position",0);
Log.i("position","position : "+position);
String cardSQL = "SELECT cm.cardId, cm.objectId "+
"FROM cardmedias AS cm "+
"INNER JOIN cards AS cd "+
"ON (cm.cardId = cd.objectId) "+
"WHERE cd.collectionId="+collId +" AND cm.mediaType="+mediaType;
Cursor cards = userDbHelper.executeSQLQuery(cardSQL);
if (cards.getCount() == 0) {
Log.i("", "No Image file");
cards.close();
} else if (cards.getCount() > 0) {
for (cards.move(0); cards.moveToNext(); cards.isAfterLast()) {
cardsId = Integer.parseInt(cards.getString(cards
.getColumnIndex("objectId")));
card = Integer.parseInt(cards.getString(cards
.getColumnIndex("cardId")));
String path = Environment.getExternalStorageDirectory()
+ "/.Stampii/MediaCard/" + cardsId + ".png";
ids.add(card);
hm.put(cardsId, path);
path = hm.get(cardsId);
Log.i("","path : "+hm.get(cardsId));
Log.i("","hm size : "+hm.size());
images.add(path);
}
}
Button back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
viewFlow = (ViewFlow) findViewById(R.id.viewflow);
viewFlow.setAdapter(new ImageAdapter(this, images),position);
ImageButton prevBtn = (ImageButton) findViewById(R.id.previous_button);
prevBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()-1;
if (indexxx>=0) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
ImageButton nextBtn = (ImageButton) findViewById(R.id.next_button);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()+1;
if (indexxx<images.size()) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
Button info = (Button) findViewById(R.id.info_button);
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cards.this, SingleCardInfo.class);
intent.putExtra("card_id", ids.get(position));
intent.putExtra("collection_id", collId);
startActivity(intent);
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
viewFlow.onConfigurationChanged(newConfig);
}
}
That should do the trick!