Adapter selecting issue - android

I have a ListView which extends BaseAdapter. I have a array list. The ListView inflates and populates correctly. I am using the flipper view to change the layout to another but the problem is when i clicked on the first item it rotate but the item at third or sixth row will also rotate
list view how can i fix it i only want the image is change of selected item
ArrayList<product_data> al=new ArrayList<product_data>();
class product_data
{
String post_title;
String newprice;
String oldprice;
String image;
String id;
product_data(String post_title,String newprice,String oldprice,String image,String id)
{
this.post_title=post_title;
this.newprice=newprice;
this.oldprice=oldprice;
this.image=image;
this.id=id;
}
}
to add data in arraylist
try {
JSONObject parentObject = new JSONObject(json.toString());
JSONObject userDetails = parentObject.getJSONObject("response");
JSONArray jarray=userDetails.getJSONArray("products_data");
for(int i=0;i<jarray.length();i++)
{
System.out.println("From the Dataaaa");
JSONObject c = jarray.getJSONObject(i);
String details=c.getString("details");
String image=c.getString("image");
String catagory=c.getString("catagory");
String new_price=c.getString("new_price");
String title=c.getString("title");
String id1=c.getString("id");
System.out.println("from ther first image"+image);
System.out.println("from the sdafdfadf"+details);
al.add(new product_data(title, new_price, new_price, image, id1));
Adapter class
class MyAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return al.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return al.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View singleView, ViewGroup parent) {
// TODO Auto-generated method stub
final int ok=position;
if(singleView==null)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
singleView = inflater.inflate(R.layout.product_ist_layout,parent,false);
System.out.println("from the if"+position);
viewAnimator = (ViewAnimator)singleView.findViewById(R.id.viewFlipper);
rootLayout = (View)singleView.findViewById(R.id.main_activity_root);
cardFace = (View)singleView.findViewById(R.id.main_activity_card_face);
cardBack = (View) singleView.findViewById(R.id.main_activity_card_back);
}
System.out.println("from the else");
System.out.println("Position in else"+position);
product_data a=al.get(position);
TextView tv1=(TextView)singleView.findViewById(R.id.textView2);
TextView tv2=(TextView)singleView.findViewById(R.id.textView3);
TextView tv3=(TextView)singleView.findViewById(R.id.textView1);
/**
* Bind a click listener to initiate the flip transitions
*/
viewAnimator.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// This is all you need to do to 3D flip
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
cardFace.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("positon"+ok);
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
cardBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
imgview1=(ImageView)singleView.findViewById(R.id.imageView4);
imgview1.setTag(position);
imgview1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println(position1);
String id=al.get(position1).id;
System.out.println("id from the list"+id);
Intent in=new Intent(product_list_Activity.this,rating_dialog.class);
in.putExtra("id",id);
startActivity(in);
}
});
ImageView imgview2=(ImageView)singleView.findViewById(R.id.imageView5);
imgview2.setTag(position);
imgview2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println(position1);
String id=al.get(position1).id;
System.out.println("id from the list"+id);
Intent in=new Intent(product_list_Activity.this,product_review.class);
in.putExtra("id",id);
startActivity(in);
}
});
tv3.setTag(position);
tv3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println("from the review "+position1);
String id=al.get(position1).id;
globalvariables.product_id=id;
Intent in=new Intent(getApplicationContext(),review_product_tabbar.class);
startActivity(in);
}
});
tv1.setText(a.post_title);
tv2.setText("$"+a.oldprice);
tv1.setTypeface(tf);
tv2.setTypeface(tf);
tv3.setTypeface(tf);
int loader = R.drawable.ic_launcher;
ImageView image = (ImageView)singleView. findViewById(R.id.imageView1);
imgLoader.DisplayImage(a.image, loader, image);
Animation anim = new Rotate3dAnimation(90.0f, 0.0f, 100.0f, false, singleView);
anim.setDuration(1000l);
singleView.startAnimation(anim);
return singleView;
}
}
}
when i click on the first item it rotate and another view is coming
but when i scrolled the fourth item in below image will also rotate
i am using the on click listner on the relative views as in the code

Use ViewHolder for fill adapter. that may solve your issue
Example Code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.news_by_categories_content, null);
holder = new ViewHolder();
holder.strNewsTitle = (TextView) convertView
.findViewById(R.id.txtNewsByCategories);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
NewsListByCategoriesItem obj = new NewsListByCategoriesItem(); // My Model class getting value from this
obj = newsArray.get(position);
holder.strNewsTitle.setText(obj.getStrNewsTitle());
return convertView;
}
class ViewHolder {
TextView strNewsTitle;
}
}

Related

How to set onclick listener for two Gridview in same layout?

i have two custom GridView, I want to set Onclick Listener for first GridView, i did it inside its adapter , working fine ... but when generate items in second GridView the onclick listener read values from second GridView when i press on item in first GridView!
The onclick listener working fine if the second GridView empty
I have no idea how to fix this
The problem with holder.tvgroup1 and holder.tvgroup_delete_icon
Thanks
First GridView Adapter
public class GroupGeneratedAdapter extends BaseAdapter {
ArrayList<String> result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
GroupGeneratedAdapter(GroupMakerG groupMakerG, ArrayList<String> UserNameinput) {
// TODO Auto-generated constructor stub
result = UserNameinput;
context = groupMakerG;
// imageId=prgmImages;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.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 tvgroup, tvgroup1;
ImageView tvgroup_delete_icon;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
// View rowView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group_generated_original, parent, false);
}
holder.tvgroup = (TextView) convertView.findViewById(R.id.tvgroup);
holder.tvgroup1 = (TextView) convertView.findViewById(R.id.tvgroup1);
holder.tvgroup_delete_icon = (ImageView) convertView.findViewById(R.id.tvgroup_delete_icon);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tvgroup.setText(String.valueOf(position + 1) + "-");
holder.tvgroup1.setText(result.get(position));
// holder.img.setImageResource(imageId[position]);
holder.tvgroup_delete_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GroupMakerG.GroupOfNames.remove(position);
GroupMakerG.MainGroup.invalidateViews();
if (GroupMakerG.arraySugestion.size() > 0) {
GroupMakerG.arraySugestion.clear();
GroupMakerG.makeSuggestions();
} else {
GroupMakerG.makeSuggestions();
}
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.No_Of_Groups.setText("");
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
GroupMakerG.GroupNameLength.setText(String.valueOf(GroupMakerG.GroupOfNames.size()));
}
});
holder.tvgroup1.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context );
builder.setTitle("Modify Item No." + " " + (position + 1));
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(context).inflate(R.layout.modify_name_mainlist, (ViewGroup) parent.findViewById(android.R.id.content), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.client_name_input);
input.setText(GroupMakerG.GroupOfNames.get(position));
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
String m_Text = input.getText().toString();
if (m_Text.trim().equals("")) {
// Toast.makeText(context, "You should enter name", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(context,context.getString(R.string.group_you_should_enter_name), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
GroupMakerG.GroupOfNames.set(position, m_Text);
GroupMakerG.MainGroup.invalidateViews();
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
Toast toast = Toast.makeText(context, context.getString(R.string.group_item_changed), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return false;
}
});
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+ result.get(position), Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Second GridView Adapter
public class GroupGeneratedAdapterG extends BaseAdapter {
private ArrayList<String> resultg;
int[] imageId;
private static LayoutInflater inflaterg = null;
private static int generated_group_counter;
Context contextg;
GroupGeneratedAdapterG(GroupMakerG groupMaker, ArrayList<String> UserNameoutput) {
// TODO Auto-generated constructor stub
resultg = UserNameoutput;
contextg = groupMaker;
// imageId=prgmImages;
inflaterg = (LayoutInflater) contextg.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
generated_group_counter = 0;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return resultg.size();
}
#Override
public Object getItem(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
#Override
public long getItemId(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
public class Holder {
TextView tvgroupg, tvgroup1g;
// ImageView img;
}
#Override
public View getView(final int positiong, View convertViewg, ViewGroup parentg) {
// TODO Auto-generated method stub
generated_group_counter = generated_group_counter + 1;
Holder holderg = new Holder();
// View rowView;
if (convertViewg == null) {
convertViewg = inflaterg.inflate(R.layout.group_generated_generated, parentg, false);
}
holderg.tvgroupg = (TextView) convertViewg.findViewById(R.id.tvgroupg);
holderg.tvgroup1g = (TextView) convertViewg.findViewById(R.id.tvgroup1g);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
String[] ary = resultg.get(positiong).split("!##%");
if (ary[1].length() > 4) {
if (ary[1].substring(0, 5).equals("Group")) {
holderg.tvgroupg.setText("");
holderg.tvgroup1g.setText(ary[1]);
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
convertViewg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(contextg, "You Clicked "+ String.valueOf(resultg.get(positiong)), Toast.LENGTH_LONG).show();
}
});
return convertViewg;
}
}

how to remove the empty cell of custom list-view in my android application

Hi i am doing an application in which i want to show the content depending on the custom and the public ,data is coming from the sever.i am receiving the is_public as a parameter value as 0 and 1 if it is 1 it for public, we need to display to all user if t is 0,we need to display only the custom member like user id 8,10. for rest of the user the received content like user id 11 need to be invisible.
i able to make invisible the content, when i invisible it it is taking blank space in the list view how to remove the blank space i am posting my adapter class below
please help me
public class PlacementsBoardAdapter extends BaseAdapter{
private ArrayList<PlacementsBoardModel> listData;
private LayoutInflater layoutInflater;
ArrayList<PlacementsBoardModel> listData1;
public ImageLoader imageLoader;
DisplayImageOptions profile_options;
ImageView imageview;
private Context prova;
Bitmap bit_map_image;
int isPublic;
String custom;
public PlacementsBoardAdapter(Context context,ArrayList<PlacementsBoardModel> listData){
this.listData = listData;
listData1=listData;
prova = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
imageLoader =imageLoader.getInstance();
profile_options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.pdfimage)
.showImageForEmptyUri(R.drawable.pdfimage)
.showImageOnFail(R.drawable.pdfimage)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
final ViewHolder holder;
if (layoutInflater == null)
layoutInflater = (LayoutInflater) prova.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.placementsboardcutomview, null);
holder = new ViewHolder();
/*holder.title_of_placesment = (TextView) convertView.findViewById(R.id.title_of_placesment);
holder.pdf_image_custom=(ImageView)convertView.findViewById(R.id.pdf_image_custom);
holder.created_date = (TextView) convertView.findViewById(R.id.created_date);*/
holder.title_of_placesment = (TextView) convertView.findViewById(R.id.noticetopic);
holder.pdf_image_custom=(ImageView)convertView.findViewById(R.id.notice_title_name_image);
holder.readmore=(TextView)convertView.findViewById(R.id.readmore);
holder.placement_etext = (TextView) convertView.findViewById(R.id.noticetext);
holder.readmorelayout=(RelativeLayout)convertView.findViewById(R.id.bottom_layout);
holder.created_date = (TextView) convertView.findViewById(R.id.createddate);
holder.placementCustomLinear=(LinearLayout)convertView.findViewById(R.id.placementCustomLinear);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
final PlacementsBoardModel placementboardItem = (PlacementsBoardModel) listData.get(position);
holder.title_of_placesment.setText(placementboardItem.getTitle());
holder.created_date.setText(placementboardItem.getCreated_date());
holder.placement_etext.setText(placementboardItem.getDescription());
String description=placementboardItem.getDescription();
isPublic=placementboardItem.getIsPublic();
custom=placementboardItem.getCustom();
if (description!=null&&!placementboardItem.getDownload_file_path().contains("null")) {
holder.placement_etext.setVisibility(View.VISIBLE);
holder.pdf_image_custom.setVisibility(View.VISIBLE);
if(isPublic==0&&Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}
if (description.length()>350) {
holder.placement_etext.setText(placementboardItem.getDescription().trim().subSequence(0, 300)+"....");
holder.readmorelayout.setVisibility(View.VISIBLE);
}
}
else if(description!=null&&placementboardItem.getDownload_file_path().contains("null")){
if (description.length()>350) {
holder.placement_etext.setText(placementboardItem.getDescription().trim().subSequence(0, 300)+"....");
holder.readmorelayout.setVisibility(View.VISIBLE);
}
else{
holder.readmorelayout.setVisibility(View.GONE);
holder.placement_etext.setVisibility(View.VISIBLE);
holder.pdf_image_custom.setVisibility(View.GONE);
}
}
if(placementboardItem.getDescription().contains("null")&&!placementboardItem.getDownload_file_path().contains("null")) {
holder.placement_etext.setVisibility(View.GONE);
holder.pdf_image_custom.setVisibility(View.VISIBLE);
holder.readmorelayout.setVisibility(View.GONE);
}
//holder.pdf_image_custom.setBackground(background)
if (placementboardItem.getDownload_file_type().contains("jpg")||placementboardItem.getDownload_file_type().contains("jpeg")||placementboardItem.getDownload_file_type().contains("png")) {
Log.i("only jpg or png", "tittle the file for display");
if (placementboardItem.getTitle().length()>=20) {
holder.title_of_placesment.setText(placementboardItem.getTitle().trim().subSequence(0, 20)+"....");
//holder.imageview.setImageBitmap(noticeboardItem.getBit_image());
}else{
//noticeboardItem.getBit_image()
holder.title_of_placesment.setText(placementboardItem.getTitle());
holder.pdf_image_custom.setImageBitmap(bit_map_image);
}
} else {
if (placementboardItem.getTitle().length()>=20) {
holder.title_of_placesment.setText(placementboardItem.getTitle().trim().subSequence(0, 20)+"....");
//holder.imageview.setImageResource(R.drawable.pdfimage);
}else{
holder.title_of_placesment.setText(placementboardItem.getTitle());
//holder.imageview.setImageResource(R.drawable.pdfimage);
Log.i("only pdf", "only pdf");;
}
}
if(isPublic==1&&!Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}
holder.pdf_image_custom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PlacementsBoardModel notice_data = (PlacementsBoardModel) listData.get(position);
/*String title=notice_data.getTitle();
String description=notice_data.getDescription();
Intent intent = new Intent(prova,DscriptionDisplay.class);
intent.putExtra("title",title);
intent.putExtra("description",description);
prova.startActivity(intent);*/
if (notice_data.getDownload_file_type().contains("jpg")||notice_data.getDownload_file_type().contains("gif")||notice_data.getDownload_file_type().contains("jpeg")||notice_data.getDownload_file_type().contains("png")) {
Log.i("only jpg or png", "tittle the file for display");
Intent intent1 = new Intent(prova,NoticeBoardImageDisplayActivity.class);
intent1.putExtra("noticeimagelink",notice_data.getDownload_file_path());
intent1.putExtra("noticetitle",notice_data.getTitle());
prova.startActivity(intent1);
} else {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(notice_data.getDownload_file_path()));
prova.startActivity(browserIntent);
Log.i("only pdf", "only pdf");
}
notifyDataSetChanged();
}
});
holder.readmore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//placementboardItem = (PlacementsBoardModel) listData.get(position);
String title=placementboardItem.getTitle();
String description=placementboardItem.getDescription();
Intent intent = new Intent(prova,DscriptionDisplay.class);
intent.putExtra("title",title);
intent.putExtra("description",description);
prova.startActivity(intent);
notifyDataSetChanged();
}
});
imageLoader.displayImage(placementboardItem.getDownload_file_path(), holder.pdf_image_custom, profile_options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//bit_map_image=loadedImage;
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current,
int total) {
}
}
);
notifyDataSetChanged();
return convertView;
}
static class ViewHolder{
RelativeLayout readmorelayout;
TextView placement_etext;
TextView readmore;
TextView title_of_placesment;
TextView created_date;
ImageView pdf_image_custom;
LinearLayout placementCustomLinear;
}
}
holder.placementCustomLinear is the custom leaner-layout need to be make it invisible
After some research i have solved my problem by adding a parent layout in the the xml and adding the some logic in the adapter class like
if (Util.ROLE.equalsIgnoreCase("admin")) {
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}else
if(isPublic==0){
Log.i("inside if ", ""+isPublic);
Log.i("custom disply", custom);
int[] arry= stringToInteger(custom);
Log.i("numbers to ccheck ", ""+(arry));
for (int i = 0; i < arry.length; i++) {
if(custom.contains(Util.USER_ID)){
Log.i("true checked ", "inside");
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}else{
holder.placementCustomLinear.setVisibility(View.GONE);
notifyDataSetChanged();
}
}
if(isPublic==0&&Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
}
else{
Log.i("else block ",""+isPublic);
if(isPublic==1)
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
my problem is solved thanks for the people who have give some suggestion

My listview won't update in fragment

My ListView won't refresh after I key in new data. It will only refresh if I change tabs. I put in notifyDataSetChange() but it still doesn't work. Help!
public class Tab4 extends Fragment {
TextView title;
TextView DateTitle;
TextView AmountTitle;
TextView DescTitle;
ListView ExpensesList;
List<Expenses> Expenses;
Expenses expenses;
ExpensesListAdapter adapter;
Toast mToast;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.tab4, container, false);
title = (TextView) rootView.findViewById(R.id.Title);
DateTitle = (TextView) rootView.findViewById(R.id.DateTitle);
AmountTitle = (TextView) rootView.findViewById(R.id.AmountTitle);
DescTitle = (TextView) rootView.findViewById(R.id.DescTitle);
ExpensesList = (ListView) rootView.findViewById(R.id.ExpensesList);
Expenses = new ArrayList<Expenses>();
expenses = new Expenses();
mToast = Toast.makeText(getActivity().getApplicationContext(), "",
Toast.LENGTH_SHORT);
ExpensesList.setAdapter(adapter);
adapter = new ExpensesListAdapter(
getActivity().getApplicationContext(), Expenses);
if (expenses.getAllExpenses().size() == 0) {
title.setText("Total number of record is 0");
DateTitle.setVisibility(View.GONE);
AmountTitle.setVisibility(View.GONE);
DescTitle.setVisibility(View.GONE);
} else {
for (int i = 0; i < expenses.getAllExpenses().size(); i++) {
Expenses.add(expenses.getAllExpenses().get(i));
System.out.println("Expenses are "
+ expenses.getAllExpenses().get(i));
adapter.notifyDataSetChanged();
ExpensesList.invalidateViews();
}
title.setText("Total number of record is "
+ expenses.getAllExpenses().size());
}
ExpensesList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setMessage("ARE YOU SURE YOU WANT TO DELETE THIS RECORD?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
expenses = new Expenses();
expenses = expenses.getAllExpenses().get(
position);
expenses.delete();
Expenses.remove(position);
adapter.notifyDataSetChanged();
title.setText("Total number of record is "
+ expenses.getAllExpenses().size());
mToast.setText("Record has been deleted");
mToast.show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
builder.show();
return false;
}
});
return rootView;
}
}
class ExpensesListAdapter extends BaseAdapter {
List<Expenses> Expenses;
Context context;
LayoutInflater inflater;
public ExpensesListAdapter(Context context, List<Expenses> Expenses) {
this.context = context;
this.Expenses = Expenses;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Expenses.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 Date;
TextView Amount;
TextView Desc;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
convertView = inflater.inflate(R.layout.listview_expenseslist, null);
holder.Date = (TextView) convertView.findViewById(R.id.ExpensesDate);
holder.Amount = (TextView) convertView
.findViewById(R.id.ExpensesAmount);
holder.Desc = (TextView) convertView.findViewById(R.id.ExpensesDesc);
holder.Date.setText(Expenses.get(position).Date);
holder.Amount.setText(String.valueOf(Expenses.get(position).Amount));
holder.Desc.setText(Expenses.get(position).Desc);
return convertView;
}
}
My listview won't refresh after i key in new data. It will only
refresh if i change tabs.
Becuase currently adding new data in Expenses ArrayList.
To update new item in ListView Adapter, need to add item in data-sorcude which is used inside adapter for getting data and getCount` method.
To achive same create a method in ExpensesListAdapter :
public void addAllItem(List<Expenses> strItem){
this.Expenses.addAll(strItem);
this.notifyDataSetChanged();
}
Now call addNewItem method to add new item when AlertDialog positive button click :
adapter.addNewItem(expenses.getAllExpenses());

ListView not showing right item after filtering

Its been a week since I'm stuck with this problem.
I developed an application with a listView and editText to make a search. When I make a search the new list is showed very well but when I click on the item it redirect me to the item of the inicial list.
I don't know what to do please help me. These are my codes.
-For the ReaderListAdapter :
public class ReaderListAdapter extends BaseAdapter {
ArrayList<Reader> listReader = new ArrayList<Reader>();
ArrayList<Reader> arrayList;
LayoutInflater layoutInflater;
Context context;
int lastPosition = -1;
// constructeur
public ReaderListAdapter(Context context, ArrayList<Reader> listReader) {
this.listReader = listReader;
this.context = context;
arrayList = new ArrayList<Reader> ();;
layoutInflater = LayoutInflater.from(this.context);
arrayList.addAll(listReader);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position).getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,(position > lastPosition)
? R.anim.up_from_bottom: R.anim.up_from_bottom);
convertView.startAnimation(animation);
position=lastPosition;
return convertView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
listReader.clear();
if(charText.length()==0){
listReader.addAll(arrayList);
}
else{
for (Reader c : arrayList) {
if (c.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
listReader.add(c);
}
}
}
notifyDataSetChanged();
}
}
-For the MainActivity:
public class MainActivity extends Activity {
String[] listNames = { "kooora","yahoo", "hespress"};
int[] listPrices = { 1, 2, 3 };
ArrayList<Reader> listReader = new ArrayList<Reader>();;
ArrayList<Reader> listReaderNew;
ListView lv;
EditText search;
ReaderListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {getResources().getDrawable(R.drawable.a1),getResources().getDrawable(R.drawable.a2),getResources().getDrawable(R.drawable.a3)};
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i], listPrices[i]));
}
adapter=new ReaderListAdapter(getApplicationContext(), listReader);
lv.setAdapter(adapter);
//lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReader));
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
MainActivity.this.adapter.filter(text);
}});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.kooora.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.hespress.com")) ;break; }if (intent != null) {
startActivity(intent);
}}});}}
Please help me. Thanks in advance!
I think the code in onItemClick is causing this.
The problem:
searchTerm = "yahoo"
You filter yahoo and show the listitem for yahoo. Lets says its position in the list is 0. When the user clicks it, the onItemClick will be called and case 0: will be executed.
The correct logic should be,
Reader reader = parent.getAdapter().getItem(position);
String searchTerm = reader.getName(); // or whichever is the id for that listitem
if(searchTerm.contains("yahoo")) {
intent.setData(Uri.parse("http://www.yahoo.com"))
} // and so on

BaseAdapter selecting item issue

I have a ListView which extends BaseAdapter. I have a array list. The ListView inflates and populates correctly. I am using the flipper view to change the layout to another but the problem is when i clicked on the first item it rotate but the item at third or sixth row will also rotate
list view how can i fix it i only want the image is change of selected item
ArrayList<product_data> al=new ArrayList<product_data>();
class product_data
{
String post_title;
String newprice;
String oldprice;
String image;
String id;
product_data(String post_title,String newprice,String oldprice,String image,String id)
{
this.post_title=post_title;
this.newprice=newprice;
this.oldprice=oldprice;
this.image=image;
this.id=id;
}
}
to add data in arraylist
try {
JSONObject parentObject = new JSONObject(json.toString());
JSONObject userDetails = parentObject.getJSONObject("response");
JSONArray jarray=userDetails.getJSONArray("products_data");
for(int i=0;i<jarray.length();i++)
{
System.out.println("From the Dataaaa");
JSONObject c = jarray.getJSONObject(i);
String details=c.getString("details");
String image=c.getString("image");
String catagory=c.getString("catagory");
String new_price=c.getString("new_price");
String title=c.getString("title");
String id1=c.getString("id");
System.out.println("from ther first image"+image);
System.out.println("from the sdafdfadf"+details);
al.add(new product_data(title, new_price, new_price, image, id1));
Adapter class
class MyAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return al.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return al.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View singleView, ViewGroup parent) {
// TODO Auto-generated method stub
final int ok=position;
if(singleView==null)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
singleView = inflater.inflate(R.layout.product_ist_layout,parent,false);
System.out.println("from the if"+position);
viewAnimator = (ViewAnimator)singleView.findViewById(R.id.viewFlipper);
rootLayout = (View)singleView.findViewById(R.id.main_activity_root);
cardFace = (View)singleView.findViewById(R.id.main_activity_card_face);
cardBack = (View) singleView.findViewById(R.id.main_activity_card_back);
}
System.out.println("from the else");
System.out.println("Position in else"+position);
product_data a=al.get(position);
TextView tv1=(TextView)singleView.findViewById(R.id.textView2);
TextView tv2=(TextView)singleView.findViewById(R.id.textView3);
TextView tv3=(TextView)singleView.findViewById(R.id.textView1);
/**
* Bind a click listener to initiate the flip transitions
*/
viewAnimator.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// This is all you need to do to 3D flip
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
cardFace.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("positon"+ok);
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
cardBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
imgview1=(ImageView)singleView.findViewById(R.id.imageView4);
imgview1.setTag(position);
imgview1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println(position1);
String id=al.get(position1).id;
System.out.println("id from the list"+id);
Intent in=new Intent(product_list_Activity.this,rating_dialog.class);
in.putExtra("id",id);
startActivity(in);
}
});
ImageView imgview2=(ImageView)singleView.findViewById(R.id.imageView5);
imgview2.setTag(position);
imgview2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println(position1);
String id=al.get(position1).id;
System.out.println("id from the list"+id);
Intent in=new Intent(product_list_Activity.this,product_review.class);
in.putExtra("id",id);
startActivity(in);
}
});
tv3.setTag(position);
tv3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println("from the review "+position1);
String id=al.get(position1).id;
globalvariables.product_id=id;
Intent in=new Intent(getApplicationContext(),review_product_tabbar.class);
startActivity(in);
}
});
tv1.setText(a.post_title);
tv2.setText("$"+a.oldprice);
tv1.setTypeface(tf);
tv2.setTypeface(tf);
tv3.setTypeface(tf);
int loader = R.drawable.ic_launcher;
ImageView image = (ImageView)singleView. findViewById(R.id.imageView1);
imgLoader.DisplayImage(a.image, loader, image);
Animation anim = new Rotate3dAnimation(90.0f, 0.0f, 100.0f, false, singleView);
anim.setDuration(1000l);
singleView.startAnimation(anim);
return singleView;
}
}
}
when i click on the first item it rotate and another view is coming
but when i scrolled the fourth item in below image will also rotate
i am using the on click listner on the relative views as in the code
I have one idea on click of image first try to get Position and when you get Position then set new image background at that position.

Categories

Resources