How to use getPosition() to get the ListView value? - android

In Activity WorkDetailsTable , it has a ListView as shown below. When it is clicked, it should display the value on the Add_Details_Information EditText
Assume the first list is clicked, and it intent to Add_Details_Information
Noted that the value on editText was actually get from the second list in Activity A. But what I want is get value accordingly to their position not the latest value.
WorkDetailsTable
int mClickedPosition;
MyCustomBaseAdapter objMyCustomBaseAdapter;
ArrayList<SearchResults> results=new ArrayList<SearchResults>();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mClickedPosition = position;
// how to getPosition???
Intent i = new Intent(getApplication(), Add_Details_Information.class);
i.putExtra("ReceiveProject", ReceiveProject);
i.putExtra("ReceiveDescription", ReceiveDescription);
i.putExtra("ReceiveProgress", ReceiveProgress);
i.putExtra("ReceiveTimeIn", ReceiveTimeIn);
i.putExtra("ReceiveTimeOut", ReceiveTimeOut);
i.putExtra("date",date);
i.putExtra("status", status);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}
Add_Details_Information
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_details_information);
addItemsOnSpinner(); // Spinner for project/service/training
tp = new TimePick(); // call tmePick
description=(EditText)findViewById(R.id.editTextWorkDescription);
timeIn=(EditText)findViewById(R.id.TimeIn);
timeOut=(EditText)findViewById(R.id.TimeOut);
save=(Button)findViewById(R.id.saveButton);
seekBar=(SeekBar)findViewById(R.id.seekBarPercentage);
progressText=(TextView)findViewById(R.id.textProgress);
progressText.setText("Covered:" + "" + seekBar.getProgress() + "/" + seekBar.getMax());
if(getIntent().getExtras()!=null)
{
final String Project1=getIntent().getStringExtra("ReceiveProject");
final String Description1=getIntent().getStringExtra("ReceiveDescription");
final int Progress1=getIntent().getIntExtra("ReceiveProgress", 0);
final String TimeIn1=getIntent().getStringExtra("ReceiveTimeIn");
final String TimeOut1=getIntent().getStringExtra("ReceiveTimeOut");
// project.setText(Project1);
description.setText(Description1);
seekBar.setProgress(Progress1);
timeIn.setText(TimeIn1);
timeOut.setText(TimeOut1);
seekBar.setProgress(Progress1);
progressText.setText("Covered:" + "" + seekBar.getProgress() + "/" + seekBar.getMax());
}
MyCustomBaseAdapter
public class MyCustomBaseAdapter extends BaseAdapter{ // for ListView in WorkDetailsTable
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public void addNewItem(String P,String D,int Per,String I,String O)
{
SearchResults obj=new SearchResults();
obj.setProject(" Project/Service/Training : "+P);
obj.setDescription(" Work Description : " + D);
obj.setProgress(" Progress : " + Per);
obj.setTimeIn(" Time In : " + I);
obj.setTimeOut(" Time Out : " + O);
searchArrayList.add(obj);
this. notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtProject= (TextView) convertView.findViewById(R.id.ListProject);
holder.txtDescription = (TextView) convertView.findViewById(R.id.ListDescription);
holder.txtProgress = (TextView) convertView.findViewById(R.id.ListProgress);
holder.txtIn=(TextView)convertView.findViewById(R.id.ListTimeIn);
holder.txtOut=(TextView)convertView.findViewById(R.id.ListTimeOut);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtProject.setText(searchArrayList.get(position).getProject());
holder.txtDescription.setText(searchArrayList.get(position).getDescription());
holder.txtProgress.setText(searchArrayList.get(position).getProgress());
holder.txtIn.setText(searchArrayList.get(position).getTimeIn());
holder.txtOut.setText(searchArrayList.get(position).getTimeOut());
return convertView;
}
static class ViewHolder {
TextView txtProject;
TextView txtDescription;
TextView txtProgress;
TextView txtIn;
TextView txtOut;
}
}
Trying Code
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o=listview.getItemAtPosition(position);
SearchResults fullObject=(SearchResults)o;
String ReceiveDescription=((SearchResults) o).getDescription();
Intent i = new Intent(getApplication(), Add_Details_Information.class);
i.putExtra("ReceiveDescription", ReceiveDescription);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}

Try this:
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}

Related

How to get listview items both visible and invisible child values

This loop return only visible position values.However I need the values of child items that are invisible.
for (int i = 0; i < material_issue_list.getCount(); i++) {
View layout = materialIssueAdapter.getViewByPositio(i, material_issue_list);
LinearLayout listItem = (LinearLayout) materialIssueAdapter.getViewByPositio(i, material_issue_list);
String batchSTR = ((AutoCompleteTextView) listItem.findViewById(R.id.batch_AutoComplete)).getText().toString();
String qtySTR = ((EditText) listItem.findViewById(R.id.issue_qty_ETD)).getText().toString();}
My full adapter class,Some one help me suggest to get the correct output.My problem I'm getting null values from the views that are invisible.
Only the visible values are being updated to arraylist.
Thanks in advance.
public class IssueMaterialAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList Dummylist;
private static LayoutInflater inflater = null;
public Resources res;
public static ArrayList<BatchNav> batchNavs_Arr;
static ArrayList<String> batch_Arr;
public static ArrayList<String> batch_data;
public static ArrayList<String> issue_qty;
LinkedHashSet<String> hashSet;
public static ArrayList<BatchModel> batchModels = new ArrayList<BatchModel>();
public static HashMap<ViewHolder, String> batch_map;
public static HashMap<ViewHolder, String> qty_map;
HashMap<String, String> mValues = new HashMap<String, String>();
ArrayList<SaveDataModel> saveDataModels;
public IssueMaterialAdapter(Activity a, ArrayList dummy) {
activity = a;
Dummylist = dummy;
loadBatch();
this.batch_map = new HashMap<>();
inflater = (LayoutInflater) activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (Dummylist.size() <= 0)
return 1;
return Dummylist.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.material_issue_details_list, null);
holder = new ViewHolder();
holder.batch = (AutoCompleteTextView) vi.findViewById(R.id.batch_AutoComplete);
holder.issue = (EditText) vi.findViewById(R.id.issue_qty_ET);
holder.material_descrption = (TextView) vi.findViewById(R.id.material_desc);
holder.unit_issue = (EditText) vi.findViewById(R.id.unit_issue_ET);
holder.matnr = (TextView) vi.findViewById(R.id.matnr);
holder.prdgrp = (TextView) vi.findViewById(R.id.prod_grp);
vi.setTag(holder);
batch_map.put(holder, "");
FilterWithSpaceAdapter<String> farmer_co_no_adapter = new FilterWithSpaceAdapter<String>(activity,
R.layout.custom_items, batch_Arr);
holder.batch.setAdapter(farmer_co_no_adapter);
holder.batch.setThreshold(1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Dummylist.size() == AgriDistributionActivity.get_materials.size()) {
holder.material_descrption.setText(AgriDistributionActivity.get_materials.get(position));
holder.matnr.setText(AgriDistributionActivity.get_matnr.get(position));
holder.prdgrp.setText(AgriDistributionActivity.selected_prdgrp.get(position));
}
try {
if (saveDataArr.size() > 0) {
holder.batch.setText(saveDataArr.get(position).getBatch());
holder.issue.setText(saveDataArr.get(position).getQty());
holder.unit_issue.setText(saveDataArr.get(position).getQty_uom());
}
} catch (Exception e) {
}
return vi;
}
public static class ViewHolder {
public EditText issue, unit_issue;
public AutoCompleteTextView batch;
public TextView material_descrption, matnr,prdgrp;
}
private void loadBatch() {
batch_Arr = new ArrayList<String>();
batchNavs_Arr = new ArrayList<BatchNav>();
hashSet = new LinkedHashSet<>();
BatchNavEntityCollection batchNavEntityCollection = BatchNavEntityCollection.getInstance();
batchNavs_Arr = batchNavEntityCollection.getBatchOutVal();
for (int i = 0; i < batchNavs_Arr.size(); i++) {
String batch = batchNavs_Arr.get(i).getCharg();
batch_Arr.add(batch);
hashSet.addAll(batch_Arr);
batch_Arr.clear();
batch_Arr.addAll(hashSet);
}
}
public View getViewByPositio(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition) {
return listView.getAdapter().getView(position, null, listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
}
You have saveDataArr list which holds all your data.
You can add a getter if you want to do it from an activity , add something like this to your adapter :
private SaveDataModelsendLog(int position) {
return saveDataArr(position);
}
That should do the trick , having said all that you should also look at the difference between static and non-static variables ,
it seems like you have to many of them ,
Enjoy.

Trying to manually add item in a ListView tied to a custom cursor adapter

I need a little help for the redaction of a class. I want to add some item in my listView, and to do that I use a custom adapter found in this forum, but modified for my use :
public class AdvertisingAdapter extends cCursorAdapter {
private static final String ADMOB_PUBLISHER_ID = "YOUR_ADMOB_ID_HERE";
private final Activity activity;
private final cCursorAdapter delegate;
Context context;
static int rec = 15;
public AdvertisingAdapter(Activity activity, cCursorAdapter delegate, Context context, Cursor cursor)
{
super(context, cursor, 0);
this.activity = activity;
this.delegate = delegate;
this.context = context;
delegate.registerDataSetObserver(new DataSetObserver()
{
#Override
public void onChanged()
{
notifyDataSetChanged();
}
#Override
public void onInvalidated()
{
notifyDataSetInvalidated();
}
});
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (position == 0 || position % rec == 0)
{
j = j + 1 ;
if (convertView instanceof AdView)
{
notifyDataSetChanged();
return convertView;
}
else
{
AdView adView = new AdView(context);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Default layout params have to be converted to ListView compatible
// params otherwise there will be a ClassCastException.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params
= new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder().build();
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.setAdSize(com.google.android.gms.ads.AdSize.BANNER);
adView.loadAd(adRequest);
notifyDataSetChanged();
return adView;
}
}
else
{
Log.i ("TEST AD ADAPTER", String.valueOf(j)
+ " " + String.valueOf(position)
+ " " + String.valueOf(getNbreAd())
+ " " + String.valueOf(getNbrePos(position))
+ " " + String.valueOf(getCount()));
return delegate.getView(position - getNbrePos(position), convertView, parent);
}
}
public int getNbreAd(){
int l = delegate.getCount();
return (l / rec) + 1;
}
public int getNbrePos(int position){
int k = (position/rec) + 1;
return k;
}
#Override
public int getCount()
{
return delegate.getCount() + getNbreAd();
}
#Override
public Object getItem(int i)
{
return delegate.getItem(i - 1);
}
#Override
public long getItemId(int i)
{
return delegate.getItemId(i - 1);
}
#Override
public int getViewTypeCount()
{
return delegate.getViewTypeCount() + 1;
}
#Override
public int getItemViewType(int position)
{
return position == 0 ? delegate.getViewTypeCount()
: delegate.getItemViewType(position - 1);
}
#Override
public boolean areAllItemsEnabled()
{
return false;
}
#Override
public boolean isEnabled(int position)
{
return position != 0 && delegate.isEnabled(position - 1);
}
}
My cCursorAdapter :
public class cCursorAdapter extends android.widget.CursorAdapter {
DataHelper mDBHelper;
public cCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_result2, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor){
// Find fields to populate in inflated template
TextView nameResult = (TextView) view.findViewById(R.id.nameResult2);
TextView ageG = (TextView) view.findViewById(R.id.ageG2);
TextView nbreJoueur = (TextView) view.findViewById(R.id.nbreJoueur2);
TextView timeResult = (TextView) view.findViewById(R.id.time2);
ImageView placeGD = (ImageView) view.findViewById(R.id.placeD2);
TextView IDR2 = (TextView) view.findViewById(R.id.IDR2);
// Extract properties from cursor
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String place = cursor.getString(cursor.getColumnIndexOrThrow("place"));
int ageMin = cursor.getInt(cursor.getColumnIndexOrThrow("agemin"));
int ageMax = cursor.getInt(cursor.getColumnIndexOrThrow("agemax"));
int nbreMin = cursor.getInt(cursor.getColumnIndexOrThrow("nbremin"));
int nbreMax = cursor.getInt(cursor.getColumnIndexOrThrow("nbremax"));
int time = cursor.getInt(cursor.getColumnIndexOrThrow("time"));
final int ID = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
// Populate fields with extracted properties
nameResult.setText(name);
ageG.setText(String.valueOf(ageMin) + " - " + String.valueOf(ageMax));
nbreJoueur.setText(String.valueOf(nbreMin) + " - " + String.valueOf(nbreMax));
timeResult.setText(String.valueOf(time));
IDR2.setText(String.valueOf(ID));
if (place.equals("extérieur")) {
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_wb_sunny_black_24dp);
placeGD.setImageDrawable(placeD);
} else if (place.equals("intérieur")){
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_event_seat_black_24dp);
placeGD.setImageDrawable(placeD);
} else if (place.equals("partout")) {
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_explore_black_24dp);
placeGD.setImageDrawable(placeD);
}
//Cacher l'ID (c'est pas joli)
IDR2.setVisibility(View.INVISIBLE);
}
//Override the convert to string sequence
#Override
public CharSequence convertToString(Cursor cursor){
final int colIndex = cursor.getColumnIndexOrThrow("name");
return cursor.getString(colIndex);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint)
{
Cursor currentCursor = null;
if (getFilterQueryProvider() != null)
{
return getFilterQueryProvider().runQuery(constraint);
}
String args = "";
if (constraint != null)
{
args = constraint.toString();
}
//Initialize that shit
mDBHelper = new DataHelper(MainActivity.mContext);
currentCursor = mDBHelper.getNameCursor(args);
return currentCursor;
}
}
In a certain way, it works. But when I swipe the listView too fast, I have this error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.tanoshi.traveler.doctorgamesfree.cCursorAdapter.bindView(cCursorAdapter.java:57)
at android.widget.CursorAdapter.getView(CursorAdapter.java:254)
at com.tanoshi.traveler.doctorgamesfree.AdvertisingAdapter.getView(AdvertisingAdapter.java:102)
I think it is becausemy listView try to load an item in a view which is not loaded.
How can I do to fix this ?
Thank you for your time.

How to take the new values edited in the list to send it to server database.

Here is my adapter code where on edit field edited am calculating the 2 other fields and displaying through TextWatcher. There are 2 issues here.
1. On scroll the values are changing to default values
2. How can I take the new values updated on click of a button
Please help...thanks.
public class ItemListAdapter extends BaseAdapter {
private ArrayList<Itemlist> mProductList,medicineList;
private LayoutInflater mInflater;
String newEditValu[];
Itemlist curProduct;
Itemlist list;
DataTranrfer df;
public ItemListAdapter(ArrayList<Itemlist> list, LayoutInflater inflater) {
mProductList = list;
mInflater = inflater;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewItem item;
final int pos=position;
medicineList=new ArrayList<Itemlist>();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_medicine_list,null);
item = new ViewItem();
item.medicineTitle = (TextView) convertView.findViewById(R.id.tvMedicineName);
item.medcineQuantity =(EditText)convertView.findViewById(R.id.etQuantity);
item.itemDaily=(TextView)convertView.findViewById(R.id.tvDailyText);
item.itemNdays=(TextView)convertView.findViewById(R.id.tvNodays);
item.itemTotal = (TextView)convertView.findViewById(R.id.tvCost);
convertView.setTag(item);
ImageButton b2 = (ImageButton) convertView.findViewById(R.id.thumbnail);
b2.setTag(position);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (int)arg0.getTag();
mProductList.remove(pos);
ItemListAdapter.this.notifyDataSetChanged();
}
});
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
curProduct = mProductList.get(position);
item.ref=position;
item.medicineTitle.setText(curProduct.getmedicineName());
item.itemDaily.setText("Daily: " + curProduct.getMedicineDaily());
item.itemNdays.setText("Days: " + curProduct.medicineNoDays);
item.itemTotal.setText("Rs." + curProduct.getMedicineTotal());
item.medcineQuantity.setText("" + curProduct.getMedicineQuantity());
ItemListAdapter.this.notifyDataSetChanged();
item.medcineQuantity.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//ItemListAdapter.this.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
System.out.print("edit response" + s.toString());
Itemlist curProduct = mProductList.get(position);
if (item.medcineQuantity.getText().length() >= 0) {
double dItemcost = Double.parseDouble(curProduct.getMedicineCost());
double dItemDaily = Double.parseDouble(curProduct.getMedicineDaily());
double dItemQuantity = Double.parseDouble(item.medcineQuantity.getText().toString());
//double dItemQuantity = Double.parseDouble(myList.get(pos));
double dItemDays = (dItemQuantity / dItemDaily);
double dItemTotal = (dItemQuantity * dItemcost);
item.medcineQuantity.setText("" +myList.get(pos));
item.itemNdays.setText("Days: " + dItemDays);
item.itemTotal.setText("Rs." + dItemTotal);
list=new Itemlist();
list.setmedicineName(curProduct.getmedicineName());
list.setMedicineDaily(curProduct.getMedicineDaily());
list.setMedicineQuantity(dItemQuantity);
list.setMedicineCost("" + dItemcost);
list.setMedicineTotal(dItemTotal);
medicineList.add(list);
for(int i=0;i<medicineList.size();i++)
{
System.out.println("medicine list"+medicineList.toString());
System.out.println("medicine total at"+i+":"+medicineList.get(i).getMedicineTotal());
}
}
}
});
return convertView;
}
private class ViewItem {
TextView medicineTitle,itemDaily,itemNdays,itemTotal;
EditText medcineQuantity;
int ref;
}
}

Spinners selection changes on adding new items or scrolling listview android

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);
//...
}

How to get the position of Item on Click in Android

Hello Everyone!!
I am making a sample shopping cart in which i need to get the position of item clicked and get the image displayed on the page on selecting the image from the shopping cart..But here i am getting image of first item only no matter i have clicked another..it is always showing first image of the list...
Here is my code for ProductAdapter.java
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
}}
And Here is my shoppingcart file
public class ShoppingCartActivity extends Activity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(),
true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),
ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
startActivity(productDetailsIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if (mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
double subTotal = 0;
for (Product p : mCartList) {
int quantity = ShoppingCartHelper.getProductQuantity(p);
subTotal += p.price * quantity;
}
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
productPriceTextView.setText("Subtotal: $" + subTotal);
}
}
ProductActivity.java
public class CatalogActivity extends Activity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
Code for ProductDetailsActivity.java
public class ProductDetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productdetails);
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewProductPrice);
productPriceTextView.setText("$" + selectedProduct.price);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
Plz guys Any help will be highly appreciated.
Thanx in advance..
The int position in onItemClick gives the position of the clicked item in the array/list you gave to the adapter.
You can also do getItemAtPosition(); on your listview, if you don't have an easy handle on your original list.
add this code to your Project :
mProductList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
int h = parent.getPositionForView(v);
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected" + h,
Toast.LENGTH_SHORT).show();
}
});
Just geussig that you have a problematic code where you are reading the index value. Following is the sample code for writing and reading int extra:
To put int value:
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
Following code should be used to read this value in another Activity
int index = getIntent().getExtras().getInt(ShoppingCartHelper.PRODUCT_INDEX);
Hope it helps...

Categories

Resources