Delete/Remove position of a list view when timer completes - android

I am using list view with each and every row has its own timer.I want to delete the position of a list view when timer is completed its time interval.I had implemented as below but position is always catching wrongly and last item is deleting every time.Please see my code below,inside onfinish() of timer i am trying to remove the position but it is not getting deleted properly, help me.
ProductListAdapter.java
package com.devpoint.adapter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.w3c.dom.Document;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Html;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TableLayout;
import android.widget.TextView;
import com.devpoint.PlacesandMaps.GMapV2Direction;
import com.devpoint.PlacesandMaps.PlacesMapActivity;
import com.devpoint.common.GetAllGooglePlaces;
import com.devpoint.model.ListDetails;
import com.devpoint.rprtgnet.LoadActivity;
import com.devpoint.rprtgnet.MapFragmentActivity;
import com.devpoint.rprtgnet.R;
import com.devpoint.sharedpreferences.SharedPreference;
import com.devpoint.tabsswipe.ListOnGoing;
import com.devpoint.tabsswipe.SwipeViewPagerAdapter;
import com.devpoint.user.PostLogcatErrors;
import com.devpoint.volley.AppController;
import com.google.android.gms.maps.GoogleMap;
import com.squareup.picasso.Picasso;
import android.view.animation.Transformation;
#SuppressLint({ "InflateParams", "ShowToast" })
public class ProductListAdapter extends ArrayAdapter<ListDetails> {
private Activity context;
List<ListDetails> products;
SharedPreference sharedPreference;
public static com.android.volley.toolbox.ImageLoader imageLoader;
LayoutInflater inflater;
//ViewHolder holder;
protected String Day = "";
public static View alertLayout;
private static GMapV2Direction gmapdirection;
public static GoogleMap gmap;
protected Document doc;
static final int ANIMATION_DURATION = 200;
//TextView timer;
//String Pagename;
private HashMap<TextView,CountDownTimer> counters;
static class TestViewHolder
{
public TextView tvCounter;
}
public ProductListAdapter(Context context, List<ListDetails> products) {
super(context, R.layout.adapter_offer_list_item, products);
this.context = (Activity) context;
this.products = products;
sharedPreference = new SharedPreference();
imageLoader = AppController.getInstance().getImageLoader();
this.counters = new HashMap<TextView, CountDownTimer>();
inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder {
TextView productNameTxt;
//TextView Ratingsno;
TextView productPriceTxt;
//TextView timedist;
TableLayout distancesection;
TextView categoryname;
ImageView favoriteImg;
RatingBar rb;
ImageView OfferImage;
//ImageView MapImage;
ImageView listimage;
public TextView distance;
public ImageView indicator;
TextView timer;
TextView move;
//TextView Postedon;
}
#Override
public int getCount() {
return products.size();
}
#Override
public ListDetails getItem(int position) {
return products.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int po, View convertView, final ViewGroup parent) {
try {
ViewHolder holder = null;
Day = "";
final ListDetails product = products.get(po);
//final int abc = po;
/*LayoutInflater li = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);*/
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.offerlist_new, parent,
false);
final View v= convertView;
// convertView.requestLayout();
holder.productNameTxt = (TextView) convertView
.findViewById(R.id.name);
holder.productPriceTxt = (TextView) convertView
.findViewById(R.id.listview_description);
holder.distance = (TextView) convertView
.findViewById(R.id.listview_distane);
/*holder.timedist = (TextView) convertView
.findViewById(R.id.timedist);*/
/*holder.Ratingsno = (TextView) convertView
.findViewById(R.id.Ratingsno);*/
/*holder.Postedon = (TextView) convertView
.findViewById(R.id.Postedon);*/
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.fav_checkbox);
holder.rb = (RatingBar) convertView
.findViewById(R.id.ratingbar);
holder.timer = (TextView) convertView.findViewById(R.id.time);
holder.categoryname = (TextView) convertView
.findViewById(R.id.Categoryname);
holder.listimage = (ImageView) convertView
.findViewById(R.id.list_image);
/*holder.distancesection = (TableLayout) convertView
.findViewById(R.id.distancesection);*/
/*holder.MapImage = (ImageView) convertView
.findViewById(R.id.imgmap);*/
holder.move = (TextView) convertView
.findViewById(R.id.listview_description3);
holder.move.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
removeListItem(v,po) ;
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
});
String text = "<font color=#222222>" + product.getShopName()
+ "</font>"
+ "<small><font color=#0091EA> ( </font></small>"
+ " <small><font color=#0091EA>" + product.getAreaName()
+ "</font></small>"
+ "<small><font color=#0091EA> ) </font></small>";
holder.productNameTxt.setText(Html.fromHtml(text));
// holder.productNameTxt.setText(product.getShopName() + " " + "( "
// + Html.fromHtml("<font color='#0091EA'>" + product.getAreaName()
// + "</font>") + " )");
holder.productPriceTxt.setText(product.getDeal() + "");
holder.rb.setRating(Float.valueOf(product.getRatingAvg()));
//holder.Ratingsno.setText(product.getTotalRatings() + " Ratings");
//holder.timedist.setText(product.getTime());
holder.distance.setText(String.valueOf(product.getDistance())
+ " Km");
holder.categoryname.setText(product.getCategoryName());
//holder.listimage.setImageUrl(product.getListImage(), imageLoader);
Picasso.with(context).load(product.getListImage()).into(holder.listimage);
if (checkFavoriteItem(product)) {
holder.favoriteImg.setImageResource(R.drawable.checked);
holder.favoriteImg.setTag(context
.getString(R.string.red_favcolor));
} else {
holder.favoriteImg.setImageResource(R.drawable.unchecked);
holder.favoriteImg.setTag(context
.getString(R.string.grey_favcolor));
}
/*holder.Postedon.setText("Posted On" + " "
+ product.getPostedDate());*/
final TextView tv = holder.timer;
CountDownTimer cdt = counters.get(tv);
if(cdt!=null)
{
cdt.cancel();
cdt=null;
}
cdt = new CountDownTimer(Long.parseLong(product.getOfferEndTime()), 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
int minutes = 0;
int seconds = 0;
String sDate = "";
if(millisUntilFinished > DateUtils.MINUTE_IN_MILLIS)
{
minutes = (int) (millisUntilFinished / DateUtils.MINUTE_IN_MILLIS);
}
millisUntilFinished -= (minutes*DateUtils.MINUTE_IN_MILLIS);
if(millisUntilFinished > DateUtils.SECOND_IN_MILLIS)
{
seconds = (int) (millisUntilFinished / DateUtils.SECOND_IN_MILLIS);
}
sDate += " "+"00"+":"+String.format("%02d",minutes)+":"+String.format("%02d",seconds);
tv.setText(sDate.trim());
}
#Override
public void onFinish() {
tv.setText("Finished");
final int abc = po;
final Animation animation = AnimationUtils.loadAnimation(
context, android.R.anim.slide_in_left);
v.startAnimation(animation);
Handler handle = new Handler();
handle.postDelayed(new Runnable() {
public void run() {
products.remove(abc);
ListOnGoing.productListAdapter = new ProductListAdapter(
LoadActivity.activity, products);
ListOnGoing.swipelisview
.setAdapter(ListOnGoing.productListAdapter);
ListOnGoing.productListAdapter.notifyDataSetChanged();
}
}, 1000);
}
};
counters.put(tv, cdt);
cdt.start();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
return convertView;
}
/* Checks whether a particular product exists in SharedPreferences */
public boolean checkFavoriteItem(ListDetails checkProduct) {
boolean check = false;
List<ListDetails> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (ListDetails product : favorites) {
/*
* if (product.equals(checkProduct)) { check = true; break; }
*/
if (product.getOfferID().equals(checkProduct.getOfferID())) {
check = true;
break;
}
}
}
return check;
}
public void cancelAllTimers()
{
Set<Entry<TextView, CountDownTimer>> s = counters.entrySet();
Iterator it = s.iterator();
while(it.hasNext())
{
try
{
Map.Entry pairs = (Map.Entry)it.next();
CountDownTimer cdt = (CountDownTimer)pairs.getValue();
cdt.cancel();
cdt = null;
}
catch(Exception e){}
}
it=null;
s=null;
counters.clear();
}
}

If abc is declared as a field of your class (e. g. private int abc), you are assigning po to abc each time getView gets called. Later, when you call
products.remove(abc);
You are removing an element with index of the last assigned value of abc, which most probably is index of the last element.
Replace the above line with
products.remove(po);
or change
abc = po;
to
final int abc = po;
Also try doing a similar thing with the following line:
holder = null;

Related

How to Improve List Performance when Timer is running inside each row

i am using timer to show count down of each list list row item.But Listview Performance is very slow while running the timer. Is there any solution to increase performance of a listview with timer.please see below code and suggest me changes.
package com.devpoint.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.RP.database.Repo;
import com.RPRT.database.model.ReserveTable;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.devpoint.PlacesandMaps.GMapV2Direction;
import com.devpoint.PlacesandMaps.PlacesMapActivity;
import com.devpoint.common.GetAllGooglePlaces;
import com.devpoint.common.BackStackingManager.ModuleFragmentBackStackingClass;
import com.devpoint.common.BackStackingManager.ModulesTagsClass.EnumModuleTags;
import com.devpoint.model.ListDetails;
import com.devpoint.retailer.Retailers_Login_Page;
import com.devpoint.rprtgnet.LoadActivity;
import com.devpoint.rprtgnet.MapFragmentActivity;
import com.devpoint.rprtgnet.R;
import com.devpoint.rprtgnet.SplashScreen;
import com.devpoint.sharedpreferences.SessionManager;
import com.devpoint.sharedpreferences.SharedPreference;
import com.devpoint.tabsswipe.ListOngoing;
import com.devpoint.tabsswipe.SwipeViewPagerAdapter;
import com.devpoint.user.DetailsViewpagerFragment;
import com.devpoint.user.PostLogcatErrors;
import com.devpoint.volley.AppController;
import com.google.android.gms.maps.GoogleMap;
import com.squareup.picasso.Picasso;
import android.view.animation.Transformation;
#SuppressLint({ "InflateParams", "ShowToast" })
public class ProductListAdapter extends ArrayAdapter<ListDetails> {
private Activity context;
CopyOnWriteArrayList<ListDetails> products;
SharedPreference sharedPreference;
public static com.android.volley.toolbox.ImageLoader imageLoader;
LayoutInflater inflater;
//ViewHolder holder;
protected String Day = "";
public static View alertLayout;
private static GMapV2Direction gmapdirection;
public static GoogleMap gmap;
protected Document doc;
static final int ANIMATION_DURATION = 200;
String Key;
ProductListAdapter adproductListAdapter;
ListView adswipelisview;
//TextView timer;
ListDetails product;
SessionManager session;
long blobkedmilliseconds=0;
//String Pagename;
private HashMap<TextView,CountDownTimer> counters;
private View v;
private Repo repoObject;
TextView available;
static class TestViewHolder
{
public TextView tvCounter;
}
public ProductListAdapter(Context context, CopyOnWriteArrayList<ListDetails> products, ProductListAdapter productListAdapter, ListView swipelisview) {
super(context, R.layout.adapter_offer_list_item, products);
this.context = (Activity) context;
this.products = products;
sharedPreference = new SharedPreference();
imageLoader = AppController.getInstance().getImageLoader();
adproductListAdapter=productListAdapter;
adswipelisview=swipelisview;
this.counters = new HashMap<TextView, CountDownTimer>();
session = SessionManager.getInstance(context);
inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder {
TextView productNameTxt;
//TextView Ratingsno;
TextView productPriceTxt;
//TextView timedist;
TableLayout distancesection;
TextView categoryname;
TextView Modulename;
//ImageView favoriteImg;
RatingBar rb;
ImageView OfferImage;
//ImageView MapImage;
ImageView listimage;
public TextView distance;
public ImageView indicator;
TextView timer;
TextView move;
TextView areaname;
Button blockornotifybtn;
//TextView Postedon;
}
#Override
public int getCount() {
return products.size();
}
#Override
public ListDetails getItem(int position) {
return products.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("ResourceAsColor")
#Override
public View getView(final int po, View convertView, final ViewGroup parent) {
try {
ViewHolder holder = null;
Day = "";
product = products.get(po);
v= convertView;
session.createPageID(String.valueOf(po));
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.listitem_final, parent,
false);
holder.productNameTxt = (TextView) convertView
.findViewById(R.id.name);
holder.productPriceTxt = (TextView) convertView
.findViewById(R.id.listview_description);
holder.distance = (TextView) convertView
.findViewById(R.id.listview_distane);
holder.rb = (RatingBar) convertView
.findViewById(R.id.ratingbar);
holder.timer = (TextView) convertView.findViewById(R.id.time);
holder.categoryname = (TextView) convertView
.findViewById(R.id.Categoryname);
holder.Modulename = (TextView) convertView
.findViewById(R.id.modulename);
holder.listimage = (ImageView) convertView
.findViewById(R.id.list_image);
holder.blockornotifybtn = (Button)convertView
.findViewById(R.id.blockornotifybtn);
holder.areaname = (TextView) convertView
.findViewById(R.id.areaname);
available = (TextView) convertView
.findViewById(R.id.available);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Typeface type = Typeface.createFromAsset(context.getAssets(),"fonts/roboto/Oswald-Regular.ttf");
holder.productNameTxt.setTypeface(type);
holder.distance.setTypeface(type);
available.setText("Available: "+product.getAvailable());
available.setTypeface(type);
holder.productNameTxt.setText(product.getShopName());
holder.areaname.setText(product.getAreaName());
repoObject = SplashScreen.getRepo();
ReserveTable Reserved = repoObject.rReserveoffer
.getByOpportunityId(Integer.parseInt(product.getOfferID()));
if(Reserved==null)
{
holder.blockornotifybtn.setBackgroundResource(R.drawable.block);
holder.blockornotifybtn.setEnabled(true);
available.setVisibility(View.VISIBLE);
blobkedmilliseconds = 0;
}
else
{
holder.blockornotifybtn.setBackgroundResource(R.drawable.blocked);
holder.blockornotifybtn.setEnabled(false);
available.setVisibility(View.GONE);
blobkedmilliseconds = 300000;
}
holder.Modulename.setText(product.getModuleId());
holder.productPriceTxt.setText(product.getDeal() + "");
holder.rb.setRating(Float.valueOf(product.getRatingAvg()));
holder.distance.setText(String.valueOf(product.getDistance())
+ " Km");
holder.categoryname.setText(product.getCategoryName());
Picasso.with(context).load(product.getListImage()).into(holder.listimage);
final TextView tv = holder.timer;
CountDownTimer cdt = counters.get(tv);
if(cdt!=null)
{
cdt.cancel();
cdt=null;
}
cdt = new CountDownTimer(product.getOfferDifferenceTime()+blobkedmilliseconds, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
int minutes = 0;
int seconds = 0;
String sDate = "";
if(millisUntilFinished > DateUtils.MINUTE_IN_MILLIS)
{
minutes = (int) (millisUntilFinished / DateUtils.MINUTE_IN_MILLIS);
}
millisUntilFinished -= (minutes*DateUtils.MINUTE_IN_MILLIS);
if(millisUntilFinished > DateUtils.SECOND_IN_MILLIS)
{
seconds = (int) (millisUntilFinished / DateUtils.SECOND_IN_MILLIS);
}
sDate += " "+"00"+":"+String.format("%02d",minutes)+":"+String.format("%02d",seconds);
tv.setText(sDate.trim());
}
#Override
public void onFinish() {
tv.setText("Finished");
final Animation animation = AnimationUtils.loadAnimation(
context, android.R.anim.slide_in_left);
// v.startAnimation(animation);
Handler handle = new Handler();
handle.postDelayed(new Runnable() {
public void run() {
if(v!=null)
{
((Activity) v.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
CopyOnWriteArrayList<ListDetails> produc = new CopyOnWriteArrayList<>();
for (ListDetails Pro : products) {
if(Pro.getOfferDifferenceTime()<0)
{
// produc.add(Pro);
}
else
{
produc.add(Pro);
}
}
adproductListAdapter = new ProductListAdapter(
LoadActivity.activity, produc,adproductListAdapter,adswipelisview);
adswipelisview
.setAdapter(adproductListAdapter);
adproductListAdapter.notifyDataSetChanged();
}
});
}
else
{
try {
((Activity) v.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1000);
}
};
counters.put(tv, cdt);
cdt.start();
return convertView;
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
return convertView;
}
protected JSONObject getSaveViewUserParams() {
JSONObject params = new JSONObject();
try {
params.put("BlockedUserId", session.getUserRegisterID());
params.put("OpportunityId", product.getOfferID());
params.put("BlockText","Blocked");
params.put("KeyValue", Key);
params.put("DeviceId", session.getDeviceId());
} catch (JSONException e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
return params;
}
}
I solved this differently in my case. Instead of having a timer handler set inside your getView(), I just set the time difference between the current time and your desired time to the TextView every time getView() is called. So move this code of yours back inside getView():
long outputTime = Math.abs(promoAction.timer_end
- System.currentTimeMillis());
Date date = new java.util.Date(outputTime);
String result = new SimpleDateFormat("hh:mm:ss").format(date);
tv.setText(result);
Then create a handler in the activity to call notifyDatasetChanged() every one minute on the listview's adapter:
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
myAdapter.notifyDataSetChanged();
timerHandler.postDelayed(this, 60000); //run every minute
}
};
I stop this handler on onPause():
#Override
protected void onPause() {
timerHandler.removeCallbacks(timerRunnable);
super.onPause();
}
And I start it again on onResume():
#Override
protected void onResume() {
timerHandler.postDelayed(timerRunnable, 500);
super.onResume();
}
And that's it. :)
Hope it helps. For more info ListView and items with countdown timer

NotifyDataSetChanged on gridview not working - Android

I am working with GridView. I want to update GridView on some basis. But notifyDataSetChanged() method is not working.
I am selecting tables on basis of section name. When I select section name very first time than I got tables of that section. But when I go to sections fragment again and select diff. section than I get previously selected tables only. That means notifyDataSetChanged() is not working.
What I have tried is like below.
TableScreenActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.db.DBAdapter;
import com.malaka.helper.ActionItem;
import com.malaka.helper.AssignGetterSetter;
import com.malaka.helper.Attributes;
import com.malaka.helper.CategoryAdapter;
import com.malaka.helper.DialogAdapter;
import com.malaka.helper.JoinTableAdapter;
import com.malaka.helper.ListSwipeDetector;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.AddNewCustomerAsync;
import com.malaka.helper.async.CustomerPhotoAsync;
import com.malaka.helper.async.GetValetNoAsync;
import com.malaka.helper.async.ReAssignTableAsync;
import com.malaka.helper.async.SetTableStatusAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.helper.async.UnAttendedAsync;
import com.malaka.helper.async.ValetAsync;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.PreferenceUtils;
public class TableScreenActivity extends Fragment {
final static String TAG = "TableScreenActivity";
Button btnBarCode, btnFeedBack, btnLogOut;
GridView gridView;
private TextView mDropdownTitle;
static DBAdapter dbAdapter;
TextView malaka, version;
ImageView refresh;
Animation rotation;
boolean isOpen = false;
RelativeLayout rl;
public static FragmentActivity activity;
LinearLayout mDropdownFoldOutNewCust;
TextView dropDownTextViewNewCust, alt0NewCust, alt1NewCust,
mDropdownTitleNewCust;
LinearLayout ll;
static Dialog dialogAddCust, joinDialog;
ListSwipeDetector detector;
static PreferenceUtils pref;
ArrayList<String> tableName, tableId, sectionId, tableDescriptionId,
tableDescription, custName, custId, custNo, parentId, isManager,
parentName;
ArrayList<String> isVale, isInquired;
ArrayList<Integer> tableColors;
Bundle bundle;
String name = "", no = "", custType = "", tableIds, tableDesc;
static String tableDescId;
static EditText edtName, edtNo;
int pos;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_SECTIONS = 11;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
static ArrayList<String> o_name, o_id, e_id, mTableIdList;
private CategoryAdapter categoryAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("TestTag: savedInstanceState " + savedInstanceState
+ " container: " + container);
System.out.println("TestTag: o_name " + o_name + " mTableIdList: "
+ mTableIdList);
View view = inflater.inflate(R.layout.table_screen, container, false);
init(view);
return view;
}
private void init(View view) {
System.out.println("TestTag: Time1: " + System.currentTimeMillis());
// getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity = getActivity();
o_id = new ArrayList<String>();
o_name = new ArrayList<String>();
e_id = new ArrayList<String>();
mTableIdList = new ArrayList<String>();
TextView textView = (TextView) view.findViewById(R.id.txt_table_status);
textView.setVisibility(View.GONE);
refresh = (ImageView) view.findViewById(R.id.img_refresh_table);
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
pref = new PreferenceUtils(getActivity());
version = (TextView) view.findViewById(R.id.table_version);
version.setText(pref.getVersion());
if (!pref.getTableStatus()) {
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
Log.e(TAG,
"user id : " + pref.getUserId() + "location : "
+ pref.getLocation() + "SectionId: "
+ pref.getSectionId());
map.put("UserId", pref.getUserId());
map.put("SectionId", pref.getSectionId());
map.put("Location", pref.getLocation());
Async.execute(map);
}
dbAdapter = new DBAdapter(getActivity());
dbAdapter.open();
tableId = dbAdapter.getTableId();
tableName = dbAdapter.getTableName();
sectionId = dbAdapter.getTableSectionId();
tableDescriptionId = dbAdapter.getTableDescriptionId();
tableDescription = dbAdapter.getTableDescription();
custName = dbAdapter.getTableCustName();
custId = dbAdapter.getTableCustID();
custNo = dbAdapter.getTableCustNo();
parentId = dbAdapter.getTableParentId();
parentName = dbAdapter.getTableParentName();
isVale = dbAdapter.getTableIsValeStatus();
isManager = dbAdapter.getTableIsManagerStatus();
isInquired = dbAdapter.getTableIsInquiredStatus();
dbAdapter.close();
Log.d(TAG, "Table length ==" + tableId.size());
tableColors = new ArrayList<Integer>();
for (int i = 0; i < tableDescriptionId.size(); i++) {
tableColors.add(Attributes.getColors(tableDescriptionId.get(i),
getActivity()));
}
ll = (LinearLayout) view.findViewById(R.id.table_ll);
rl = (RelativeLayout) view.findViewById(R.id.ll);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
quickActionLocation.show(arg0);
}
});
detector = new ListSwipeDetector();
malaka = (TextView) view.findViewById(R.id.txt_malaka_title_table);
malaka.setText(pref.getLocation());
gridView = (GridView) view.findViewById(R.id.gridView_table);
if (tableId.size() <= 0) {
gridView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
} else {
gridView.setVisibility(View.VISIBLE);
textView.setVisibility(View.GONE);
}
dbAdapter = new DBAdapter(getActivity());
// CategoryAdapter categoryAdapter = new CategoryAdapter(getActivity(),
// 0,
// tableName, tableColors, isInquired, custName,
// tableDescriptionId, parentId, parentName, isManager);
// gridView.setAdapter(categoryAdapter);
// categoryAdapter.notifyDataSetChanged();
//tableName.clear();
//tableName = dbAdapter.getTableName();
categoryAdapter = new CategoryAdapter(getActivity(), 0, tableName,
tableColors, isInquired, custName, tableDescriptionId,
parentId, parentName, isManager);
gridView.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
gridView.setOnTouchListener(detector);
gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
....
....
}
gridView.setOnItemClickListener(new OnItemClickListener() {
....
....
}
}// init() method closes
#Override
public void onAttach(Activity activity) {
Log.d(TAG, "TestTag::: onAttach()");
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onCreate() savedInstanceState: "
+ savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
Log.d(TAG, "TestTag::: onStart()");
super.onStart();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onActivityCreated(): savedInstanceState "
+ savedInstanceState);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResume() {
Log.d(TAG, "TestTag::: onResume()");
super.onResume();
}
#Override
public void onPause() {
Log.d(TAG, "TestTag::: onPause()");
super.onPause();
}
#Override
public void onDestroyView() {
Log.d(TAG, "TestTag::: onDestroyView()");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.d(TAG, "TestTag::: onDestroy()");
super.onDestroy();
}
#Override
public void onStop() {
Log.d(TAG, "TestTag::: onStop()");
super.onStop();
}
#Override
public void onDetach() {
Log.d(TAG, "TestTag::: onDetach()");
super.onDetach();
}
}
Please, Help. I got stuck in. Thanks advance.
EDIT
TableStatusAsync.java
package com.malaka.helper.async;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.TableScreenActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class TableStatusAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "TableStatusAsync";
FragmentActivity context;
String xml;
PreferenceUtils pref;
int response;
boolean isConnected;
public TableStatusAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.TableStatusNAMESPACE,
AsyncAttributes.TableStatusMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
// PropertyInfo pi1 = new PropertyInfo();
// pi1.setName("UserId");
// pi1.setValue(map.get("UserId"));
// pi1.setType(String.class);
//
// PropertyInfo pi2 = new PropertyInfo();
// pi2.setName("SectionId");
// pi2.setValue(map.get("SectionId"));
// pi2.setType(String.class);
//
// PropertyInfo pi3 = new PropertyInfo();
// pi3.setName("Location");
// pi3.setValue(map.get("Location"));
// pi3.setType(String.class);
//
// request.addProperty(pi1);
// request.addProperty(pi2);
// request.addProperty(pi3);
Log.e(TAG,
"user id : " + map.get("UserId") + "\nsection id : "
+ map.get("SectionId") + "\nlocation : "
+ map.get("Location"));
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.d(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.TableStatusURL);
try {
androidHttpTransport.call(
AsyncAttributes.TableStatusSOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetTableStatusResponse{GetTableStatusResult=No Table available; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.d(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.d(TAG, "Task 1 result " + xml);
TableStatusXmlParser.getTableStatusXmlParseData(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setTableStatus(true);
ReplaceFragment.getReplaceFragment(context,
new TableScreenActivity(), "");
}
}
}
EDIT - 2
CategoryAdapter.java
package com.malaka.helper;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.utils.PreferenceUtils;
public class CategoryAdapter extends ArrayAdapter<String> {
ArrayList<String> table, custName, isInquired, isManager, sectionId,
parentId, parentname;
ArrayList<Integer> tableColors;
FragmentActivity context;
ArrayList<Boolean> status;
View view;
PreferenceUtils pref;
int posision;
final static String TAG = "CategoryAdapter";
public CategoryAdapter(FragmentActivity context, int textViewResourceId,
List<String> objects, List<Integer> colors,
List<String> isInquired, List<String> custName,
List<String> sectionId, List<String> parentId,
List<String> parentname, List<String> ismanager) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
table = (ArrayList<String>) objects;
this.parentId = (ArrayList<String>) parentId;
this.parentname = (ArrayList<String>) parentname;
pref = new PreferenceUtils(context);
this.custName = (ArrayList<String>) custName;
tableColors = (ArrayList<Integer>) colors;
this.isManager = (ArrayList<String>) ismanager;
this.isInquired = (ArrayList<String>) isInquired;
this.sectionId = (ArrayList<String>) sectionId;
status = new ArrayList<Boolean>();
Log.i(TAG, "\nisInquired == " + isInquired);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
view = convertView;
ViewHolder holder = new ViewHolder();
if (convertView == null) {
Display display = context.getWindowManager().getDefaultDisplay();
int height = display.getHeight() / 8;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.table_screen_row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.txt_category_seat);
holder.txtName = (TextView) convertView
.findViewById(R.id.txt_customer_name);
holder.imageViewManager = (ImageView) convertView
.findViewById(R.id.imageView_table_manager);
holder.textViewValet = (TextView) convertView
.findViewById(R.id.text_table_valley);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, height);
holder.rl = (RelativeLayout) convertView
.findViewById(R.id.category_seat);
holder.rl.setLayoutParams(params);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// if(isVale.get(position).equals("0")){
// holder.textViewValet.setText("");
// }else{
// if(parentId.get(position).equals("0")){
// holder.textViewValet.setText(isVale.get(position));
// }
// }
Log.d(TAG, "custName == " + custName.get(position) + "\nlength == "
+ custName.get(position).length());
if (custName.get(position).length() > 9) {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position).substring(0, 8)
+ "...");
holder.textView.setText(table.get(position));
} else {
// we have to use parent table Name when Parent id is not 0
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
} else {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position));
holder.textView.setText(table.get(position));
} else {
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
}
if (isManager.get(position).equals("true")) {
holder.imageViewManager
.setBackgroundResource(R.drawable.manager_icon);
} else {
holder.imageViewManager.setBackgroundResource(0);
}
holder.rl.setBackgroundColor(tableColors.get(position));
return convertView;
}
private class ViewHolder {
TextView textView, txtName;
ImageView imageViewManager;
TextView textViewValet;
RelativeLayout rl;
}
}
At last I got the solution.
I have done like below...
I was maintaining a FLAG called getTableStatus to get the tables of particular section. If the value of getTableStatus is FALSE than only TableStatusAsync is called. At first selection of section, tables are coming from web service and those tables are being inserted in DB.
On second time, selecting of SECTION, tables are coming from DB not from web service. And tables are coming from DB are of previously selected SECTION. So, there is nothing to do with notifyDataSetChanged().
I have just change the FLAG value to FALSE by calling pref.setTableStatus(false); on selection of SECTION. Now, TableStatusAsync is called every time when you change your selection of SECTION.
Modified Code...
TableScreenSectionwiseActivity.java
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
pref.setSectionId(view.getTag().toString());
pref.setTableStatus(false);
pref.setTableServiceStatus(false);
Fragment fragment = new TableScreenActivity();
ReplaceFragment.getReplaceFragment(getActivity(), fragment, "");
}

Hinding system folder in File Picker

Question :- This code is working well for picking up the file but i want to hide system folders when I am running this code it also show me all android folder starting with "." I tried some things which you can already see in comments in my code..
FileChooser.java
package com.sarita.scheduler;
import java.io.File;
import java.sql.Date;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ListView;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fill(currentDir);
}
private void fill(File f)
{
String rootDriectory = Environment.getExternalStorageDirectory().getName(); ;
/* String chkFileName = f.getName().toString();
String chkSystemFolder =String.valueOf(chkFileName.charAt(0));
*/
File[]dirs = f.listFiles();
/*if (chkSystemFolder != "."){*/
this.setTitle("Current Dir: "+f.getName());
List<Item>dir = new ArrayList<Item>();
List<Item>fls = new ArrayList<Item>();
try{
for(File ff: dirs)
{
Date lastModDate = new Date(ff.lastModified());
DateFormat formater = DateFormat.getDateTimeInstance();
String date_modify = formater.format(lastModDate);
if(ff.isDirectory()){
File[] fbuf = ff.listFiles();
int buf = 0;
if(fbuf != null){
buf = fbuf.length;
}
else buf = 0;
String num_item = String.valueOf(buf);
if(buf == 0) num_item = num_item + " item";
else num_item = num_item + " items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(),num_item,date_modify,ff.getAbsolutePath(),"directory_icon"));
}
else
{
fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"file_icon"));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase(rootDriectory))
dir.add(0,new Item("..","Parent Directory","",f.getParent(),"directory_up"));
adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_explorer,dir);
this.setListAdapter(adapter);
/*}*/
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon")||o.getImage().equalsIgnoreCase("directory_up")){
currentDir = new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o);
}
}
private void onFileClick(Item o)
{
//Toast.makeText(this, "Folder Clicked: "+ currentDir, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("GetPath",currentDir.toString());
intent.putExtra("GetFileName",o.getName());
setResult(RESULT_OK, intent);
finish();
}
}
FileArrayAdapter.java
package com.sarita.scheduler;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FileArrayAdapter extends ArrayAdapter<Item>{
private Context c;
private int id;
private List<Item>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Item o = items.get(position);
String chkFileName = o.getName().toString();
String chkSystemFolder =String.valueOf(chkFileName.charAt(0));
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
//convertView = ( RelativeLayout ) inflater.inflate( resource, null );
if (chkSystemFolder != ".")
{
if (o != null)
{
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if (chkSystemFolder != "."){
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
if(t3!=null)
t3.setText(o.getDate());
}
}
}
return v;
}
}
Add the following as the first line in the for loop of your fill() method:
if(ff.isHidden()) continue;
The File#isHidden() returns true if the file or folder it represents is hidden; i.e. if its filename starts with '.'. The continue statement inside a loop causes the current iteration of the loop to be skipped. So, this code basically says "If this file/folder is hidden, just go to the next one."

Setting OnClickListener on items inside of ListView Item in Custom Adapter

I have created a custom Adapter for list which different items and each item has a button to invite. The item should flip horizontally when the respective invite button is clicked and that is working fine. The problem is that when I click invite button of first item then invite button of 4th item is also clicked. I am attaching the code hee
package rovoltlabs.coffeechat.adapters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rovoltlabs.coffeechat.R;
import rovoltlabs.coffeechat.animation.AnimationFactory;
import rovoltlabs.coffeechat.animation.AnimationFactory.FlipDirection;
import rovoltlabs.coffeechat.volley.utils.Const;
import rovoltslabs.coffeechat.app.AppController;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
public class MyCustomAdapter extends BaseAdapter implements OnClickListener {
Context contexts;
List<String> name = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
List<String> slots = new ArrayList<String>();
List<String> heading = new ArrayList<String>();
List<String> showtime = new ArrayList<String>();
List<Bitmap> img = new ArrayList<Bitmap>();
List<ViewHolder> myview = new ArrayList<ViewHolder>();
private String tag_json_obj = "jobj_req";
private LayoutInflater mLayoutInflater;
View row;
ViewHolder holder;
public MyCustomAdapter(Context context, List<String> name,
List<Bitmap> img, List<String> heading, List<String> slots,
List<String> id) {
super();
this.contexts = context;
this.name = name;
this.img = img;
this.heading = heading;
this.slots = slots;
this.ids = id;
mLayoutInflater = ((Activity) contexts).getLayoutInflater();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
// check to see if the reused view is null or not, if is not null then
// reuse it
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.item, null);
holder.name = (TextView) view.findViewById(R.id.Name);
holder.fname = (TextView) view.findViewById(R.id.flipName);
holder.msg = (EditText) view.findViewById(R.id.fsend);
holder.heading = (TextView) view.findViewById(R.id.ddheading);
holder.distance = (TextView) view.findViewById(R.id.Distance);
holder.image = (ImageView) view.findViewById(R.id.imagecoffee);
holder.invite = (Button) view.findViewById(R.id.inviteButton);
holder.send = (Button) view.findViewById(R.id.fsendButton);
holder.time = (TextView) view.findViewById(R.id.timefree);
holder.viewAnimator = (ViewAnimator) view
.findViewById(R.id.viewFlipper);
myview.add(holder);
holder.v = view;
} else {
holder = (ViewHolder) view.getTag();
}
view.setTag(holder);
holder.invite.setOnClickListener(this);
holder.send.setOnClickListener(this);
holder.name.setText(name.get(position).split("\n")[0]);
holder.fname.setText(name.get(position).split("\n")[0]);
holder.heading.setText(heading.get(position));
String temp = "";
int sl = Integer.parseInt(slots.get(position));
if (sl % 2 == 0) {
temp = "" + ((sl / 2) - 1) + ":30 - " + ((sl / 2)) + ":00";
} else {
temp = "" + ((sl / 2)) + ":00-" + ((sl / 2)) + ":30";
}
holder.time.setText(temp);
holder.distance.setText(name.get(position).split("\n")[1] + " m");
holder.image.setImageBitmap(img.get(position));
holder.invite.setTag(position);
holder.send.setTag(position);
return view;
}
private static class ViewHolder {
protected TextView name;
protected TextView heading;
protected TextView distance, time;
protected ImageView image;
protected Button invite, send;
protected View v;
protected ViewAnimator viewAnimator;
protected TextView fname;
protected EditText msg;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.inviteButton) {
AnimationFactory.flipTransition(
myview.get((Integer) v.getTag()).viewAnimator,
FlipDirection.LEFT_RIGHT);
} else if (v.getId() == R.id.fsend) {
SharedPreferences pref = contexts.getApplicationContext()
.getSharedPreferences("MyPref", 0);
String slotsss = "{\"slots\":[" + slots.get((Integer) v.getTag())
+ "]}";
final Map<String, String> params = new HashMap<String, String>();
params.put("slot", slotsss);
Log.e("invite slots", slotsss);
params.put("to", ids.get((Integer) v.getTag()));
params.put("from", pref.getString("id", "N/A"));
params.put("message", myview.get((Integer) v.getTag()).msg
.getText().toString());
StringRequest jsonObjReq = new StringRequest(Method.POST,
Const.URL_INVITE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Slots Response: ", response.toString());
Toast.makeText(contexts, "invited" + response,
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("invite Error:",
"Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
}
}
}
The View objects are recycling and you're using the same ViewHolder object (and other UI components) for both positions. The view being clicked has had its tag updated to the position desired, but the animation object is the same as another position due to the recycling.

on Click of text View inside a List Item not getting proper value

I have a ListView ,In that each ListItem having some items(textViews),In which one textView is having click event.That I have put in my custom adater,And I am calling an asynctask on its cLick event,For that I want a value when I click on that textView its "queID" I want,But currently I am gettong it null..Please see my code and help me please..!
"qoute" is that textView.On which I have put click event.how to set"buyer_req_Id" and get tag on it?I currrently successfully get the tag on each "ListItem" Click event ,I want to set the same tag on ListItem's textView.Inside java class I have put only adapter,In which I want "buyer_request_id".
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
java class(asynctask)
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
scr_post.setVisibility(View.GONE);
scr_view.setVisibility(View.GONE);
quote_view.setVisibility(View.VISIBLE);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// String query = "?customer_id=" +
// Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "")
// + "&buyer_request_id=23";
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + buyer_request_id;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyerID = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyerID);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyerID);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
queList.add(quote);
System.out.println(":::::::::::::Buyer request ID:" + buyerID);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
quoteAdapter = new QuoteAdapter(BuyingreqActivity.this, queList);
quoteList.setAdapter(quoteAdapter);
}
}
// Try this way,hope this will help you...
localViewholder.quote.setTag(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
String buyerId = v.getTag().toString(); // user this buyerId for your requirement
System.out.println("Buyer Id Is "+buyerId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
I have solved my problem as below by changing my asynctask to void to string :
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> reqList) {
this.mContext = paramContext;
this.BuyingRequestArray = reqList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
/* localViewholder.quote.setTag(localViewholder); */
} else {
localViewholder = (Viewholder) paramView.getTag();
/* localViewholder.quote = ((TextView) paramView.getTag()); */
}
final String reqId = BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println("::::::::::::::My reqId:::::::::::" + reqId);
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
System.out.println("Buyer Id Is " + reqId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute(reqId);
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}

Categories

Resources