Custom listview adapter with a chronometer refreshes when scrolled - android

I have created a custom listview adapter to fit a button, a custom chronometer and a textview. When i scroll my listview, the rows that are "hidden" refresh themselves and so chronometers, how can i keep chronometers running even if they're hidden?
I am quite new to Android development so i may have done something wrong; I know that listview refresh its rows when scrolled but maybe there's something that i missed to make chronometers running in background
public class MyCustomAdapter extends BaseAdapter {
ArrayList<String> users;
Context context;
LayoutInflater inflater = null;
public MyCustomAdapter(Activity mainActivity, ArrayList<String> usersList) {
// TODO Auto-generated constructor stub
users = usersList;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return users.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return users.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
private class Holder {
TextView tv;
CustomChrono cr;
Button but;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.customized_list_view, null);
holder.tv = (TextView) rowView.findViewById(R.id.names_laps);
holder.cr = (CustomChrono) rowView.findViewById(R.id.chronometer_laps);
holder.but = (Button) rowView.findViewById(R.id.stop_button);
holder.cr.start();
holder.but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//((ListView) parent).performItemClick(v, position, 0);
holder.cr.stop();
stopped = true;
}
});
holder.tv.setText(users.get(position));
rowView.setTag(holder);
return rowView;
}
}
Then I have my activity class where I use this adapter
public class RunnerLaps extends AppCompatActivity {
ListView list;
ArrayList<String> runner_array;
private Map<Runner,String> map = new HashMap<Runner,String>(10);
private boolean isClicked = true;
private boolean isStartedNow = false;
boolean stopped = false;
ArrayList<Runner> arr_runners;
ArrayList<Runner> runners_arrList;
private long previousClickTime1 = 0;
Runner r = null;
String m = "";
SerializableManager serializableManager;
String filename = "myfile";
FileOutputStream outputStream = null;
ObjectOutputStream objectOutputStream = null;
//Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_laps);
Intent i = getIntent();
serializableManager = new SerializableManager();
runner_array = (ArrayList<String>) getIntent().getSerializableExtra("KEY");
ArrayList<Runner> running = getIntent().getExtras().getParcelableArrayList("arr2");
runners_arrList = new ArrayList<Runner>(runner_array.size());
for (String r : runner_array)
{
runners_arrList.add(new Runner(r));
}
for (int f = 0; f < runners_arrList.size();f++)
{
Log.d("Runner: " + f,runners_arrList.get(f).getName());
}
m = getIntent().getExtras().getString("booly");
for (int j = 0; j < runner_array.size(); j++) {
Runner r = new Runner(runner_array.get(j));
map.put(r, runner_array.get(j));
}
if (m!= null)
{
stopped = true;
}
list = (ListView) findViewById(R.id.laps_list);
final MyCustomAdapter adapter = new MyCustomAdapter(RunnerLaps.this,runner_array);
list.setAdapter(adapter);
//addRunners();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomChrono chr = (CustomChrono) view.findViewById(R.id.chronometer_laps);
r = runners_arrList.get(position);
r.setTemp(System.currentTimeMillis());
long temp = r.getTemp();
previousClickTime1 = temp;
if (previousClickTime1 != 0 && previousClickTime1 - temp < 300)
{
if (stopped == true)
{
chr.stop();
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
Intent i = new Intent (RunnerLaps.this,Runner_Display.class);
i.putExtra("key",(Serializable) r);
i.putParcelableArrayListExtra("arr",arr_runners);
for (int h = 0; h < runners_arrList.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
startActivity(i);
}
else
{
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
for (int h = 0; h < runner_array.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
}
}
else
{}
}
});
}
}

Related

Custom listview in Textview Value change by Scrolling

This Is my Adapter problem was scroll listview to change textview value by every position how to solve it ? plus click event to increment one and minus event to decrment and set value in textview (Plus click to quantity + 1 , minus click to quantity - 1).
public class CustomListViewDrycleaning extends BaseAdapter {
ArrayList<ProductModel> myList = new ArrayList<ProductModel>();
LayoutInflater inflater;
Context context;
int loader = R.drawable.loader;
int minteger = 0;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
String rem, b;
private DisplayImageOptions options;
ProductModel currentListData;
String cid, qcount;
public CustomListViewDrycleaning(Context context, ArrayList<ProductModel> list) {
this.myList = list;
this.context = context;
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_launcher) .showImageForEmptyUri(R.drawable.ic_launcher).showImageOnFail(R.drawable.ic_launcher) .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).build();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.customproductlistdrycleaning, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
currentListData = myList.get(position);
mViewHolder.btndropdown.setTag(currentListData.getCategoryId());
mViewHolder.name.setText(currentListData.getName());
mViewHolder.prize.setText("$" + currentListData.getCharge());
mViewHolder.name.setTag(currentListData.getCategoryId());
mViewHolder.plus.setTag(currentListData.getCategoryId());
mViewHolder.minus.setTag(currentListData.getCategoryId());
String img_path = currentListData.getImage();
ImageLoader.getInstance().displayImage(img_path, mViewHolder.imgbucket, options, animateFirstListener);
String servicecheck1 = currentListData.getServiceId1();
String servicecheck2 = currentListData.getServiceId2();
String servicecheck3 = currentListData.getServiceId3();
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
}
mViewHolder.btndropdown.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.VISIBLE);
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.btndropdown1.setVisibility(View.VISIBLE);
}
});
mViewHolder.btndropdown1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.GONE);
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.btndropdown1.setVisibility(View.GONE);
}
});
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.lnrproduct1.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.lnrproduct1.setVisibility(View.VISIBLE);
mViewHolder.checkBox1.setText(currentListData.getServiceName1());
mViewHolder.txtproductprize1.setText("$" + currentListData.getServiceCharge1());
}
if (servicecheck2 == null) {
mViewHolder.lnrproduct2.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct2.setVisibility(View.VISIBLE);
mViewHolder.checkBox2.setText(currentListData.getServiceName2());
mViewHolder.txtproductprize2.setText("$" + currentListData.getServiceCharge2());
}
if (servicecheck3 == null) {
mViewHolder.lnrproduct3.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct3.setVisibility(View.VISIBLE);
mViewHolder.checkBox3.setText(currentListData.getServiceName3());
mViewHolder.txtproductprize3.setText("$" + currentListData.getServiceCharge3());
}
qcount = currentListData.getQuantity();
mViewHolder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.add(mViewHolder.name.getTag() + "");
int quantityyp = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.plus.getTag() + "";
Log.e("", "#ii" + ii);
if (mViewHolder.plus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
Toast.makeText(context, "Match", Toast.LENGTH_SHORT).show();
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
quantityyp = Integer.parseInt(b) + 1;
String c = Integer.toString(quantityyp);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmaplus = new HashMap<String, String>();
hashmaplus.put("categoryId", rem);
hashmaplus.put("quantity", c);
Utils.qtylist.add(hashmaplus);
Log.e("", "#Utils.qtylistadd" + Utils.qtylist);
break;
}
}
}
});
mViewHolder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.remove(mViewHolder.name.getTag() + "");
int quantityym = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.minus.getTag() + "";
Log.e("", "#iiminus" + ii);
if (mViewHolder.minus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
Log.e("", "#QQQ" + b);
Log.e("", "#rem" + rem);
if (b.equals("0")) {
} else {
quantityym = Integer.parseInt(b) - 1;
String c = Integer.toString(quantityym);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmapminus = new HashMap<String, String>();
hashmapminus.put("categoryId", rem);
hashmapminus.put("quantity", c);
Utils.qtylist.add(hashmapminus);
break;
}
}
}
}
});
return convertView;
}
private class MyViewHolder {
TextView name, prize, strcount, txtproductprize1, txtproductprize2, txtproductprize3;
Button cart, plus, minus, btndropdown, btndropdown1;
ImageView imgbucket;
LinearLayout lnrbelowdry, lnrproduct1, lnrproduct2, lnrproduct3;
CheckBox checkBox1, checkBox2, checkBox3;
public MyViewHolder(View item) {
name = (TextView) item.findViewById(R.id.txtproductname);
prize = (TextView) item.findViewById(R.id.txtprize);
strcount = (TextView) item.findViewById(R.id.txtcount);
imgbucket = (ImageView) item.findViewById(R.id.imgbucket);
plus = (Button) item.findViewById(R.id.btnplus);
minus = (Button) item.findViewById(R.id.btnminus);
btndropdown = (Button) item.findViewById(R.id.btndropdown);
btndropdown1 = (Button) item.findViewById(R.id.btndropdown1);
lnrbelowdry = (LinearLayout) item.findViewById(R.id.lnrbelowdry);
lnrproduct1 = (LinearLayout) item.findViewById(R.id.lnrproduct1);
lnrproduct2 = (LinearLayout) item.findViewById(R.id.lnrproduct2);
lnrproduct3 = (LinearLayout) item.findViewById(R.id.lnrproduct3);
checkBox1 = (CheckBox) item.findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) item.findViewById(R.id.checkBox2);
checkBox3 = (CheckBox) item.findViewById(R.id.checkBox3);
txtproductprize1 = (TextView) item.findViewById(R.id.txtproductprize1);
txtproductprize2 = (TextView) item.findViewById(R.id.txtproductprize2);
txtproductprize3 = (TextView) item.findViewById(R.id.txtproductprize3);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
You are returning a same ID for each row. try this:
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

android - How to check how many elements are present in a GridView?

I am dynamically adding images to a GridView.
I want to have a counter to check how many images are present in a GridView.
The purpose is to restrict the user to add maximum of "n" images.
Therefore I want to have a counter which will count this number and I will check accordingly.
public class ExistingDetailedActivity extends Activity {
public String images,audiopath,name,assignedTo;
TextView ringtonename,assigned;
public GridView gridView;
public String [] imgpath;
CustomBaseExistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_existing_detailed);
Intent i = getIntent();
if(i.hasExtra("BNDL")){
Bundle bdl = getIntent().getBundleExtra("BNDL");
if(bdl.get("IMAGEPATH") != null){
images = bdl.getString("IMAGEPATH");
}
if(bdl.get("AUDIOPATH") != null){
audiopath = bdl.getString("AUDIOPATH");
}
if(bdl.get("RINGTONENAME") != null){
name = bdl.getString("RINGTONENAME");
}
if(bdl.get("ASSIGNEDTO") != null){
assignedTo = bdl.getString("ASSIGNEDTO");
}
}
Typeface FONT_NAME = Typeface.createFromAsset(this.getAssets(), "komika-title-brush-1361511399.ttf");
imgpath=images.split("\\*") ;
ringtonename=(TextView) findViewById(R.id.textView2);
ringtonename.setText(name);
ringtonename.setTypeface(null, Typeface.BOLD);
ringtonename.setTypeface(FONT_NAME);
assigned=(TextView) findViewById(R.id.textView4);
assigned.setText(assignedTo);
assigned.setTypeface(null, Typeface.BOLD);
assigned.setTypeface(FONT_NAME);
gridView=(GridView) findViewById(R.id.gridview1);
adapter = new CustomBaseExistAdapter(this,imgpath);
//adapter.notifyDataSetChanged();
gridView.invalidateViews();
gridView.setAdapter(adapter);
}
}
Another one is
public class CustomBaseExistAdapter extends BaseAdapter{
private final Activity context;
public String[] imagepath;
private String[] imagepath1=null;
private String[] imagepathBackUp=null;
public CustomBaseExistAdapter(Activity context,
String[] imagepath) {
this.context = context;
this.imagepath = imagepath;
this.imagepathBackUp =imagepath;
List<String> nonBlank = new ArrayList<String>();
for(String s: imagepath) {
if (!s.trim().isEmpty()) {
nonBlank.add(s);
}
}
imagepath1 = (String[]) nonBlank.toArray( new String[nonBlank.size()] );
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagepath.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.custom_image_with_checkbox, null);
CheckBox cb=(CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imgThumb);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int id = buttonView.getId();
if(isChecked){
/*String newList[] = new String[imagepath.length - 1];
int count = 0;
for (int i = 0; i < imagepath.length; i++) {
if (imagepath.length - 1 > 0) {
if (imagepath[i] == imagepath1[position]) { // itemPath[1] as the range starts from 0, so 1 would be ITEM2
// SKIP IF MATCHES THE ITEM YO WANT TO REMOVE
} else {
newList[count] = imagepath[i];
count++;
}
}
}
imagepath=new String[newList.length];
imagepath= newList;*/
List<String> newlist= new ArrayList<String>(Arrays.asList(imagepath));
newlist.remove(imagepath1[position]);
imagepath=null;
imagepath = newlist.toArray(new String[newlist.size()]);
/*new String[newlist.size()];
for(int j =0;j<newlist.size();j++){
imagepath[j] = newlist.get(j);
}*/
notifyDataSetChanged();
}
}
});
imageView.setImageBitmap(BitmapFactory.decodeFile(imagepath[position]));
}
return convertView;
}
}
To know number of Elements in GridView, here ,
put int count = (position + 1); in your GridView Adapter getView(..) method. It is callback method, called number of times to populate your Gridview. Starts from 0.
int count = 0; // define count as global instance var.
public View getView(final int position, View convertView, ViewGroup parent){
...
count = position + 1;
...
}
count is what you want.

Closed or circular Vertical ListView Android

I have an Vertical listview i want listview should be closed. For example if the last item is reached in Listview then show the first item below the last item. It means item should be in circular format. And if i scroll from first item it should show last item before first item. I want scrolling for both side.
public class MainActivity extends Activity {
ListView list;
long startTime;
long endTime;
List<String> mList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
downloadDetails();
String str;
for (int i = 0; i < 10; i++) {
str = new String("Data --- " + i);
mList.add(str);
}
CircularAdapter adapter = new CircularAdapter(this, 0, mList);
list.setAdapter(adapter);
final YourRunnable runy = new YourRunnable();
list.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
startTime = (new Date()).getTime();
runy.onPause();// pausing thread actually pauses scrolling
}
if (event.getAction() == MotionEvent.ACTION_UP) {
endTime = (new Date()).getTime();
if ((endTime - startTime) <= 100) {// 100 mill second limit
// for click
// Log.i("ITEM CLICK() ", "item : ");
}
runy.onResume(); // resume scrolling
}
return false;
}
});
new Thread(runy).start();
}
class YourRunnable implements Runnable {
private Object mPauseLock;
private boolean mPaused;
private boolean mFinished;
public YourRunnable() {
mPauseLock = new Object();
mPaused = false;
mFinished = false;
}
#SuppressLint("NewApi")
public void run() {
while (!mFinished) {
// for loop is not infinite but enough as Integer.MAX_VALUE
for (int index = 0; index < list.getAdapter().getCount(); index++) {
list.smoothScrollToPositionFromTop(list.getLastVisiblePosition() + 1, 0, 10000);
try {
// it helps scrolling to stay smooth as possible (by
// experiment)
Thread.sleep(3000);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();// putting thread in wait
// list of mPauseLock
// object
} catch (InterruptedException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// to pause list
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
// resume thread
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();// notify all object that are waiting on
// the wait list of mPauseLock object
}
}
}
private class CircularAdapter extends ArrayAdapter {
List<String> mlist;
Context mContext;
LayoutInflater inflater;
public final int HALF_MAX_VALUE = Integer.MAX_VALUE / 2;
public final int MIDDLE;
#SuppressWarnings("unchecked")
public CircularAdapter(Context ctx, int resId, List<String> objects) {
super(ctx, resId, objects);
mContext = ctx;
mlist = objects;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MIDDLE = HALF_MAX_VALUE - HALF_MAX_VALUE % mlist.size();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
int relativePos = position % mlist.size();
Log.i("RELATIVE : ", " POS:" + relativePos);
return mlist.get(relativePos);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String model = getItem(position);
holder.name.setText(model);
convertView.setOnClickListener(new ListenerT(model) {
#Override
public void onClick(View v) {
Log.i("CLICK", "ITEM---" + name);
}
});
return convertView;
}
}
// use your own listener to pass parameter
private class ListenerT implements OnClickListener {
String name;
public ListenerT(String nm) {
name = nm;
}
#Override
public void onClick(View v) {
}
}
private class ViewHolder {
TextView name;
}
}

Custom Listview using Base adapter not scrolls fast in Android

Hi I am working with android application which is having custom listview. The items in listview around 3000. My problem is after loading items when scrolling it makes outOfMemory Error.
I am using Base Adapter and Each item having One Checkbox and four textviews.
Here is my code. Please let me know the solution.
public class GuestListAdapter extends BaseAdapter implements OnClickListener {
private String strExe;
AlertDialog.Builder builder;
String sId;
String sCheckIn;
String strCheckInResponse;
Context context;
private ArrayList<String> arrayListId;
private ArrayList<String> arrayListFirstName;
private ArrayList<String> arrayListLastName;
private ArrayList<String> arrayListGuests;
private ArrayList<String> arrayCustomOne;
private ArrayList<String> arTempId;
public static ArrayList<Boolean> chickinlist;
public static ArrayList<Integer> arrCheckedItems;
public static ArrayList<Integer> arrUnCheckedItems;
Button btnInfo;
private SQLiteAdapter mySqliteAdapter;
private GuestListScreen myGuestList;
private RelativeLayout views;
private String strAlertValue;
// private AlertDialog alertDialog = null;
private ArrayList<Boolean> checks = new ArrayList<Boolean>();
public GuestListAdapter(Context mcontext, ArrayList<String> arrListid,
ArrayList<String> arrListFN, ArrayList<String> arrListLN,
ArrayList<String> arrListGuest, ArrayList<String> arrTiketID,
ArrayList<String> arrCustOne, ArrayList<Boolean> chicklist) {
clearAdapter();
arrayListId = new ArrayList<String>();
arrayListFirstName = new ArrayList<String>();
arrayListLastName = new ArrayList<String>();
arrayListGuests = new ArrayList<String>();
arrayCustomOne = new ArrayList<String>();
arTempId = new ArrayList<String>();
chickinlist = new ArrayList<Boolean>();
arrCheckedItems = new ArrayList<Integer>();
arrUnCheckedItems = new ArrayList<Integer>();
arrayListId = arrListid;
arrayListFirstName = arrListFN;
arrayListLastName = arrListLN;
arrayListGuests = arrListGuest;
arrayCustomOne = arrCustOne;
arTempId = arrTiketID;
chickinlist = chicklist;
context = mcontext;
mySqliteAdapter = new SQLiteAdapter(context);
for (int i = 0; i < arrayListFirstName.size(); i++) {
checks.add(i, false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayListFirstName.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayListFirstName.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final int pos = position;
views = null;
LayoutInflater layoutInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
views = (RelativeLayout) layoutInflator.inflate(
R.layout.guest_list_item, null);
final CheckBox chk = (CheckBox) views.getChildAt(0);
// Log.d("", "CheckBox Pos "+position);
chk.setId(position);
TextView txtView = (TextView) views.getChildAt(1);
TextView txtView2 = (TextView) views.getChildAt(2);
TextView txtView3 = (TextView) views.getChildAt(3);
final TextView txtView4 = (TextView) views.getChildAt(4);
TextView txtView5 = (TextView) views.getChildAt(6);
txtView5.setId(position);
// Log.d("", "Button Pos "+position);
txtView4.setId(position);
txtView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, InfoScreen.class);
intent.putExtra("IDVALUE", arTempId.get(txtView4.getId()));
intent.putExtra("IDVALUE", arrayListId.get(position));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
for (int dd = 0; dd < arrayListFirstName.size(); dd++) {
if (position == dd) {
// Log.d("", "Passsing arr size " + chickinlist.size());
Boolean result = chickinlist.get(position);
// Log.d("", "After " + result);
if (result == true) {
chk.setChecked(true);
arrCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_checked);
} else {
chk.setChecked(false);
arrUnCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_unchecked);
}
txtView.setText(arrayListFirstName.get(position));
txtView2.setText(arrayListLastName.get(position));
txtView3.setText("(" + arrayListGuests.get(position) + ")");
if (arrayCustomOne.get(position).equalsIgnoreCase("0")
|| arrayCustomOne.get(position).equalsIgnoreCase(null)
|| arrayCustomOne.get(position).equalsIgnoreCase(
"(null)")) {
txtView5.setText("");
} else {
txtView5.setText(arrayCustomOne.get(position));
}
}
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mySqliteAdapter.openToWrite();
sId = arrayListId.get(chk.getId());
// Log.d("Adapter",
// "Checked Temp Id "+arTempId.get(chk.getId()));
if (isChecked) {
chk.setChecked(true);
arrCheckedItems.add(position);
strAlertValue = "1";
sCheckIn = "1";
strExe = "update ticket_details set checkin_status=1 where tempid="
+ arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
if (Util.getInstance(context).isTabletDevice()) {
buttonView
.setBackgroundResource(R.drawable.tablet_list_item_check);
Log.e("Tablet", "Tablet Checked ");
} else {
buttonView
.setBackgroundResource(R.drawable.list_item_checked);
Log.e("Device", "Device Checked ");
}
new CheckInUpdate().execute();
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.create();
builder.setMessage(arrayListFirstName.get(chk.getId())
+ " " + arrayListLastName.get(chk.getId())
+ " has been checked in.");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Intent intentNavGuestList = new Intent(
context, GuestListScreen.class);
intentNavGuestList
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intentNavGuestList);
dialog.dismiss();
}
}).show();
// Log.d("", "ID = " + buttonView.getId());
}
if (!isChecked) {
sCheckIn = "0";
strAlertValue = "0";
strExe = "update ticket_details set checkin_status=0 where tempid="
+ arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
if (Util.getInstance(context).isTabletDevice()) {
buttonView
.setBackgroundResource(R.drawable.tablet_list_item_uncheck);
Log.e("Tablet", "Tablet UnChecked ");
} else {
buttonView
.setBackgroundResource(R.drawable.list_item_unchecked);
Log.e("Device", "Device UnChecked ");
}
new CheckInUpdate().execute();
Intent intentNavGuestList = new Intent(context,
GuestListScreen.class);
intentNavGuestList
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intentNavGuestList);
}
}
});
return views;
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Integer index = (Integer) view.getTag();
boolean state = checks.get(index.intValue());
checks.set(index.intValue(), !state);
}
public void clearAdapter() {
if (arrayListFirstName != null) {
arrayListFirstName.clear();
arrayListId.clear();
arrayListId = null;
arrayListFirstName = null;
arrayListLastName.clear();
arrayListLastName = null;
arrayListGuests.clear();
arrayListGuests = null;
arrayCustomOne.clear();
arrayCustomOne = null;
arTempId.clear();
arTempId = null;
chickinlist.clear();
chickinlist = null;
arrCheckedItems.clear();
arrCheckedItems = null;
arrUnCheckedItems.clear();
arrUnCheckedItems = null;
}
}
}
I also tried with View Holder but still loading slow. Please tell the solution how to solve this.
You need to reuse view paremeter from View getView(final int position, Vie view, ViewGroup parent) and if it's not null, then You don't need to inflate again.
Use ViewHolder pattern;
remove loop for (int dd = 0; dd < arrayListFirstName.size(); dd++) from getView;
Try simplify layout for list items;
Seems arrayListFirstName.size() can be simplified (e.g. use some variable to avoid size() calls)
Do profiling in order to know exactly what is slow downs You scrolling (It might be enough to profike only getView())
Also, check out this video from Google I/O for more details on how to make ListViews in a right way.

ListView displaying items wrongly

In my application I am using a listview which displays the data from a CustomAdapter.In my arraylist I have two items.My listview shows the last added data two times instead of first item.
This is my custom Adapter:
public class NodeListViewCustomAdapter extends BaseAdapter {
LayoutInflater inflater;
Activity mActivity;
ArrayList<Node> mNodeList;
double mRecvProgress;
double mSentProgress;
String repeatSentprogress;
String repeatRecvprogress;
ViewHolder holder;
Node node;
public NodeListViewCustomAdapter(Activity aContext,Node node,ArrayList<Node> nodeList){
super();
mActivity = aContext;
this.node = node;
this.inflater = (LayoutInflater)aContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mNodeList = nodeList;
}
#Override
public int getCount() {
return mNodeList.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 void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public static class ViewHolder
{
TextView txtViewnodeTitle;
TextView sentStatustxtView;
TextView recvStatustxtView;
TextView msgsentvalue;
TextView msgrecvvalue;
TextView sentindicator;
TextView recvindicator;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.nodelistitem_row, null);
} else{
holder=(ViewHolder)convertView.getTag();
}
if(node.advertise)
convertView.setBackgroundColor(Color.YELLOW);
node.advertise = false;
convertView.setBackgroundColor(Color.BLACK);
holder.txtViewnodeTitle = (TextView) convertView.findViewById(R.id.txtViewnodeTitle);
holder.sentStatustxtView = (TextView) convertView.findViewById(R.id.sentstatustxtView);
holder.recvStatustxtView = (TextView) convertView.findViewById(R.id.recvstatustextView);
holder.msgsentvalue = (TextView) convertView.findViewById(R.id.msgsenttitle);
holder.msgrecvvalue = (TextView) convertView.findViewById(R.id.msgrecvtitle);
convertView.setTag(holder);
holder.sentStatustxtView.setGravity(Gravity.LEFT);
holder.recvStatustxtView.setGravity(Gravity.LEFT);
computeProgress();
holder.txtViewnodeTitle.setText(String.valueOf(node.nodeID));
holder.msgsentvalue.setText("< "+String.valueOf(node.ms)+"/"+node.MS);
holder.sentStatustxtView.setText(repeatSentprogress);
holder.msgrecvvalue.setText("> "+String.valueOf(node.mr)+"/"+node.MR);
holder.recvStatustxtView.setText(repeatRecvprogress);
return convertView;
}
private void computeProgress() {
mSentProgress = ((double)node.ms/(double)node.MS)*20;
mRecvProgress = ((double)node.mr/(double)node.MR)*20;
repeatSentprogress = new String(new char[(int)mSentProgress]).replace('\0', (char) 9608);
repeatRecvprogress = new String(new char[(int)mRecvProgress]).replace('\0', (char) 9608);
if(node.ms == node.MS)holder.sentStatustxtView.setTextColor(Color.GREEN);
else holder.sentStatustxtView.setTextColor(Color.BLUE);
if(node.mr == node.MR)holder.recvStatustxtView.setTextColor(Color.GREEN);
else holder.recvStatustxtView.setTextColor(Color.BLUE);
}
}
This is my Activity:
public class Nodes extends Activity implements OnItemClickListener {
ListView mListView;
NodeListViewCustomAdapter mNodeListAdapter;
public ArrayList <Node> mNodesList ;
TextView nodeIdView;
Timer mTimer;
Timer mInnerTimer;
int delay = 500;
int period = 500;
boolean found = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nodes);
mListView = (ListView)findViewById(R.id.node_list);
mNodesList = new ArrayList<Node>();
doTimerTask();
mListView.setOnItemClickListener(this);
}
private void doTimerTask() {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
while(true){
try{
String PeardOutput = null;
synchronized(AndroidPeardServer.nodestatsqe){
PeardOutput = AndroidPeardServer.nodestatsqe.poll();
if (PeardOutput == null) return;
}
String msg = PeardOutput.substring(3);
process_nodeStats(msg);
mNodeListAdapter.notifyDataSetChanged();
}
catch(Exception e){
e.printStackTrace();
}
}
}
});
}
}, delay, period);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
private void process_nodeStats(String msg) {
String[] nodeStats = msg.split(":");
String type = nodeStats[0];
int nodeID = Integer.parseInt(nodeStats[1]);
int value = Integer.parseInt(nodeStats[2]);
int cycle = Integer.parseInt(nodeStats[3]);
// Iterate through the nodelist
found = false;
for(Node node: mNodesList){
if (node.nodeID != nodeID) {
continue;
}
else found = true;
populateNode(node,type, nodeID, value, cycle);
mNodeListAdapter = new NodeListViewCustomAdapter(getParent(),node,mNodesList);
mListView.setAdapter(mNodeListAdapter);
break;
}
if (!found){
Node node = new Node();
mNodesList.add(node);
populateNode(node,type,nodeID,value,cycle);
mNodeListAdapter = new NodeListViewCustomAdapter(getParent(),node,mNodesList);
mListView.setAdapter(mNodeListAdapter);
}
}
private void populateNode(Node node,String type,int nodeId, int value, int cycle) {
node.nodeID = nodeId;
if(type.equals("MS")){
node.MS = value;
node.CS = cycle;
node.ms = 0;
}else if(type.equals("MR")){
node.MR = value;
node.CR = cycle;
node.mr = 0;
}else if(type.equals("ms")){
if(cycle==node.CS) node.ms = + value;
else node.ms = value;
}else if(type.equals("mr")){
if(cycle==node.CR) node.mr = + value;
else node.mr = value;
}else if (type.equals("NL")){
mNodesList.remove(node);
}else if(type.equals("NA")){
node.advertise = true;
}
}
//========= Node class to store in NodeList =================
public class Node {
int nodeID;
int MS; //Total Messages to Send to nodeID
int ms; //number of Messages sent so far
int MR ; //Total Messages expected from nodeID
int mr; //number of Messages received so far
int CS; //Investigation Cycle for Sending
int CR; //Investigation Cycle for Receiving
boolean advertise = false; // To know the advertisements received
}
}
I finally got tit right.I have not taken the node from the arraylist.So this line done it for me.
node = mNodeList.get(position);
Thanks for all.

Categories

Resources