I have made a list view with a custom Adapter having an imageview, textview and a checkBox
---------------------------------------
<ImageView --- textView --- checkbox >
---------------------------------------
The listview has an onClickListener to it and the checkboxes have onCheckListener..
I have used a boolean array (named as status) to set the checkboxes checked or not initialized to false in the begining.
Suppose I have 19 items on the list and I check the checkbox of first item it works properly and index 0 of the boolean array is changed to true.
But when I scroll and check the last item 3rd position of the list is reflected and index 3 of the boolean array turns true.
Also many other checkboxes are automatically checked.
Java Code
public class Search_list extends Activity {
static String str1 = "v1", str2 = "v2";
String s, item, idd;
static int spnr, range1, range2;
private CarHelper dbcarhelper = null;
private Cursor ourCursor;
CarHelper h = null;
List<String[]> names2 = null;
ListView LV;
MyCustomAdapter dataAdapter = null;
private ArrayList<Boolean> status;
byte[] Image = null;
Cursor c;
Bitmap decodedByte;
String c1_make = null, c1_model = null, c1_ver = null, c2_make = null,
c2_model = null, c2_ver = null;
int cntr = 0;
Button b1;
CheckBox cb;
protected ProgressDialog dialog;
List<String[]> mlist = new ArrayList<String[]>();
TextView tv1;
ArrayList<String> stg1;
ArrayList<String> arr_make = new ArrayList<String>();
ArrayList<String> arr_model = new ArrayList<String>();
ArrayList<String> arr_ver = new ArrayList<String>();
ArrayList<Bitmap> arr_img = new ArrayList<Bitmap>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
dialog = ProgressDialog.show(Search_list.this, "Loading",
"Please Wait...");
status = new ArrayList<Boolean>(); /
LV = (ListView) findViewById(R.id.list);
//------------------ Compare button onClick() ------------------------------
b1 = (Button) findViewById(R.id.btnCmp);
b1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
int count = 1;
if (cntr == 1) {
Toast.makeText(getApplicationContext(),
"Please select atleast two cars!",
Toast.LENGTH_LONG).show();
} else {
for (int i = 0; i < status.size(); i++) {
System.out.println("Compare click Position= " + i + " Status: "
+ status.get(i));
// System.out.println();
if (status.get(i)) {
if (count == 2) {
c2_make = arr_make.get(i);
c2_model = arr_model.get(i);
c2_ver = arr_ver.get(i);
count++;
}
if (count == 1) {
c1_make = arr_make.get(i);
c1_model = arr_model.get(i);
c1_ver = arr_ver.get(i);
count++;
}
} else {
}
}
Intent intent = new Intent(Search_list.this, DispComp.class);
Bundle b = new Bundle();
b.putString("car1", c1_make);
b.putString("carm1", c1_model);
b.putString("carv1", c1_ver);
b.putString("car2", c2_make);
b.putString("carm2", c2_model);
b.putString("carv2", c2_ver);
intent.putExtras(b);
startActivity(intent);
}
}
});
//--------------------------------------------------------------------------
dbcarhelper = new CarHelper(this);
dbcarhelper.createDatabase();
dbcarhelper.openDataBase();
if (s != null) {
startManagingCursor(ourCursor);
}
if (spnr == 1) {
byMakeModel();
}
if (spnr == 2) {
byBudgetFuel();
}
fill_list();
for (int i = 0; i < arr_make.size(); i++) {
status.add(false);
}
System.out.println("Inside onCreate() ... status all null..! ");
dialog.dismiss();
}
public void SetId(String s1, String s2, int s) {
System.out.println("SetMake spnr= |" + spnr + "|");
System.out.println("SetMake s= |" + s + "|");
str1 = s1;
str2 = s2;
spnr = s;
System.out.println("SetMake aftr spnr= |" + spnr + "|");
}
public void SetBudgetFuel(String s1, String s2, int s, int r1, int r2) {
System.out.println("SetBudget spnr= |" + spnr + "|");
System.out.println("SetBudget s= |" + s + "|");
System.out.println("SetBudget r1= |" + r1 + "|");
System.out.println("SetBudget r2= |" + r2 + "|");
str1 = s1;
str2 = s2;
spnr = s;
range1 = r1;
range2 = r2;
System.out.println("SetMake aftr spnr= |" + spnr + "|");
}
// -------------------------------------------------------------------------
public void byMakeModel() {
// make n model selected *******************************
if (str2.equalsIgnoreCase("(Select)")) {
dbcarhelper.search_by_make(str1);
} else {
dbcarhelper.search_by_makemodel(str1, str2);
}
}
// -------------------------------------------------------------------------
public void byBudgetFuel() {
// budget or fuel selected
// ************************************************
if (str1.equalsIgnoreCase("Any Budget")) {
dbcarhelper.search_by_fuel(str2);
}
else if (str2.equalsIgnoreCase("All")) {
dbcarhelper.search_by_budget(range1, range2);
}
else {
dbcarhelper.search_by_budgetfuel(str2, range1, range2);
}
}
// -------------------------------------------------------------------------
public void fill_list() {
final CarHelper h = new CarHelper(getApplicationContext());
Toast.makeText(getApplicationContext(), "Inside if case",
Toast.LENGTH_LONG).show();
mlist = h.selectAllb2();
stg1 = new ArrayList<String>();
int x = 0;
String stg;
for (String[] srch : mlist) {
stg = "Make: " + srch[0] + "\nModel: " + srch[1] + " \nVersion: "
+ srch[2] + "\nPrice: Rs. " + srch[3];
stg1.add(stg);
arr_make.add(srch[0]);
arr_model.add(srch[1]);
arr_ver.add(srch[2]);
System.out.println("srch 0" + srch[0] + "\nsrch 1" + srch[1]
+ "\nsrch 2" + srch[2] + "\nsrch 3" + srch[3]);
x++;
}
System.out.println("length--------------------- " + stg1.size());
// ----------------Image--------------------
int run = 0;
c = dbcarhelper.fetchImgRow("1");
if (c.moveToFirst()) {
do {
Image = c.getBlob(c.getColumnIndex("img_str"));
System.out.println("Image = " + Image);
System.out.println("run = " + run);
byte[] decodedString = Base64.decode(Image, Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
arr_img.add(decodedByte);
System.gc();
run++;
} while (c.moveToNext());
}
dbcarhelper.close();
// ----------------Image--------------------
System.out.println("run after close() = " + run);
dataAdapter = new MyCustomAdapter(this, R.layout.new_search_adptr, stg1);
LV.setAdapter(dataAdapter);
int[] colors = { 0, 0xff00ffff, 0 };
LV.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
LV.setDividerHeight(4);
LV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
New_Details det = new New_Details();
System.out.println("Inside Click !");
String car1 = h.srch_make.get(position);
String carm1 = h.srch_model.get(position);
String carv1 = h.srch_ver.get(position);
det.setImg(arr_img.get(position));
// Bitmap car_img = arr_img.get(position);
// System.out.println("position: " + position);
// System.out.println("arr_img position: " +
// arr_img.get(position));
Intent intent = new Intent(Search_list.this, New_Details.class);
Bundle b = new Bundle();
b.putString("car1", car1);
b.putString("carm1", carm1);
b.putString("carv1", carv1);
intent.putExtras(b);
startActivity(intent);
}
});
}
private class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<String> sList) {
super(context, textViewResourceId, sList);
}
private class ViewHolder {
TextView text;
CheckBox chkbox;
ImageView imageview;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder = null;
//Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.new_search_adptr, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.adapterText1);
holder.chkbox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
//---------- Setting the checkBoxes -----------------------------------
if (status.get(position)) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
//-----------------------------------------------------------------
holder.imageview = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(holder);
holder.chkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
// User checked (selected) a car
// *********************************
if (cntr > 1) {
// More than two cars selected
Toast.makeText(getApplicationContext(),
"Please select only two cars!",
Toast.LENGTH_LONG).show();
cb.setChecked(false);
} else {
// car selected
status.set(position, true);
cntr++;
System.out.println("Chk List Position= " + position );
for (int i = 0; i < status.size(); i++) {
System.out.println("Chkbox chkd Position= " + i + " Status: "
+ status.get(i));
}
}
} else {
// User Unchecked (de - selected) a car
// *********************************
cntr--;
status.set(position, false);
System.out.println("Unchk List Position= " + position );
for (int i = 0; i < status.size(); i++) {
System.out.println("UnChkbox chkd Position= " + i + " Status: "
+ status.get(i));
}
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
holder.chkbox.setOnCheckedChangeListener(null);
}
holder.text.setText(stg1.get(position).toString());
// setting image
holder.imageview.setImageBitmap(arr_img.get(position));
return convertView;
}
}
}
Please help me find a solution. Thank you.
Stack Trace
08-17 06:58:16.798: W/dalvikvm(698): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-17 06:58:16.808: E/AndroidRuntime(698): FATAL EXCEPTION: main
08-17 06:58:16.808: E/AndroidRuntime(698): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
08-17 06:58:16.808: E/AndroidRuntime(698): at android.graphics.BitmapFactory.nativeDecodeByteArray(Native Method)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:405)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:418)
08-17 06:58:16.808: E/AndroidRuntime(698): at com.MyAuto.Search_list.fill_list(Search_list.java:334)
08-17 06:58:16.808: E/AndroidRuntime(698): at com.MyAuto.Search_list.onCreate(Search_list.java:196)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.os.Handler.dispatchMessage(Handler.java:99)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.os.Looper.loop(Looper.java:123)
08-17 06:58:16.808: E/AndroidRuntime(698): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-17 06:58:16.808: E/AndroidRuntime(698): at java.lang.reflect.Method.invokeNative(Native Method)
08-17 06:58:16.808: E/AndroidRuntime(698): at java.lang.reflect.Method.invoke(Method.java:507)
08-17 06:58:16.808: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-17 06:58:16.808: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-17 06:58:16.808: E/AndroidRuntime(698): at dalvik.system.NativeStart.main(Native Method)
For reference use the example
Get Selected Item Using Checkbox in Listview
Change your adapter class to below.
You need to override getCount and use SparseBooleanArray
private class MyCustomAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener{
ArrayList<String> myList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<String> sList) {
super(context, textViewResourceId, sList);
mCheckStates = new SparseBooleanArray(sList.size());
myList= sList;
}
private SparseBooleanArray mCheckStates;
private class ViewHolder {
TextView text;
CheckBox chkbox;
ImageView imageview;
}
#Override
public int getCount() {
return stg1.size();
}
#Override
public View getView(final int position, View convertView,ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.new_search_adptr, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.adapterText1);
holder.chkbox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
holder.imageview = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.chkbox.setTag(position);
holder.chkbox.setChecked(mCheckStates.get(position, false));
holder.chkbox.setOnCheckedChangeListener(this);
holder.text.setText(stg1.get(position).toString());
holder.imageview.setImageBitmap(arr_img.get(position));
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
To get on Button click
StringBuilder result = new StringBuilder();
for(int i=0;i<youradapter.mCheckStates.size();i++)
{
if(youradapter.mCheckStates.get(i)==true)
{
result.append(arr_make.get(i).toString()+" "+arr_model.get(i).toString()+" "+arr_ver.get(i).toString());
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
In your getView() you're only setting the checked state on newly created views. When views are recycled (convertView != null), the checked state will be that of the old, recycled view.
Move the "Setting the checkBoxes" code part one indentation level up after the if (converView == null) ... else part. That is, change your code from this:
if (convertView == null) {
//...
//create view and init holder
//---------- Setting the checkBoxes -----------------------------------
if (status.get(position)) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
//...
} else {
holder = (ViewHolder) convertView.getTag();
holder.chkbox.setOnCheckedChangeListener(null);
}
to this:
if (convertView == null) {
//...
//create view and init holder
} else {
holder = (ViewHolder) convertView.getTag();
holder.chkbox.setOnCheckedChangeListener(null);
}
//---------- Setting the checkBoxes -----------------------------------
if (status.get(position)) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
I declared the boolean array inside my custom adapter.
Also I removed the if statement ie
if (convertView == null)
public class Search_list extends Activity {
static String str1 = "v1", str2 = "v2";
String s, item, idd;
static int spnr, range1, range2;
private CarHelper dbcarhelper = null;
private Cursor ourCursor;
CarHelper h = null;
List<String[]> names2 = null;
ListView LV;
MyCustomAdapter dataAdapter = null;
byte[] Image = null;
Cursor c;
Bitmap decodedByte;
String c1_make = null, c1_model = null, c1_ver = null, c2_make = null,
c2_model = null, c2_ver = null;
int cntr = 0;
Button b1;
CheckBox cb;
protected ProgressDialog dialog;
List<String[]> mlist = new ArrayList<String[]>();
TextView tv1;
ArrayList<String> stg1;
ArrayList<String> arr_make = new ArrayList<String>();
ArrayList<String> arr_model = new ArrayList<String>();
ArrayList<String> arr_ver = new ArrayList<String>();
ArrayList<Bitmap> arr_img = new ArrayList<Bitmap>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
dialog = ProgressDialog.show(Search_list.this, "Loading",
"Please Wait...");
LV = (ListView) findViewById(R.id.list);
//------------------ Compare button onClick() ------------------------------
b1 = (Button) findViewById(R.id.btnCmp);
b1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
int count = 1;
if (cntr == 1) {
Toast.makeText(getApplicationContext(),
"Please select atleast two cars!",
Toast.LENGTH_LONG).show();
} else {
for (int i = 0; i < dataAdapter.status.size(); i++) {
System.out.println("Compare click Position= " + i + " Status: "
+ dataAdapter.status.get(i));
// System.out.println();
if (dataAdapter.status.get(i)) {
if (count == 2) {
c2_make = arr_make.get(i);
c2_model = arr_model.get(i);
c2_ver = arr_ver.get(i);
count++;
}
if (count == 1) {
c1_make = arr_make.get(i);
c1_model = arr_model.get(i);
c1_ver = arr_ver.get(i);
count++;
}
} else {
}
}
Intent intent = new Intent(Search_list.this, DispComp.class);
Bundle b = new Bundle();
b.putString("car1", c1_make);
b.putString("carm1", c1_model);
b.putString("carv1", c1_ver);
b.putString("car2", c2_make);
b.putString("carm2", c2_model);
b.putString("carv2", c2_ver);
intent.putExtras(b);
startActivity(intent);
}
}
});
//--------------------------------------------------------------------------
dbcarhelper = new CarHelper(this);
dbcarhelper.createDatabase();
dbcarhelper.openDataBase();
if (s != null) {
startManagingCursor(ourCursor);
}
if (spnr == 1) {
byMakeModel();
}
if (spnr == 2) {
byBudgetFuel();
}
fill_list();
System.out.println("Inside onCreate() ... status all null..! ");
dialog.dismiss();
}
public void SetId(String s1, String s2, int s) {
System.out.println("SetMake spnr= |" + spnr + "|");
System.out.println("SetMake s= |" + s + "|");
str1 = s1;
str2 = s2;
spnr = s;
System.out.println("SetMake aftr spnr= |" + spnr + "|");
}
public void SetBudgetFuel(String s1, String s2, int s, int r1, int r2) {
System.out.println("SetBudget spnr= |" + spnr + "|");
System.out.println("SetBudget s= |" + s + "|");
System.out.println("SetBudget r1= |" + r1 + "|");
System.out.println("SetBudget r2= |" + r2 + "|");
str1 = s1;
str2 = s2;
spnr = s;
range1 = r1;
range2 = r2;
System.out.println("SetMake aftr spnr= |" + spnr + "|");
}
// -------------------------------------------------------------------------
public void byMakeModel() {
// make n model selected *******************************
if (str2.equalsIgnoreCase("(Select)")) {
dbcarhelper.search_by_make(str1);
} else {
dbcarhelper.search_by_makemodel(str1, str2);
}
}
// -------------------------------------------------------------------------
public void byBudgetFuel() {
// budget or fuel selected
// ************************************************
if (str1.equalsIgnoreCase("Any Budget")) {
dbcarhelper.search_by_fuel(str2);
}
else if (str2.equalsIgnoreCase("All")) {
dbcarhelper.search_by_budget(range1, range2);
}
else {
dbcarhelper.search_by_budgetfuel(str2, range1, range2);
}
}
// -------------------------------------------------------------------------
public void fill_list() {
final CarHelper h = new CarHelper(getApplicationContext());
Toast.makeText(getApplicationContext(), "Inside if case",
Toast.LENGTH_LONG).show();
mlist = h.selectAllb2();
stg1 = new ArrayList<String>();
int x = 0;
String stg;
for (String[] srch : mlist) {
stg = "Make: " + srch[0] + "\nModel: " + srch[1] + " \nVersion: "
+ srch[2] + "\nPrice: Rs. " + srch[3];
stg1.add(stg);
arr_make.add(srch[0]);
arr_model.add(srch[1]);
arr_ver.add(srch[2]);
System.out.println("srch 0" + srch[0] + "\nsrch 1" + srch[1]
+ "\nsrch 2" + srch[2] + "\nsrch 3" + srch[3]);
x++;
}
System.out.println("length--------------------- " + stg1.size());
// ----------------Image--------------------
int run = 0;
c = dbcarhelper.fetchImgRow("1");
if (c.moveToFirst()) {
do {
Image = c.getBlob(c.getColumnIndex("img_str"));
System.out.println("Image = " + Image);
System.out.println("run = " + run);
byte[] decodedString = Base64.decode(Image, Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
arr_img.add(decodedByte);
System.gc();
run++;
} while (c.moveToNext());
}
dbcarhelper.close();
// ----------------Image--------------------
System.out.println("run after close() = " + run);
dataAdapter = new MyCustomAdapter(this, R.layout.new_search_adptr, stg1);
LV.setAdapter(dataAdapter);
int[] colors = { 0, 0xff00ffff, 0 };
LV.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
LV.setDividerHeight(4);
LV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
New_Details det = new New_Details();
System.out.println("Inside Click !");
String car1 = h.srch_make.get(position);
String carm1 = h.srch_model.get(position);
String carv1 = h.srch_ver.get(position);
det.setImg(arr_img.get(position));
Intent intent = new Intent(Search_list.this, New_Details.class);
Bundle b = new Bundle();
b.putString("car1", car1);
b.putString("carm1", carm1);
b.putString("carv1", carv1);
intent.putExtras(b);
startActivity(intent);
}
});
}
private class MyCustomAdapter extends ArrayAdapter<String> {
private ArrayList<Boolean> status = new ArrayList<Boolean>();
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<String> sList) {
super(context, textViewResourceId, sList);
for (int i = 0; i < arr_make.size(); i++) {
status.add(false);
}
System.out.println("Inside My Custom Adapter.. status all null..! ");
}
private class ViewHolder {
TextView text;
CheckBox chkbox;
ImageView imageview;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr_make.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder = null;
//Log.v("ConvertView", String.valueOf(position));
//if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.new_search_adptr, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.adapterText1);
holder.chkbox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
//---------- Setting the checkBoxes ------------------------
if (status.get(position)) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
//----------------------------------------------------------
holder.imageview = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(holder);
holder.chkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
// User checked (selected) a car
// *********************************
if (cntr > 1) {
// More than two cars selected
Toast.makeText(getApplicationContext(),
"Please select only two cars!",
Toast.LENGTH_LONG).show();
cb.setChecked(false);
} else {
// car selected
status.set(position, true);
cntr++;
System.out.println("Chk List Position= " + position );
for (int i = 0; i < status.size(); i++) {
System.out.println("Chkbox chkd Position= " + i + " Status: "
+ status.get(i));
}
}
} else {
// User Unchecked (de - selected) a car
// *********************************
cntr--;
status.set(position, false);
System.out.println("Unchk List Position= " + position );
for (int i = 0; i < status.size(); i++) {
System.out.println("UnChkbox chkd Position= " + i + " Status: "
+ status.get(i));
}
}
}
});
holder.text.setText(stg1.get(position).toString());
// setting image
holder.imageview.setImageBitmap(arr_img.get(position));
return convertView;
}
}
}
Related
I am making a multi-video downloader. I have created a listview and for each item in the listview an asynctask is called which downloads the file in the background. Everything works perfect. But, if i want to delete an item from the listview for example from position 2, the item at position 3 (both are currently running) comes on position 2 and the asynctask attached previously to position 2 continues running and it shows the progress of asynctask that was previously attached to the position 2. How can I move the asynctask of position 3 to position 2.
Here is my Adapter Class from where I am calling the asynctask class:
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
public static TextView progpercent;
// Simple class to make it so that we don't have to call findViewById frequently
// private static final String TAG = FileDownloadTask.class.getSimpleName();
public static Integer result;
LayoutInflater inflater5;
ImageView delete;
Activity activity1;
int mvalue;
ContextWrapper cw1;
int flag=0;
int status=0;
GlobalDownload downloadList;
ArrayList downloadState;
FileDownloadTask task;
private static class ViewHolder {
TextView textView;
ProgressBar progressBar;
ImageView delete;
DownloadInfo info;
TextView size;
TextView prog;
public TextView progpercent;
}
private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();
public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
List<DownloadInfo> objects, ContextWrapper cw, Activity DownloadScreen) {
super(context, textViewResourceId, objects);
cw1=cw;
activity1=DownloadScreen;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final DownloadInfo info = getItem(position);
ViewHolder holder = null;
if(null == row) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_download_row, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
holder.size=(TextView) row.findViewById(R.id.downloadFileSize);
holder.progpercent=(TextView) row.findViewById(R.id.downloadFileProgress);
holder.delete=(ImageView) row.findViewById(R.id.deletebutton);
// holder.button = (Button)row.findViewById(R.id.downloadButton);
// holder.info = info;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.textView.setText(info.getFilename());
holder.progpercent.setText(info.getDownloadState().toString());
if(info.getStatus()== null)
{
Log.e("DATABASE1", "null ");
status=3;
info.setLastState(2);
}
else if(info.getStatus()== DownloadInfo.State.DONE)
{
if(info.getLastState()==1)
{
Log.e("DATABASE", "LS " + 1);
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
status=1;
}
else if(info.getLastState()==0)
{
Log.e("DATABASE", "LS " + 2);
info.setDownloadState(DownloadInfo.DownloadState.FAILED);
status=1;
}
else
{
status=2;
}
}
Log.e("DATABASE", "DOWNLOAD STATE " + info.getDownloadState().toString());
if(info.getDownloadState()== DownloadInfo.DownloadState.NOT_STARTED)
{
if(status==3) {
holder.progressBar.setProgress(info.getProgress());
holder.progressBar.setMax(100);
holder.progpercent.setText("DOWNLOADING");
}
}
holder.size.setText(info.getFileSize());
info.setProgressBar(holder.progressBar);
if(info.getDownloadState()==DownloadInfo.DownloadState.NOT_STARTED){ info.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
if (MainScreen.settingsvalue==0) {
Log.e("DATABASE", " " + 0);
mvalue = 0;
task = new FileDownloadTask(info, cw1, activity1, mvalue);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if(info.getDownloadState()== DownloadInfo.DownloadState.COMPLETE) {
Log.e("DATABASE", "UPDATE COMPLETE " + info.getDownloadState());
info.setStatus(DownloadInfo.State.DONE);
info.setLastState(1);
holder.progressBar.setProgress(R.drawable.download_bar);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
if(info.getDownloadState()== DownloadInfo.DownloadState.FAILED) {
info.setStatus(DownloadInfo.State.DONE);
MainScreen.newDB.execSQL("update " + DatabaseHelper.TABLE_NAME + " set " + DatabaseHelper.COL_6 + " = '" + info.getStatus() + "', " + DatabaseHelper.COL_7 + " =0 where " + DatabaseHelper.COL_1 + " = " + info.getFileid());
Log.e("DATABASE", "UPDATED ");
info.setLastState(0);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
Log.e("POSITION", "TAG " + index);
Log.e("POSITION", "POSITION " + position);
downloadList = ((GlobalDownload) activity1.getApplicationContext());
downloadState = (ArrayList) downloadList.getDownloadInfo();
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass2.customfilename2= info.getFilename() + "." + info.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass2 cdd = new CustomDialogClass2(MainScreen.activity1);
cdd.show();
CustomDialogClass2.mPosition=position;
CustomDialogClass2.id=info.getFileid();
// downloadState.remove(position);
Log.e("STATUS", "Status before stopping " + info.getDownloadState());
if((info.getDownloadState()== DownloadInfo.DownloadState.DOWNLOADING)) {
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
cancelstatus=1;
task.cancel(true);
}
}
});
return row;
}
}
Here is the Asynctask class
public class FileDownloadTask extends AsyncTask<String, Integer, Integer> {
private static final String TAG = FileDownloadTask.class.getSimpleName();
final DownloadInfo mInfo;
TextView display;
public int progress;
public String encodedurl;
PopupWindow popupWindow;
Activity activity;
// ListView listview1;
// Context context;
LayoutInflater layoutInflater;
static int i=0;
int Mvalue;
ContextWrapper cw;
File file;
String nameoffile;
PowerManager mgr;
PowerManager.WakeLock wakeLock;
public static int cancelstatus =0;
int a=0;
// DownloadInfoArrayAdapter mAdapter;
public FileDownloadTask(DownloadInfo info, ContextWrapper cw1, Activity activity1, int mvalue) {
mInfo = info;
cw=cw1;
activity=activity1;
this.Mvalue=mvalue;
// listView1 = (ListView) listview.findViewById(R.id.downloadListView);
// mAdapter = new DownloadInfoArrayAdapter(, R.id.downloadListView,mInfo);
}
// #Override
protected void onProgressUpdate(Integer... values) {
mInfo.setProgress(values[0]);
mInfo.setFilePercent(values[0]);
// Log.e("FILE PERCENT", String.valueOf(mInfo.getFilePercent()));
// mAdapter.notifyDataSetChanged();
// mAdapter.setNotifyOnChange(true);
// display = (TextView) row.findViewById(R.id.downloadFileProgress);
ProgressBar bar = mInfo.getProgressBar();
// Integer percent=mInfo.getFilePercent();
if (bar != null) {
bar.setProgress(mInfo.getProgress());
// percent(mInfo.getFilePercent());
// display.setText(mInfo.getProgress());
// bar.invalidate();
}
// DownloadScreen.adapter.notifyDataSetChanged();
// DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
}
#Override
protected void onCancelled() {
super.onCancelled();
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
File file = new File(rootdirectory, CustomDialogClass2.customfilename2);
Log.e("FILE", " name" + file.toString());
file.delete();
DownloadScreen.adapter.notifyDataSetChanged();
}
#Override
protected Integer doInBackground(String... params) {
int count;
try {
String state = Environment.getExternalStorageState();
String root = Environment.getExternalStorageDirectory().toString();
URL url = new URL(mInfo.getFileUrl().toString());
Log.e("URL", "" + url);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.connect();
Log.e("connection", " " + 0);
int lenghtOfFile = conection.getContentLength();
Log.e("length", "" + lenghtOfFile);
String nameoffile = mInfo.getFilename() + "." + mInfo.getFileType();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
if (!rootdirectory.exists()) {
rootdirectory.mkdirs();
}
File file = new File(rootdirectory, nameoffile);
file.createNewFile();
Log.e("name of file", "" + nameoffile);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
mInfo.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
long total = 0;
while ((count = input.read(data)) != -1) {
if(!isCancelled()) {
total += count;
progress = (int) ((total * 100) / lenghtOfFile);
publishProgress(progress);
// Log.e("PROGRESS", "" + mInfo.getFileType() + progress);
mInfo.setFilePercent(progress);
output.write(data, 0, count);
i = 1;
}
}
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
mInfo.setStatus(DownloadInfo.State.COMPLETE);
output.flush();
output.close();
input.close();
Log.e("Download Complete", "" + 0);
Log.e("DEVICE SDCARD", " " + Mvalue);
}
return progress;
}
protected void onPostExecute(Integer progress) {
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
DownloadScreen.adapter.notifyDataSetChanged();
DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
activity.sendBroadcast(mediaScanIntent);
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass.customfilename=mInfo.getFilename() + "." + mInfo.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass cdd = new CustomDialogClass(MainScreen.activity1);
cdd.show();
}
#Override
protected void onPreExecute() {
}
}
you should override the remove method of your adapter in order to cancel properly the asyncTask associated to your item.
when i click + button increment the price and click - button decrease the price it's work perfectly but when i scroll listview the value of tvPrices (TextView) is changed.
What should i do for the stay increment price?
here is my adapter
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
price.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
try {
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
} catch (Exception e) {
e.printStackTrace();
}
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
ShowHashMapValue();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
In onclick, after you decrement the value call notifyDataSetChanged()
notifyDataSetChanged
but its a costly operation, since it refreshes complete list
I am trying to build a demo chatting App.I want to show the messages with section headers as Dates like "Today","Yesterday","May 21 2015" etc.I have managed to achieve this but since the new View method gets called whenever I scroll the list.The headers and messages get mixed up.
For simplicity, I have kept the header in the layouts itself and changing its visibility(gone and visible) if the date changes.
Can you help me out with this? Let me know if anyone needs any more info to be posted in the question.
public class ChatssAdapter extends CursorAdapter {
private Context mContext;
private LayoutInflater mInflater;
private Cursor mCursor;
private String mMyName, mMyColor, mMyImage, mMyPhone;
// private List<Contact> mContactsList;
private FragmentActivity mActivity;
private boolean mIsGroupChat;
public ChatssAdapter(Context context, Cursor c, boolean groupChat) {
super(context, c, false);
mContext = context;
mMyColor = Constants.getMyColor(context);
mMyName = Constants.getMyName(context);
mMyImage = Constants.getMyImageUrl(context);
mMyPhone = Constants.getMyPhone(context);
mIsGroupChat = groupChat;
mCursor = c;
// mActivity = fragmentActivity;
/*try {
mContactsList = PinchDb.getHelper(mContext).getContactDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
boolean type;
if (mIsGroupChat)
type = cursor.getString(cursor.getColumnIndex(Chat.COLMN_CHAT_USER)).compareTo(mMyPhone) == 0;
else type = cursor.getInt(cursor.getColumnIndex(Chat.COLMN_FROM_ME)) > 0;
if (type) {
return 0;
} else {
return 1;
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = null;
int itemViewType = getItemViewType(cursor);
if (v == null) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (itemViewType == 0) {
v = mInflater.inflate(R.layout.row_chat_outgoing, parent, false);
} else {
v = mInflater.inflate(R.layout.row_chat_incoming, parent, false);
}
}
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = new ViewHolder();
View v = view;
final Chat chat = new Chat(cursor);
boolean fromMe = mIsGroupChat ? chat.getUser().compareTo(mMyPhone) == 0 : chat.isFrom_me();
if (fromMe) {
// LOGGED IN USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
int color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(color);
holder.chat_name.setText("#You");
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setText(theRest);
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
//holder.chat_text.setText("");
}
updateTimeTextColorAsPerStatus(holder.chat_time, chat.getStatus());
v.setTag(holder);
} else {
// OTHER USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
holder.chat_image = (ImageView) v
.findViewById(R.id.chat_profile_image);
String image = cursor.getString(cursor.getColumnIndex("image"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String color = cursor.getString(cursor.getColumnIndex("color"));
// set the values...
if (holder.chat_image != null) {
MImageLoader.displayImage(context, image, holder.chat_image, R.drawable.round_user_place_holder);
}
int back_color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(back_color);
holder.chat_name.setText(name);
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
Log.d("eywa", "str date is ::::: " + str_date + " pref date is :::::: " + pref_date);
/*if (!TextUtils.isEmpty(pref_date)) {
if (!pref_date.contains(str_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
} else {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
}*/
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
// holder.chat_text.setText("");
}
String phone = cursor.getString(cursor.getColumnIndex("user"));
final Contact contact = new Contact(name, phone, "", color, image);
if (holder.chat_image != null) {
holder.chat_image.setTag(contact);
// holder.chat_name.setTag(contact);
holder.chat_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact con = (Contact) v.getTag();
Intent intent = new Intent(mContext, OtherProfileActivity.class);
intent.putExtra(Constants.EXTRA_CONTACT, con);
mContext.startActivity(intent);
}
});
}
v.setTag(holder);
}
/*else
{
view=
}*/
}
private void updateTimeTextColorAsPerStatus(TextView chat_time, int status) {
if (status == 0) chat_time.setVisibility(View.INVISIBLE);
else {
chat_time.setVisibility(View.VISIBLE);
/* if (status == 1)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.white));*/
if (status == 2)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.darker_gray));
else if (status == 3)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.black));
}
}
#Override
public int getViewTypeCount() {
return 2;
}
public class ViewHolder {
public StyleableTextView chat_name;
public StyleableTextView chat_time;
public StyleableTextView chat_tag;
public ImageView chat_image;
public TextView chat_header_text;
}
#Override
public int getCount() {
if (getCursor() == null) {
return 0;
} else {
return getCursor().getCount();
}
}
}
I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}
Hi I am using custom listview and my list item contains checkbox. When updating the listview with the existing values the background is changed, so it is working fine.But when i clicks the check button, at that time the background will not changing after loading some where again then the background is changed . My question is at the time of check the item the background need to change immediately.
This is my adapter class.
public class GuestListAdapter extends BaseAdapter implements OnClickListener {
private String strExe;
AlertDialog.Builder builder;
Context context;
private ArrayList<String> arrayListFirstName;
private ArrayList<String> arrayListLastName;
private ArrayList<String> arrayListGuests;
private ArrayList<String> arrayCustomOne;
private ArrayList<String> arTempId;
private 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 AlertDialog alertDialog = null;
private ArrayList<Boolean> checks = new ArrayList<Boolean>();
public GuestListAdapter(Context mcontext, ArrayList<String> arrListFN,
ArrayList<String> arrListLN, ArrayList<String> arrListGuest,
ArrayList<String> arrTiketID, ArrayList<String> arrCustOne,
ArrayList<Boolean> chicklist) {
clearAdapter();
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>();
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
Log.d("", "getCount" + arrayListFirstName.size());
return arrayListFirstName.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
Log.d("", "getItem" + arrayListFirstName.size());
return arrayListFirstName.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(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.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
// System.out.println(v + "##########" + " " + v.getId());
// System.out.println(v + "##########" + " " + arTempId.get(txtView4.getId()));
// System.out.println(v + "##########" + " " + chickinlist.get(txtView4.getId()));
}
});
Log.e("", "****************************************************** " );
// Log.v("", "Adapter arr pos " + pos);
// Log.v("", "Adapter arr position " + position);
Log.v("", "Adapter arr size " + arrayListFirstName.size());
Log.v("", "Passsing arr size " + chickinlist.size());
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(""))
{
txtView5.setText("");
}else
{
txtView5.setText(arrayCustomOne.get(position));
}
}
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
strExe = "update ticket_details set checkin_status=1 where tempid="+arTempId.get(chk.getId());
// Log.d("Adapter", "Checked Temp Id "+arTempId.get(chk.getId()));
Log.d("", "Position "+chk.getId()+"tempid "+arTempId.get(chk.getId()));
if (isChecked) {
// views.setBackgroundResource(R.drawable.list_item_checked);
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) {
// myGuestList = new GuestListScreen();
mySqliteAdapter.executeCheckQurey(strExe);
// myGuestList.ListUpdate();
dialog.dismiss();
}
}).show();
// Log.d("", "ID = " + buttonView.getId());
} else {
// views.setBackgroundResource(R.drawable.list_item_unchecked);
strExe = "update ticket_details set checkin_status=0 where tempid="+arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
// Toast.makeText(context, "check release", Toast.LENGTH_SHORT)
// .show();
}
}
});
return views;
}
#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);
}
// private void showADialog(int posit) {
//
// AlertDialog.Builder builder = new AlertDialog.Builder(
// context);
// builder.create();
// builder.setMessage("The clicked row is "
// + arrayListFirstName.get(posit));
// builder.setPositiveButton("Ok?", new DialogInterface.OnClickListener() {
//
// #Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
//
// }).show();
// }
public void clearAdapter() {
if (arrayListFirstName != null) {
arrayListFirstName.clear();
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 just want to change the background of the checked item immediatly without updating the list again.
I think you need to tell the BaseAdapter to refresh the data when your OnCheckedChanged Listener is called.
GuestListAdapter.this.notifyDataSetChanged()