Related
This is my activity where it contains listView and an action bar icon.
Everytime the app run, it will go through this method to load the SQLite data to listView.
public void retrieveList(String name) {
database = mdb.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + MyDatabaseHelper.TABLE__TASK + " WHERE Name = ? ", new String[]{name}, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int iD = cursor.getInt(cursor.getColumnIndex("ID"));
String month = cursor.getString(cursor.getColumnIndex("Month"));
double budget = cursor.getDouble(cursor.getColumnIndex("Budget"));
double totalUsed = cursor.getDouble(cursor.getColumnIndex("Total_Used"));
if (adapter != null) {
adapter.add(iD, month, budget, totalUsed);
listview.setAdapter(adapter);
}
}
}
}
The action bar icon (pen) will open a new dialog. Once the save button clicked, it will add new item to listView.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
mClickedPosition = -1;
final AlertDialog.Builder builder = new AlertDialog.Builder(AddMonthlyExpenses.this);
View promptView = getLayoutInflater().inflate(R.layout.dialog_in_addmonthlyexpenses, null);
save = (Button) promptView.findViewById(R.id.okBtn);
month = (EditText) promptView.findViewById(R.id.month);
budget = (EditText) promptView.findViewById(R.id.budget);
alert = builder.create();
alert.setTitle("Add Month ");
alert.setView(promptView);
alert.show();
month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog(DATE_DIALOG_ID);
}
});
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String month1 = month.getText().toString();
double budget1 = Double.parseDouble(budget.getText().toString());
if ((month1.trim().equals("")) || (String.valueOf(budget1).trim().equals(""))) {
Toast.makeText(getApplicationContext(), " Not Completed", Toast.LENGTH_SHORT).show();
} else {
adapter.add(id,month1, budget1);
Toast.makeText(getApplication(),id+"",Toast.LENGTH_SHORT).show(); // display 0
insert(name, month1, budget1);
listview.setAdapter(adapter);
alert.dismiss();
//retrieveList(String name)
}
}
}
});
break;
ExpensesAdapter
public class ExpensesAdapter extends BaseAdapter {
private static ArrayList<List> search;
private LayoutInflater mInflater;
ListView listview;
Context context;
double used = 0;
public ExpensesAdapter(Context context, ArrayList<List> searchList, ListView listview) {
this.search=searchList;
this.listview=listview;
mInflater = LayoutInflater.from(context);
this.context= context;
}
public int getCount() {
return search.size();
}
public List getItem(int position) {
return search.get(position);
}
public long getItemId(int position) {
return 0;
}
public void removeItem(int position) {
search.remove(position);
this.notifyDataSetChanged();
}
public void add(int id,String month,double budget,double used)
{
List obj = new List(id,month,budget,used);
this.used=used;
obj.setID(id);
obj.setMonthYear(" " + month);
obj.setBudget(budget);
obj.setUsed(used);
search.add(obj);
this. notifyDataSetChanged();
}
public void add(int id,String month, double budget)
{
List obj = new List(id,month,budget);
obj.setMonthYear(" " + month);
obj.setID(id);
obj.setBudget(budget);
search.add(obj);
this. notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder =null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.expenses_adapter, null);
holder= new ViewHolder();
holder.monthAndYear = (TextView) convertView.findViewById(R.id.monthAndYear);
holder.budget = (TextView) convertView.findViewById(R.id.budget);
holder.amount=(TextView)convertView.findViewById(R.id.amount);
holder.progressBar=(ProgressBar)convertView.findViewById(R.id.downloadProgressBar);
holder.balance=(TextView)convertView.findViewById(R.id.balance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.monthAndYear.setText(search.get(position).getMonthAndYear());
holder.budget.setText("RM" + "" + search.get(position).getBudget());
holder.amount.setText("RM" + "" + search.get(position).getUsed());
holder.progressBar.setProgress((int) search.get(position).getUsed());
holder.progressBar.setMax((int) search.get(position).getBudget());
double a = search.get(position).getBudget();
double b = search.get(position).getUsed();
holder.balance.setText("RM"+""+String.format("%.2f", a-b));
return convertView;
}
static class ViewHolder {
TextView monthAndYear, budget,amount,balance;
ProgressBar progressBar;
}
}
Once the new item is added in listView and I press it, I get id= 0. If I exit the app and click again then only it shows the new id. Is there a way I can make new id assign to new list item instead of exit the app or call the retrieveList method after alert.dismiss(); ?
In your adapter your not setting the id to the obj
public void add(int id,String month,double budget,double used)
{
List obj = new List(id,month,budget,used);
this.used=used;
obj.setMonthYear(" " + month);
obj.setBudget(budget);
obj.setUsed(used);
//Add this line your adapter
obj.setID(id);
search.add(obj);
this. notifyDataSetChanged();
}
public void add(int id,String month, double budget)
{
List obj = new List(id,month,budget);
obj.setMonthYear(" " + month);
obj.setBudget(budget);
//Add this line your adapter
obj.setID(id);
search.add(obj);
this. notifyDataSetChanged();
}
Your getItemId() always returns 0. To match your getItem() try returning something like:
public long getItemId(int position) {
List l = getItem(positon);
return l.getId();
}
Then of course your List must have a getId() which returns a long.
I solved by using this method
change insert(name, month1, budget1); to long id= insert(name, month1, budget1); to get the latest id. Then modify code to this
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String month1 = month.getText().toString();
double budget1 = Double.parseDouble(budget.getText().toString());
if ((month1.trim().equals("")) || (String.valueOf(budget1).trim().equals(""))) {
Toast.makeText(getApplicationContext(), " Not Completed", Toast.LENGTH_SHORT).show();
} else {
long id=insert(name, month1, budget1);
adapter.add(id,month1, budget1);
listview.setAdapter(adapter);
alert.dismiss();
check();
}
}
}
});
I am trying working on listactivity in it i am adding items to listview rows . but when i load different data to add an item in list view it repeats the same item added before .
here is my baseadapter class:
public class MyNotiAdapter extends BaseAdapter {
Context context;
String[] data;
String time;
String Name ;
String Number;
private static LayoutInflater inflater = null;
public MyNotiAdapter(Context context, String[] data,String time, String Name ,String Number) {
// TODO Auto-generated constructor stub
this.context = context;
this.data = data;
this.time = time;
this.Name = Name;
this.Number=Number;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder mHolder;
View vi = convertView;
if (vi == null){
vi = inflater.inflate(R.layout.row2, null);
mHolder = new ViewHolder();
mHolder.text= (TextView) vi.findViewById(R.id.lablel);
mHolder.Nameo = (TextView) vi.findViewById(R.id.person);
mHolder.Numbero = (TextView) vi.findViewById(R.id.edu);
mHolder.Time = (TextView) vi.findViewById(R.id.tym);
vi.setTag(mHolder);
mHolder.text.setText(data[position]);
mHolder.Nameo.setText(Name);
mHolder.Numbero.setText(Number);
mHolder.Time.setText(time);
}else {
mHolder = (ViewHolder) convertView.getTag();
}
return vi;
}
public class ViewHolder {
public TextView text;
public TextView Nameo;
public TextView Numbero;
public TextView Time;
}
}
and here is the activity in which i am setting adapter data...
public class noticall extends ListActivity {
CustomDateTimePicker custom;
TextView tv,tv1;
EditText ed;
String store;
static String Names;
public static final int PICK_CONTACT = 1;
String [] adi ;
static int incre=0;
ArrayList<String> myrows = new ArrayList<String>();
private PendingIntent pendingIntent;
ListView listview;
String temp1 ,temp2 ;
int x=0;
OnItemClickListener listener;
String Date,Time,Name,Number;
MyNotiAdapter adp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify);
listview = (ListView) findViewById(android.R.id.list);
listview.setDividerHeight(5);
custom = new CustomDateTimePicker(noticall.this,new CustomDateTimePicker.ICustomDateTimeListener() {
#Override
public void onCancel() {
finish();
}
#Override
public void onSet(Dialog dialog, Calendar calendarSelected,Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName,
int hour24, int hour12, int min, int sec,
String AM_PM) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, monthNumber, date, hour24, min, 0);
long when = calendar.getTimeInMillis(); // notification time
Intent myIntent = new Intent(noticall.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(noticall.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
//temp1= store =calendarSelected.get(Calendar.DAY_OF_MONTH) + "/" + (monthNumber+1) + "/" +
// year + ", " + hour12 + ":" + min + " " + AM_PM;
Date = calendarSelected.get(Calendar.DAY_OF_MONTH) + "/" + (monthNumber+1) + "/" +year;
Time = hour12 + ":" + min + " " + AM_PM;
Log.e("Timeee", Time+"");
setlisto(Date);
Toast.makeText(noticall.this, store, Toast.LENGTH_SHORT).show();
}
});
/*
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);
/**
* Pass Directly current data and time to show when it pop up
*/
custom.setDate(Calendar.getInstance());
//custom.showDialog();
findViewById(R.id.button_date).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
custom.showDialog();
incre++;
}
});
// ((BaseAdapter) listview.getAdapter()).notifyDataSetChanged() ;
// listview.getAdapter().notifyAll();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_CANCELED){
if (requestCode == 1)
{
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
String[] segments = contactUri.toString().split("/");
String id = segments[segments.length - 1];
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
int cid = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
String contactid = cursor.getString(cid);
if (contactid.equals(id))
{
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);
// Retrieve the contact name from the DISPLAY_NAME column
int column_name = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = cursor.getString(column_name);
// Do something with the phone number...
// Toast.makeText(this, "I added the Contact: \n" + name + " " + number, Toast.LENGTH_SHORT).show();
// ed.setText(name+" - "+number);
Name= Names=name;
Number =number;
}
cursor.moveToNext();
}
cursor.close();
}
}
}
public void setlisto(String one ){
Log.e("setlistoo",one+"");
myrows.add(one);
adi = myrows.toArray(new String[myrows.size()]);
listview.setAdapter(new MyNotiAdapter(noticall.this, adi,Time,Name,Number));
// ((BaseAdapter) listview.getAdapter()).notifyDataSetChanged();
//listview.invalidateViews();
x++;
}
}
i have gone through all the solutions provided on internet . i think i am making some mistake somewhere . if anyone can found where the problem lies...?
i Have noticed only Data[] array is updating with different values. but other String variables are overwriting on every item i add.. why is this happening ?
I think you need to do call notifyDataSetChanged method and before adding data dynamically call ones setAdapter.
or you can go through this link http://androidadapternotifiydatasetchanged.blogspot.in/
okay i have solved it by myself . the problem was i was passing simple string but i have to pass string array in order to add new data to listviews.
here are the changes i made ..
in activity:
public void setlisto(String one ){
Log.e("setlistoo",one+"");
myrows.add(one);
time1.add(Time);
name1.add(Name);
number1.add(Number);
adi = myrows.toArray(new String[myrows.size()]);
adi1=time1.toArray(new String[time1.size()]);
adi2=name1.toArray(new String[name1.size()]);
adi3=number1.toArray(new String[number1.size()]);
listview.setAdapter(new MyNotiAdapter(noticall.this, adi,adi1,adi2,adi3));
// if(adi!=null)
//adp.notifyDataSetChanged();
x++;
}
in baseadapter class :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder mHolder;
View vi = convertView;
if (vi == null){
vi = inflater.inflate(R.layout.row2, null);
mHolder = new ViewHolder();
mHolder.text= (TextView) vi.findViewById(R.id.lablel);
mHolder.Nameo = (TextView) vi.findViewById(R.id.person);
mHolder.Numbero = (TextView) vi.findViewById(R.id.edu);
mHolder.Time = (TextView) vi.findViewById(R.id.tym);
vi.setTag(mHolder);
mHolder.text.setText(data[position]);
mHolder.Nameo.setText(Name[position]);
mHolder.Numbero.setText(Number[position]);
mHolder.Time.setText(time[position]);
}else {
mHolder = (ViewHolder) convertView.getTag();
}
return vi;
}
everything goes smooth now ... its working perfect . it might help someone like me . Cheers..
Your code seems need to be refactored a lot.
Okay First, create an Model Object class, let say MyReminderObject.java :
public class MyReminderObject {
public String date;
public String time;
public String name;
public String number;
}
In your Adapter :
Add a list of MyReminderObject.
private List<MyReminderObject> mList;
Add a new constructor :
public MyNotiAdapter(Context context) {
mList = new ArrayList<MyReminderObject>();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Change some methods :
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
In your getView method, change some codes :
MyReminderObject item = mList.get(position);
mHolder.text.setText(item.date);
mHolder.Nameo.setText(item.name);
mHolder.Numbero.setText(item.number);
mHolder.Time.setText(item.time);
Still in you adapter, add a function to add item :
public void addReminder(MyReminderObject item){
mList.add(item);
notifyDataSetChanged();
}
In your Activity :
in your onCreate() :
listview.setDividerHeight(5);
adp = new MyNotiAdapter(noticall.this);
listview.setAdapter(adp);
Lastly, on your setListTo() method :
public void setlisto(String one ){
Log.e("setlistoo",one+"");
MyReminderObject newItem = new MyReminderObject();
newItem.date = one;
newItem.time = Time;
newItem.name = Name;
newItem.number = Number;
adp.addReminder(newItem);
x++;
}
I just want to get the value of clicked list item,
i.e if list contains apple,ball,cat, then clicked on apple then it gives value as apple, ,In the below code I am using inner class base adapter to display the data.
public class RecordsActivity extends Activity implements
OnItemClickListener
{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
ArrayList<String> billDate = new ArrayList<String>();
ArrayList<String> billNo = new ArrayList<String>();
ArrayList<String >partyName=new ArrayList<String>();
ArrayList<String> billAmount = new ArrayList<String>();
ArrayList<String >receipt=new ArrayList<String>();
ArrayList<String >balance=new ArrayList<String>();
ArrayList<String> week = new ArrayList<String>();
ArrayList<String> amount = new ArrayList<String>();
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
/*listProduct.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
listProduct.setClickable(true);
String data = (String)listProduct.getItemAtPosition(arg2);
Toast.makeText(getApplicationContext(),data,
Toast.LENGTH_SHORT).show();
}
});*/
}
protected void onResume()
{
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name +
"' ", null);
String
BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst())
{
do
{
BILL_DATE = c.getString(1);
BILL_NO=c.getString(2);
PARTY_NAME=c.getString(3);
BILL_AMOUNT=c.getString(4);
RECEIPT=c.getString(5);
BALANCE=c.getString(6);
WEEK=c.getString(7);
AMOUNT=c.getString(8);
billDate.add(BILL_DATE);
billNo.add(BILL_NO);
partyName.add(PARTY_NAME);
billAmount.add(BILL_AMOUNT);
receipt.add("RECEIPT");
balance.add(BALANCE);
week.add(WEEK);
amount.add(AMOUNT);
} while (c.moveToNext());
}
DisplyRecords dsptProd=new
DisplyRecords(RecordsActivity.this,billDate,billNo,partyName,
billAmount,receipt,balance,week,amount);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB()
{
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
class DisplyRecords extends BaseAdapter
{
Context c;
ArrayList<String > BILLDATE;
ArrayList<String>BILLNO;
ArrayList<String> PARTYNAME;
ArrayList<String>BILLAMOUNT;
ArrayList<String>RECEIPT;
ArrayList<String> BALANCE;
ArrayList<String>WEEK;
ArrayList<String>AMOUNT;
public DisplyRecords(RecordsActivity recordsactivity,ArrayList<String>
billDate, ArrayList<String> billNo, ArrayList<String>
partyName,ArrayList<String> billAmount, ArrayList<String> receipt,
ArrayList<String> balance, ArrayList<String> week,ArrayList<String> amount)
{
this.c=recordsactivity;
this.BILLDATE=billDate;
this.BILLNO=billNo;
this.PARTYNAME=partyName;
this.BILLAMOUNT=billAmount;
this.RECEIPT=receipt;
this.BALANCE=balance;
this.WEEK=week;
this.AMOUNT=amount;
//TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return BILLDATE.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int pos, View row, ViewGroup parent)
{
View child=row;
LayoutInflater layoutinflater;
if(child==null)
{
layoutinflater=(LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView)
child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView)
child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
txt_billdate.setText(BILLDATE.get(pos));
txt_billno.setText(BILLNO.get(pos));
txt_partyname.setText(PARTYNAME.get(pos));
txt_billamt.setText(BILLAMOUNT.get(pos));
txt_receipt.setText(RECEIPT.get(pos));
txt_balance.setText(BALANCE.get(pos));
txt_wk.setText(WEEK.get(pos));
txt_amount.setText(AMOUNT.get(pos));
// TODO Auto-generated method stub
return child;
}
}
A few assumptions here, your actual fields do not need to be ArrayList's since each query returns a single row item from the db, i create a master object with Strings to represent the data...
So here is how i would do it, you need to re structure your data
First i would change your data to a :
public class ParentObject {
public String BILLDATE ;
public String BILLNO ;
public String PARTYNAME ;
public String BILLAMOUNT ;
public String RECEIPT ;
public String BALANCE ;
public String WEEK ;
public String AMOUNT ;
}
UPDATE
then i would change my Activity to:
public class RecordsActivity extends Activity implements OnItemClickListener{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
// your new parent object ArrayList, much cleaner
List<ParentObject> parentObjects;
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(this);
}
protected void onResume(){
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name + "' ", null);
String BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst()){
// initialize the parent arrayList
parentObjects = new ArrayList<ParentObject>();
do{
// initialize a single object
ParentObject parentObject = new ParentObject();
// fill in its data
parentObject.BILL_DATE = c.getString(1);
parentObject.BILL_NO=c.getString(2);
parentObject.PARTY_NAME=c.getString(3);
parentObject.BILL_AMOUNT=c.getString(4);
parentObject.RECEIPT=c.getString(5);
parentObject.BALANCE=c.getString(6);
parentObject.WEEK=c.getString(7);
parentObject.AMOUNT=c.getString(8);
// add it to your list
parentObjects.add(parentObject);
} while (c.moveToNext());
}
// pass the List<ParentObject> into your adapter
DisplyRecords dsptProd= new DisplyRecords(RecordsActivity.this, (ArrayList<ParentObject>)parentObjects);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB(){
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// access to all your data through the parentObject
ParentObject data = (ParentObject) listProduct.getItemAtPosition(position);
// access all fields for this parent
Toast.makeText(RecordsActivity.this, "data: "+ data.BILL_DATE, + " ," + data.BILL_NO, " , etc", Toast.LENGTH_LONG).show();
}
}
and then update your Adapter to handle the List
class DisplyRecords extends BaseAdapter {
Context c;
List<ParentObject> parentObjects;
public DisplyRecords(Context context, ArrayList<ParentObject> parentObjects){
this.c=context;
this.parentObjects = parentObjects;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return parentObjects.size();
}
#Override
public Object getItem(int position) {
return parentObjects.get(position); // always return this parent
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int pos, View row, ViewGroup parent){
// You should implement the ViewHolder pattern, this is not doing that...
View child=row;
LayoutInflater layoutinflater;
if(child==null){
layoutinflater=(LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView) child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView) child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
ParentObject parentObject = parentObjects.get(pos);
txt_billdate.setText(parentObject.BILLDATE);
txt_billno.setText(parentObject.BILLNO.);
txt_partyname.setText(parentObject.PARTYNAME);
txt_billamt.setText(parentObject.BILLAMOUNT);
txt_receipt.setText(parentObject.RECEIPT);
txt_balance.setText(parentObject.BALANCE);
txt_wk.setText(parentObject.WEEK);
txt_amount.setText(parentObject.AMOUNT);
// TODO Auto-generated method stub
return child;
}
}
Im using the cwac-endless EndlessAdapter with a custom ListViewAdapter. With an AsyncTask i get the data form he webserver in 2 phases.
1) i get all the id's of the elements
2) using the EndlessAdapter i want to load say 4 elements at a time (i get from the server 4 elements by their id)
The problem that im facing is that as i create my custom ListViewAdapter when i call the contructor of MyEndlessAdapter which creates the list of items with the first bach of items. when i load the next batch of elements my custom ListViewAdapter it gets the correct items from the server but i recycles the getView(graphic/visual stuff). What am i doing wrong!
I think a possible solution bwould be to use the add method of the CustomListView but i dont know how to call it from the CompraFragment class.
How do i solve this problem?
Thanks
ListViewAdapter code:
public class ListViewAdapter extends ArrayAdapter<Item> {
private LayoutInflater inflater = null;
private final String TAG = "ListViewAdapter";
public Context context;
public int layoutResourceId;
public ArrayList<Item> items;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<Item> items) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.context = context;
this.items = items;
}
public ListViewAdapter(Context context, int listviewItemRow) {
super(context, listviewItemRow);
this.context = context;
}
#Override
public void add(Item object) {
Log.i(TAG, "---ADD---");
items.add(object);
//super.add(object);
}
#Override
public void clear() {
super.clear();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public void remove(Item object) {
super.remove(object);
}
#Override
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Item item = items.get(position);
Log.w(TAG, "view of Item " + item.getId() + " at position " + position);
ItemView view;
if (convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
view.checkFollowing(item, this, 3);
view.setTag(Long.toString(item.getId()));
Log.e(TAG, "CREATED ITEM " + item.getId() + " at position " + position);
} else {
view = (ItemView) convertView;
Log.i(TAG, "RECYCLED ITEM " + item.getId() + " at position " + position);
}
view.setOnClickListener(new OnItemClickListener(position));
view.showItems(item);
return view;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View v) {
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
}
CompraFragment code:
public class CompraFragment extends ListFragment {
private static final String TAG = "CompraFragment";
public ListView listView;
public MyEndlessAdapter adapter = null;
public ListViewAdapter mListViewAdapter;
private DownloadTask mDownloadTask = null;
public ArrayList<Item> items;
public ArrayList<Long> ids;
public Bitmap icon;
public int currentItemId = 0;
public String category = "";
public String latitude = "";
public String longitude = "";
public String radius = "";
public String keywords = "";
public String order = "";
public String state = "2";
//numero di elementi caricabili sulla wall all volta
public final int BATCH_SIZE = 4;
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
progressDialog = new ProgressDialog(this.getActivity());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_aggiorna:
items = new ArrayList<Item>();
ids = new ArrayList<Long>();
mDownloadTask = new DownloadTask();
mDownloadTask.execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
inflater.inflate(R.menu.compra, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(TAG, "onCreateView");
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null){
category = (String) extras.get("category");
latitude = (String) extras.get("latitude");
longitude = (String) extras.get("radius");
radius = (String) extras.get("radius");
keywords = (String) extras.get("keywords");
order = (String) extras.get("order");
state = (String) extras.get("state");
}
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
mDownloadTask = new DownloadTask();
mDownloadTask.execute();
return rootView;
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class DownloadTask extends AsyncTask<Integer, Void, Boolean> {
#Override
protected Boolean doInBackground(Integer... params) {
ids = new ArrayList<Long>();
ids = MVPFunctions.getInstance().search(category, latitude, longitude, radius, keywords, order, state);
if (ids.isEmpty()){
return false;
} else {
Log.i(TAG, "ids size = " + ids.size());
}
return true;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
//progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
progressDialog.setMessage("Downloading Content...");
progressDialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
mDownloadTask = null;
if (!success){
Log.i("onPostExecute", "items null");
Toast.makeText(getActivity(), "Non ci sono elementi da caricare", Toast.LENGTH_LONG).show();
} else {
items = new ArrayList<Item>();
adapter = new MyEndlessAdapter(items);
adapter.setRunInBackground(false);
listView.setAdapter(adapter);
}
}
#Override
protected void onCancelled() {
mDownloadTask = null;
}
}
class MyEndlessAdapter extends EndlessAdapter implements IItemsReadyListener {
private RotateAnimation rotate = null;
MyEndlessAdapter(ArrayList<Item> list) {
super(new ListViewAdapter(getActivity(),R.layout.listview_item_row, list));
rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
Log.i(TAG, "CONSTRUCTER CALLED");
}
#Override
protected View getPendingView(ViewGroup parent) {
View row = getActivity().getLayoutInflater().inflate(R.layout.listview_item_row, null);
View child;
child = row.findViewById(R.id.relativeLayout);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return (row);
}
#Override
protected boolean cacheInBackground() throws Exception {
//Log.i(TAG, "cacheInBackground - items.size(): " + items.size());
new FetchDataTask(this, items.size()).execute();
if (items.size() < ids.size() ){
return true;
} else {
return false;
}
}
#Override
public void onItemsReady(ArrayList<Item> data) {
Log.e(TAG, "onItemsReady");
items.addAll(data);
// Tell the EndlessAdapter to remove it's pending view and call notifyDataSetChanged()
adapter.onDataReady();
progressDialog.dismiss();
}
#Override
protected void appendCachedData() {
// TODO Auto-generated method stub
}
}
interface IItemsReadyListener {
public void onItemsReady(ArrayList<Item> data);
}
class FetchDataTask extends AsyncTask<Void, Void, ArrayList<Item>> {
private static final String TAG = "FetchDataTask";
IItemsReadyListener listener;
//The point from where to start counting.
int startPoint;
protected FetchDataTask(IItemsReadyListener listener, int startPoint) {
this.listener = listener;
this.startPoint = startPoint;
}
#Override
protected ArrayList<Item> doInBackground(Void... params) {
ArrayList<Item> result = new ArrayList<Item>();
Item item;
for (int i = startPoint; ((i < ids.size()) && (i < startPoint + BATCH_SIZE)); i++) {
Log.i(TAG, "i = " + i);
item = MVPFunctions.getInstance().getItem(ids.get(i));
result.add(item);
}
return (result);
}
#Override
protected void onPostExecute(ArrayList<Item> result) {
listener.onItemsReady(result);
}
}
}
ItemView code:
public class ItemView extends LinearLayout {
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
public ToggleButton followButton;
public String nextFollowAction = "";
public ListViewAdapter lva;
public String mLogin;
public String mPassword;
public int statusCode;
public Item item;
public BackgroundTask mBackgroundTask = null;
public ItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
prezzo = (TextView)findViewById(R.id.tvPrezzo);
scadenza = (TextView)findViewById(R.id.tvScadenza);
followers = (TextView)findViewById(R.id.tvFollowers);
ic_thumbnail = (ImageView)findViewById(R.id.ic_thumbnail);
hProgressBar = (ProgressBar)findViewById(R.id.hProgressBar);
followButton = (ToggleButton)findViewById(R.id.btnFollow);
}
public void showItems(final Item item) {
prezzo.setText(item.getPrezzo());
ic_thumbnail.setImageBitmap(item.getIcon());
scadenza.setText(item.getScadenza());
followers.setText("Followers: " + item.getFollowers());
hProgressBar.setProgress(item.getCoefficient());
followButton.setTag(item.getId());
}
public void askForFollowing(String nextFollowAction, final Item item, final int statusCode){
//Log.e("status code fo item is", Integer.toString(statusCode) + " " + item.getId());
//Status code: 0 --> OK
if(statusCode == 0) {
//Log.i("statusCode == 0", "richiesta evasa correttamente");
changeFollowStatus(nextFollowAction, item);
}
// Status code 108 --> Oggetto giĆ seguito
else if ((statusCode == 108) && (nextFollowAction.contains("kCheckFollowAction"))) {
//Log.i("statusCode == 108", "gray");
nextFollowAction = "kUnfollowAction";
followButton.setEnabled(true);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
lva.notifyDataSetChanged();
followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.setEnabled(false);
setFollowing("kUnfollowAction", item, (long) 2);
}
});
}
// Status code 122 --> Oggetto non ancora seguito
else if ((statusCode == 122) && (nextFollowAction.contains("kCheckFollowAction"))) {
//Log.i("statusCode == 122", "green");
nextFollowAction = "kFollowAction";
followButton.setEnabled(true);
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
lva.notifyDataSetChanged();
followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.setEnabled(false);
setFollowing("kFollowAction", item, (long) 1);
}
});
} else {
Log.e("error", "error non e ne 0 ne 108 ne 122");
Log.e("error", nextFollowAction);
Log.e("error", Long.toString(item.getId()));
Log.e("error", Integer.toString(statusCode));
}
}
public void changeFollowStatus(String nextFollowAction, Item item){
//Log.i("changeFollowStatus action", nextFollowAction);
if(nextFollowAction.contains("kFollowAction")) {
//Log.w("changeFollowStatus increase", "+1");
nextFollowAction = "kUnfollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
followButton.getTextOn();
increaseFollowers(item);
}
else if(nextFollowAction.contains("kUnfollowAction")){
//Log.w("changeFollowStatus decrease", "-1");
nextFollowAction = "kFollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
followButton.getTextOff();
decreaseFollowers(item);
}
}
public void increaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) + 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
public void decreaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) - 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
public void checkFollowing(Item item, ListViewAdapter listViewAdapter, long follow) {
this.lva = listViewAdapter;
mBackgroundTask = new BackgroundTask();
try {
int statusCode = mBackgroundTask.execute(item.getId(), follow).get();
askForFollowing("kCheckFollowAction", item, statusCode);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public void setFollowing(String nextFollowAction, Item item, Long follow){
mBackgroundTask = new BackgroundTask();
try {
int statusCode = mBackgroundTask.execute(item.getId(), follow).get();
/*
Log.i("setFollowing p1", Long.toString(follow));
Log.i("setFollowing p1", nextFollowAction);
Log.i("setFollowing p2", Long.toString(item.getId()));
Log.i("setFollowing p3", Integer.toString(statusCode));
*/
askForFollowing(nextFollowAction, item, statusCode);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class BackgroundTask extends AsyncTask<Long, Void, Integer> {
private int statusCode;
#Override
protected Integer doInBackground(Long... params) {
// TODO: attempt authentication against a network service.
statusCode = MVPFunctions.getInstance().followItem(mLogin, mPassword, params[0], params[1].intValue());
return statusCode;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
}
#Override
protected void onPostExecute(Integer result) {
mBackgroundTask = null;
//askForFollowing("kCheckFollowAction", item, statusCode);
//listViewAdapter.notifyDataSetChanged();
//result1 = listener.processFinish(result);
//setStatusCode(result);
//delegate.processFinish(result);
//ItemView
//Log.i("onPostExecute statusCode", Integer.toString(success) + " = " + Integer.toString(statusCode));
}
#Override
protected void onCancelled() {
mBackgroundTask = null;
}
}
}
When a view is recycled [i.e., passed to getView() as a non-null convertView], you need to update it to reflect the state of the current item. So, the 2 lines indicated below need to be moved after the if/then block.
public View getView(final int position, View convertView, ViewGroup parent) {
Item item = items.get(position);
Log.w(TAG, "view of Item " + item.getId() + " at position " + position);
ItemView view;
if (convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
Log.e(TAG, "CREATED ITEM " + item.getId() + " at position " + position);
} else {
view = (ItemView) convertView;
Log.i(TAG, "RECYCLED ITEM " + item.getId() + " at position " + position);
}
// ===> These 2 lines always need to be executed. <===
view.checkFollowing(item, this, 3);
view.setTag(Long.toString(item.getId()));
view.setOnClickListener(new OnItemClickListener(position));
view.showItems(item);
return view;
}
I have added two spinners on custom adapter list view. All is good but when I add new item to list view then value of previous item's spinner is transformed to new item. And on scrolling list view values of spinners also rotates. Any Help please.
public class CustomAdapter extends BaseAdapter {
private ArrayList<MyMessageDetails> _data;
Context _c;
ProductsItemViewHolder holder;
CustomAdapter (ArrayList<MyMessageDetails> data, Context c){
_data = data;
_c = c;
}
public int getCount() {
// TODO Auto-generated method stub
return _data.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return _data.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
final MyMessageDetails msg = _data.get(position);
if (v == null)
{
LayoutInflater vi = (LayoutInflater)_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listview_item_row, null);
holder = new ProductsItemViewHolder();
holder.image = (ImageView) v.findViewById(R.id.icon);
holder.fromView = (TextView) v.findViewById(R.id.textView1);
holder.spinnersizes = (Spinner) v.findViewById(R.id.spinner1);
holder.spinnercopies = (Spinner) v.findViewById(R.id.spinner2);
String Photo_copies[];
Photo_copies=new String[100];
int x = 1;
while( x < 101 ) {
if(x == 1){
Photo_copies[x-1]= String.valueOf(x) + " Copy";
}else{
Photo_copies[x-1]= String.valueOf(x) + " Copies";
}
x++;
}
String array_spinner[];
array_spinner=new String[5];
array_spinner[0]="4x6|Plastic|RS 20";
array_spinner[1]="option 2";
array_spinner[2]="option 3";
array_spinner[3]="option 4";
array_spinner[4]="option 5";
ArrayAdapter adapter = new ArrayAdapter(_c,android.R.layout.simple_spinner_item, array_spinner);
ArrayAdapter adapter2 = new ArrayAdapter(_c,android.R.layout.simple_spinner_item, Photo_copies);
holder.spinnersizes.setAdapter(adapter);
holder.spinnercopies.setAdapter(adapter2);
holder.spinnercopies.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
String sizes = holder.spinnersizes.getSelectedItem().toString();
holder.spinnersizes.setTag(position);
String copies = holder.spinnercopies.getSelectedItem().toString();
String mycopies = copies;
String myprice = sizes;
myprice = myprice.substring(myprice.lastIndexOf(" ") + 1);
mycopies = mycopies.substring(0, mycopies.lastIndexOf(" "));
int finalprice = Integer.parseInt(myprice) * Integer.parseInt(mycopies);
holder.fromView.setText(holder.image.getTag().toString() + " Copies:" + mycopies + " Price:" + finalprice);
msg.setCopies(mycopies);
msg.setSize(String.valueOf(finalprice));
// lab_gallery.Calculate_Bill();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.spinnersizes.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
// your code here
String sizes = holder.spinnersizes.getSelectedItem().toString();
holder.spinnersizes.setTag(position);
String copies = holder.spinnercopies.getSelectedItem().toString();
String mycopies = copies;
String myprice = sizes;
myprice = myprice.substring(myprice.lastIndexOf(" ") + 1);
mycopies = mycopies.substring(0, mycopies.lastIndexOf(" "));
int finalprice = Integer.parseInt(myprice) * Integer.parseInt(mycopies);
holder.fromView.setText(holder.image.getTag().toString() + " Copies:" + mycopies + " Price:" + finalprice);
msg.setCopies(mycopies);
msg.setSize(String.valueOf(finalprice));
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.image.setImageBitmap(msg.getIcon());
holder.fromView.setTag(msg.getUrl());
holder.fromView.setText(msg.getName());
holder.image.setTag(msg.getName());
msg.setCopies("1");
msg.setSize("20");
v.setTag(holder);
} else {
holder = (ProductsItemViewHolder) v.getTag();
}
if (holder.spinnersizes.getTag() != null){
holder.spinnersizes.setSelection(Integer.parseInt(holder.spinnersizes.getTag().toString()));
}
//image.setScaleType(ScaleType.FIT_XY);
return v;
}
static class ProductsItemViewHolder {
ImageView image;
TextView fromView;
Spinner spinnersizes;
Spinner spinnercopies;
}
}
This is because of view recycling. View are recycled with the last state. If your spinner had something selected, and if that view is reused it'll also pick the state of the spinner. You need to add logic to preserve state of your Spinners. You can maintain a dictionary with row position and selectedIndex.
//Class level field
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
inside your getView() method check if we have a state saved for the spinner at this row psition
if (myMap.containsKey(position)) {
spinner.setSelection(myMap.get(position));
}
Saving state when an item is selected in spinner
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int selectedIndex, long id) {
//...
myMap.put(position, selectedIndex);
//...
}