Related
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 have create an app in which,i want to show the checkbox prechecked with the help of xml,and after that user can checked or uncheked the checkbox,but xaml is not showing it checked on start of the app in device,what is the problem.please advise.
MainActivity
public class File_Selecter extends Activity implements OnItemClickListener {
EditText edDelimiter, edqualifier, edcolumn, edrow;
ListView list;
StringBuilder addition = new StringBuilder();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list3 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
private Button btnsave;
String str;
int t;
int count = 0;
String[] BreakData, roz;
TextView textnum;
static String fileinfo;
static StringBuilder conct = new StringBuilder();
static int ResultCode = 12;
String name = "", number = "";
MyAdapter ma;
String fin = "";
String[] cellArray;
String[] art = null;;
String pathname = Environment.getExternalStorageDirectory()
.getAbsolutePath();
static String contacts = "";
static String mixer;
static String delimiter, qulifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_file);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#00aef0"));
actionBar.setBackgroundDrawable(colorDrawable);
Intent itadd = new Intent();
// edittext name
// final String name=itadd.getStringExtra("name").toString();
textnum = (TextView) findViewById(R.id.textnum1);
list = (ListView) findViewById(R.id.listview);
ma = new MyAdapter();
list.setAdapter(ma);
// list.setOnItemClickListener(this);
// list.setItemsCanFocus(false);
// list.setTextFilterEnabled(true);
edDelimiter = (EditText) findViewById(R.id.edDelimiter);
edcolumn = (EditText) findViewById(R.id.edcoloumns);
edrow = (EditText) findViewById(R.id.edrow);
edqualifier = (EditText) findViewById(R.id.edqualifier);
// edittext number
// final String number=itadd.getStringExtra("number").toString();
edDelimiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edDelimiter.setError(null);
}
});
if(fileinfo!=null){
//Toast.makeText(getApplication(),
//fileinfo.toString(), Toast.LENGTH_LONG)
//.show();
if (delimiter != null){
edDelimiter.setText( SmsSend
.delim1.toString());
qulifier= SmsSend
.qulifier.toString(); }
ToRead(fileinfo);
// contacts from smssend
contacts = SmsSend.contacts1;
if (SmsSend.contacts1 != null) {
cellArray = contacts.split(";");
if(list2.size() != 0){
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list2.size(); j++) {
if (list2.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}}}}
else{
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list1.size(); j++) {
if (list1.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}
}
}
}
}
}
// button1
btnsave = (Button) findViewById(R.id.btnsave);
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edDelimiter.getText().toString().length()== 0){
edDelimiter.setError("Delimiter ir required");
}
if(File_Explorer.fileSizeInMB <= 1){
ToRead(fileinfo);
//finish();
}else{
Toast.makeText(getApplication(), "file size is too large", Toast.LENGTH_LONG).show();
}
}
});
}
public void ToRead(String fileinfo) {
if (fileinfo != null) {
delimiter = edDelimiter.getText().toString();
// Toast.makeText(getApplication(), delimiter, Toast.LENGTH_LONG).show();
//delim=":";
qulifier = edqualifier.getText().toString();
//Toast.makeText(getApplication(), qulifier.toString(), Toast.LENGTH_LONG).show();
// qulifier="\\";
// finish();
mixer = qulifier + delimiter;
BreakData = fileinfo.split(mixer);
str = edrow.getText().toString().trim();
try {
t = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// Handle parse error.
}
if (BreakData != null) {
// String t2= (String.valueOf(t));
if (File_Explorer.fileExtension.equals("vcf")) {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list2.add(fin.toString());
}
}
for (int a = 0; a < list2.size() && a < t; a++) {
list1.add(list2.get(a).toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list1.add(fin.toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
} else {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length && i < t; i++) {
list1.add(BreakData[i].toString());
}
textnum.setText(Integer.toString(t));
}
}
else {
for (int i = 0; i < BreakData.length; i++) {
list1.add(BreakData[i].toString());
//t = i;
}
textnum.setText(Integer.toString(BreakData.length));
}
}
}
}
list.setAdapter(ma);
// fileinfo= null;
//edDelimiter.setText(null);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < list1.size(); i++)
{
if (ma.mCheckStates.get(i) == false) {
// Toast.makeText(getApplication(), "hiii",
// Toast.LENGTH_LONG).show();
StringTokenizer st1 = new StringTokenizer(list1.get(i)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(i).toString());
}
}
//Toast.makeText(getApplication(), phno0.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.add_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.attachments:
fileinfo = null;
Intent i = new Intent(File_Selecter.this, File_Explorer.class);
startActivityForResult(i, ResultCode);
break;
case android.R.id.home:
// app icon in action bar clicked; go home
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int j = 0; j < list1.size(); j++)
{
if (ma.mCheckStates.get(j) == true) {
StringTokenizer st1 = new StringTokenizer(list1.get(j)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(j).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(j).toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
fileinfo = data.getStringExtra("name");
}
// list.setAdapter(ma);
}
if (resultCode == RESULT_CANCELED) {
}
}
AdapterCLass
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(list1.size());
mInflater = (LayoutInflater) File_Selecter.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Save ListView state
#Override
public int getCount() {
// TODO Auto-generated method stub
return list1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
// tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(list1.get(position));
// tv1.setText(phno1.get(position));
cb.setTag(position);
//cb.setChecked(mCheckStates.get(position, true));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
row.layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:ems="20"
android:text="TextView"
android:textColor="#0082e6" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checked="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="22dp"
android:layout_marginTop="5dp" />
</RelativeLayout>
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;
}
}
}
I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}
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.");
}
}
}
}