Update the Value of the ListView Item In Android - android

I have a Listview that is showing a list .So on the click of the listview i have a customDialog.In that i am taking some values from the user.So want once the user enters the details and click on the ok button ,then i have to update the value of that item from the listview and when all the item of the listview has been updated then compare it with the previous value to check whether all the item are updated or not .Help me on this how could i do this
Activity Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_iween_booking_page);
intent = getIntent();
isReturn = (Boolean) intent.getExtras().get("isReturn");
searchParam = (HashMap<String,String>) intent.getExtras().get("searchParam");
listView = (ListView) findViewById(R.id.passengerList);
emailId = (TextView)findViewById(R.id.emailid);
continuebooking = (ImageView)findViewById(R.id.continuebooking);
firstName= (EditText)findViewById(R.id.firstName);
lastName =(EditText)findViewById(R.id.LastName);
mobileNumber =(EditText)findViewById(R.id.mobileNumber);
setTittle();
if(searchParam.get("NoOfChild").equals("0") && searchParam.get("NoOfInfant").equals("0")&& searchParam.get("NoOfAdult").equals("1")){
} else {
passengerList = getPassengerList(passengerInfo);
showPassengerListView(passengerList);
}
continuebooking.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(searchParam.get("NoOfChild").equals("0") && searchParam.get("NoOfInfant").equals("0") && searchParam.get("NoOfAdult").equals("1")){
if(firstName.getText().toString().trim().equalsIgnoreCase("")){
firstName.setError("Enter FirstName");
}
if(lastName.getText().toString().trim().equalsIgnoreCase("")){
lastName.setError("Enter LastName");
}
if(mobileNumber.getText().toString().trim().equalsIgnoreCase("")){
mobileNumber.setError("Enter Mobile No.");
}
}else{
int count = listView.getAdapter().getCount();
listData = new String[count];
for (int i = 0; i < count; i++) {
listData[i] = listView.getAdapter().getItem(i).toString();
}
for(int i=0;i<listView.getAdapter().getCount();i++){
for(int j=0;j<count;j++){
if(listData[j]==listView.getAdapter().getItem(i).toString()){
Log.d("listData data", listView.getAdapter().getItem(i).toString());
// View v=listView.getChildAt(i);
// TextView tv=(TextView) v.findViewById(android.R.id.text1);
// tv.setError("Please change the data");
}
}
}
}
}
});
}
private void showPassengerListView(final String[] passengerList) {
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, passengerList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// int itemPosition = position;
// String itemValue = (String) listView.getItemAtPosition(position);
View v=listView.getChildAt(position);
TextView tv=(TextView) v.findViewById(android.R.id.text1);
tv.setError(null);
passengerInformationPopup(passengerList,position);
}
});
}
public void passengerInformationPopup(final String[] passengerList, final int position) {
final Dialog dialog= new Dialog(Test.this,R.style.Dialog_Fullscreen);
dialog.setContentView(R.layout.passenger_details_dialog);
final EditText firstNameDialog;
final EditText lastNameDialog;
ImageView continueBooking;
dateofBirth = (TextView)dialog.findViewById(R.id.dateofBirth);
firstNameDialog = (EditText)dialog.findViewById(R.id.firstName);
lastNameDialog =(EditText)dialog.findViewById(R.id.LastName);
continueBooking =(ImageView)dialog.findViewById(R.id.continuebooking);
if((passengerList[position].contains("Child"))|| (passengerList[position].contains("Infant"))){
dateofBirth.setVisibility(View.VISIBLE);
}else{
dateofBirth.setVisibility(View.GONE);
}
dateofBirth.setClickable(true);
dialog.show();
continueBooking.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
isSuccess= true;
if(firstNameDialog.getText().toString().trim().equalsIgnoreCase("")){
firstNameDialog.setError("Enter FirstName");
isSuccess= false;
}
if(lastNameDialog.getText().toString().trim().equalsIgnoreCase("")){
lastNameDialog.setError("Enter LastName");
isSuccess= false;
}
if((passengerList[position].contains("Child"))|| (passengerList[position].contains("Infant"))){
if(dateofBirth.getText().toString().trim().equalsIgnoreCase("")){
dateofBirth.setError("Date of Birth Can't be blank");
isSuccess= false;
}
}
if(isSuccess){
dialog.cancel();
View v=listView.getChildAt(position);
TextView tv= (TextView) v.findViewById(android.R.id.text1);
tv.setText(firstNameDialog.getText().toString().trim().toString()+" "+lastNameDialog.getText().toString().trim().toString());
}
}
});
}
passengerInformationPopup function i have to update the items values of the ListView .In on create continueBooking i have to check whether all the items are updated or not
Before Updation
After Updation

Never update ListView items directly. Update data in your storage and call notifyDataSetChanged on your adapter.

You will need an ArrayAdapter with the data for your list. Then when you manipulate the data in that array you can call .notifyDataSetChanged(); on the adabter to refresh your view.
Be aware that it have to be the same arraylist! so you cant call arraylist = new ArrayList(); that will destroy the reference. Instead use arraylist.clear(); and then arraylist.addAll(data);
Here is an example:
public class GroupsListAdapter extends ArrayAdapter<Object> {
/**
* Constructor
*
* #param context
* Context
* #param objects
* Array of objects to show in the list.
*/
public GroupsListAdapter(Context context, ArrayList<Object> objects) {
super(context, R.layout.row, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Object = getItem(position);
/* Initialize strings */
String nameText = group.getName();
boolean upToDate = group.isUpToDate();
/* Get the layout for the list rows */
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row, parent, false);
}
rowView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//do stuff here
}
});
return rowView;
}
}

Related

ListView click show/hide all check box

I am having a listview and it has one checkbox and two textfields , i would like to change check box visibility properties from listview on click funtion, i am able to change the properties from inside the getView funtion but i want it from listview click. Help me find a solution
public class HelpList extends Fragment {
amfFunctions amf;
MyCustomAdapter dataAdapter = null;
Database_Contact contact = new Database_Contact();
DBHelper mydb = new DBHelper(getActivity());
public static final int PICK_CONTACT = 1;
public String user_phone_number;
public String buddyName;
public String buddyNum;
LayoutInflater vi;
View v ;
Fragment fragment = null;
Button myAddButton,myDelButton;
int selected = 0;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayList<Database_Contact> selectedList = new ArrayList<>();
Database_Contact addcontacts = new Database_Contact();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_helplist, container, false);
// Inflate the layout for this fragment
displayListView();
cd = new ConnectionDetector(getActivity());
myDelButton = (Button)v. findViewById(R.id.deleteContact);
myDelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DeleteContact();
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_SHORT).show();
}
}
});
Constants.i = 0;
myAddButton = (Button)v. findViewById(R.id.Addanother);
myAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
Log.e("Myaddbutton text ", (String) myAddButton.getText());
if (isInternetPresent) {
if (myAddButton.getText().equals("Close")){
Toast.makeText(getActivity(),
getString(R.string.click_to_close), Toast.LENGTH_SHORT).show();
}
else{
AddContact();
}
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_LONG).show();
}
}
});
return v;
}
private void displayListView() {
mydb = new DBHelper(getActivity());
ArrayList<Database_Contact> contactlist = (ArrayList<Database_Contact>)
mydb.getAllDatabase_Contacts();
Collections.sort(contactlist, new Comparator<Database_Contact>() {
#Override
public int compare(Database_Contact lhs, Database_Contact rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.activity_allcontactlist, contactlist);
ListView listView = (ListView)v.findViewById(R.id.helplistview);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact)
parent.getItemAtPosition(position);
contact.isSelected();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Database_Contact> {
private ArrayList<Database_Contact> contactlist;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Database_Contact> contactlist) {
super(context, textViewResourceId, contactlist);
this.contactlist = new ArrayList<Database_Contact>();
this.contactlist.addAll(contactlist);
}
private class ViewHolder {
TextView code;
TextView Number;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_allcontactlist,
null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.helplist_name);
holder.Number = (TextView)
convertView.findViewById(R.id.helplist_num);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkbox_all);
convertView.setTag(holder);
final ViewHolder finalHolder = holder;
final ViewHolder finalHolder1 = holder;
holder.code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.Number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Database_Contact contact = (Database_Contact)
cb.getTag();
contact.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Database_Contact contact = contactlist.get(position);
holder.code.setText(contact.getName());
holder.Number.setText(contact.getPhoneNumber());
holder.name.setText("");
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
}
As I could not find any perfect solution i tried it in a different manner alough its a bit diffenrt from what i wanted i.e on click i used my displayListView() funtion and got the work done
ischeckboxVisible = true;
Runnable run = new Runnable() {
#Override
public void run() {
displayListView();
}
};
getActivity().runOnUiThread(run);
and coming to getView i have used:
if (!ischeckboxVisible)
{
holder.name.setVisibility(View.GONE);
}
if (ischeckboxVisible)
{
holder.name.setVisibility(View.VISIBLE);
}
so every time i do the click it changes the ischeckboxVisible to either true or false and initializes the displatListview() and it works.
I have had help from here Android hide and show checkboxes in custome listview on button click
Hope this might come in handy for some one out there.
Please check below code if it helps you,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact) contactlist.get(position);
contact.setSelected(!contact.isSelected());
if(contact.isSelected())
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.VISIBLE);
}
else
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.GONE);
}
}
});

how to update the text on click of listview items in adapter

enter image description hereI want that if user clicks + and - button then action performed to that particular list item in listview. In my program when I clicked first item's button then value increment and decrement also but when another items button clicked that time it consider previous items value and incerement and decrement action performed on that value .I want that each item perform their seperately. I don't know how to implement this.
Here my code:
public static class ViewHolder {
TextView tv_qty;
}
public class ProductAdapter extends ArrayAdapter<Product> {
ImageLoader imageLoader;
public ProductAdapter(Context context, int resource) {
super(context, resource);
imageLoader = new ImageLoader(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Product product = getItem(position);
// Product product=ge
View view;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(R.layout.product_row, null);
} else {
view = convertView;
}
final ViewHolder viewHolder = new ViewHolder();
tv_row_product_name = (TextView) view.findViewById(R.id.pname);
tv_row_product_rate = (TextView) view.findViewById(R.id.price);
tv_row_product_qty = (TextView) view.findViewById(R.id.productqty);
viewHolder. tv_qty = (TextView) view.findViewById(R.id.userqty);
tv_value = (TextView) findViewById(R.id.textView_value);
tv_totalprice = (TextView) findViewById(R.id.textview_totalprice);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
Log.d(Config.tag, "url : " + "uploads/product/" + product.image1);
Picasso.with(ListViewProduct.this)
.load("http://www.sureshkirana.com/uploads/product/" + product.image1)
.into(imageView);
imgbtnp = (ImageButton) view.findViewById(R.id.imageButton2);
imgbtnm = (ImageButton) view.findViewById(R.id.imageButton);
imgbtnp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count++;
viewHolder. tv_qty.setText(String.valueOf(count));
notifyDataSetChanged();
}
});
imgbtnm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (count > 0)
count--;
viewHolder.tv_qty.setText(String.valueOf(count));
notifyDataSetChanged();
}
});
view.setTag(viewHolder);
tv_row_product_name[enter image description here][1].setText(product.productTitle);
tv_row_product_rate.setText("Rs. " + product.productPrice + "/-");
tv_row_product_qty.setText(product.quantity + "kg");
tv_totalprice.setText("Rs." + product.product_amount);
return view;
}
}
}
You cannot use a single variable for this purpose. Set the count as tag to your list item viewHolder.tv_qty.setTag(count);
and retrieve the value like viewHolder.tv_qty.getTag();.
on clicking on the + or - sign get the position of the clicked item in getView and get the product object at that position and modify with the new values and again put the modified object inside same list at same position and call notifyDatasetChanged() . Hope it helps.
Using Interface you can solve this problem. You need to update your object and then refresh you list adapter using notifyDataSetChanged().
Custom Adapter
public interface QuantityClickListener {
void onIncrementClickListner(int position);
void onDecrementClickListner(int position);
}
/*
* (non-Javadoc)
*
* #see android.widget.ArrayAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ListViewWrapper wrapper = null;
LayoutInflater inflater = LayoutInflater.from(mContext);
if (null == convertView) {
convertView = inflater.inflate(R.layout.custom_list_item, null);
wrapper = new ListViewWrapper(convertView);
convertView.setTag(wrapper);
} else {
wrapper = (ListViewWrapper) convertView.getTag();
}
// Schedule schedule = objects.get(position);
Products product = mProducts.get(position);
if (null != product) {
wrapper.getTxtQuantity().setText("" + product.quantity);
wrapper.getNegativeBtn().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
quantityClickListener.onDecrementClickListner(position);
}
});
wrapper.getPositiveBtn().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
quantityClickListener.onIncrementClickListner(position);
}
});
}
return convertView;
}
Activity
/**
* Initialize UI elements
*/
private void initialize() {
listView = (ListView) findViewById(R.id.listview);
dummyData();
adapters = new CustomAdapters(this, 0, products);
adapters.setQuantityClickListener(quantityClickListener);
listView.setAdapter(adapters);
}
private QuantityClickListener quantityClickListener = new QuantityClickListener() {
#Override
public void onIncrementClickListner(int position) {
if (null != products && products.size() > 0) {
Products product = products.get(position);
product.quantity++;
product.totalPrice = product.quantity * product.price;
adapters.notifyDataSetChanged();
}
}
#Override
public void onDecrementClickListner(int position) {
if (null != products && products.size() > 0) {
Products product = products.get(position);
if (product.quantity > 0) {
product.quantity--;
product.totalPrice = product.quantity * product.price;
adapters.notifyDataSetChanged();
}
}
}
};

Footer button in listview, how to get value from custom list adapter

I have a listview with switch button in each row. I store sum of checked switches in variable. In MainActivity where I start custom adapter I want to get a sum of checked switches. So how to pass value from custom adapter to parent activity? In the footer of listview I have a button "Dalej" I've create it in MainActivity, and want to get value (this sum) from adapter when user click on it?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardio);
String[] cardio_1 = getResources().getStringArray(R.array.cardio_1);
ListView listView = (ListView) findViewById(R.id.listView);
View footer = getLayoutInflater().inflate(R.layout.cardio_footer, null);
listView.addFooterView(footer);
ListAdapter listAdapter = new Adapter_cardio(this, cardio_1);
cardio.addAll(Arrays.asList(cardio_1))
listView.setAdapter(listAdapter);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
});
Adapter
public Adapter_cardio(Context context, String[] cardios ) {
super(context, R.layout.cardio_row, cardios);
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("TAG", "tessst1");
zaznaczone = new ArrayList();
}
public String suma(String sum) {
return sum;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
String pytanie = getItem(position);
if (convertView==null){
convertView = inflater.inflate(R.layout.cardio_row, null);
holder = new ViewHolder();
holder.question = (TextView) convertView.findViewById(R.id.question);
holder.s = (Switch)convertView.findViewById(R.id.switch1);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.question.setText(pytanie);
//Model_cardio question = getItem(position);
//final boolean doCheck = (position == 4) || (position == 5);
holder.s.setTag(position);
holder.s.setOnCheckedChangeListener(null);
if (zaznaczone.contains(position) )
{
holder.s.setChecked(true);
}
else
{
holder.s.setChecked(false);
}
holder.s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
zaznaczone.add((Integer) buttonView.getTag());
} else {
zaznaczone.remove((Integer) buttonView.getTag());
}
}
});
sum = zaznaczone.size();
String x = "2";
Log.d("TAG_Switch_all", "suma = " + sum);
return convertView;
}
want to get value (this sum) from adapter when user click on it?
Create a method as public which return sum from Adapter_cardio class as:
public int getSum(){
return zaznaczone.size();
}
and call getSum method on Button click using listAdapter object as:
public void onClick(View v) {
Log.d("TAG_Switch_all", "suma = " + ((Adapter_cardio)listAdapter).getSum());
}
if listAdapter not accessible inside onClick method then declare it as final

Update Listview item and get values using BaseAdapter Android

I have a listview of that have multiple items.I want to update the items value on click of button and want to get the the values of all the items on click of the button.But i am unable to do that.Please help me to get this functionality
Activity code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_ItemValue);
setContentView(R.layout.activity_iween_booking_page);
listView = (ListView) findViewById(R.id.passengerList);
showPassengerListView(passengerList);
}
getValue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(){
}else{
//Here i have to get all the value of the listview items in a array
}
}
});
}
private void showPassengerListView(final String[] passengerList) {
listView.setAdapter(new PassengerListUpdate(passengerList));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public void passengerInformationPopup(final String[] passengerList, final int position) {
final Dialog dialog= new Dialog(MainActivity.this,R.style.Dialog_Fullscreen);
dialog.setContentView(R.layout.passenger_details_dialog);
dialog.show();
setValueDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
isSuccess= true;
if(isSuccess){
dialog.cancel();
//Here i Have to Update the item at position with some value
}
}
});
}
public void goBack(View v) {
finish();
}
class PassengerListUpdate extends BaseAdapter {
String[] ItemValue;
public PassengerListUpdate(String[] text) {
ItemValue = text;
}
public int getCount() {
// TODO Auto-generated method stub
return ItemValue.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View vi;
vi = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
TextView ItemValue;
ItemValue = (TextView) vi.findViewById(android.R.id.text1);
ItemValue.setText(ItemValue[position]);
return (vi);
}
}
Please help me to how to set a items value and how to get the listview values
[Want] to get the the values of all the items on click of the button
To get all values, create a method getAllValues() inside PassengerListUpdate:
public String[] getAllValues() {
return ItemValue;
}
Declare your adapter globally:
PassengerListUpdate myAdapter;
Initialize it in showPassengerListView(String[]):
myAdapter = new PassengerListUpdate(passengerList);
listView.setAdapter(myAdapter);
To get the list of all values on button click:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (myAdapter != null) {
String[] allValues = myAdapter.getAllValues();
}
}
});
I want to update the items value on click of button
To update the values, you can simply reinitialize and set myAdapter:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myAdapter = new PassengerListUpdate(updatedPassengerList);
listView.setAdapter(myAdapter);
}
});
First, in order to get whole the values inside ListView. You can get number of item in adapter, and then get value one by one by its position.
ArrayList<String> results = new ArrayList<String>();
final int count = mMyAdapter.getCount();
for( int i = 0; i < count; ++i ){
String item = mMyAdapter.getItem(i);
results.add(item);
}
return results;
Second, in order to add or update the value of ListView, in general extending ArrayAdapter is much easier than implementing BaseAdapter, because of ArrayAdapter support add / remove / insert method by itself. For example,
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context) {
super(context, 0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View vi;
vi = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
TextView ItemValue;
ItemValue = (TextView) vi.findViewById(android.R.id.text1);
ItemValue.setText(ItemValue[position]);
return (vi);
}
}
And you can updating adapter's value quiet directly,
mMyAdapter.add("Add Item");
mMyAdapter.remove("Remove Item");
mMyAdapter.insert("Insert Item", 0);
After finishing the jobs, you can call adapter's notifyDatSetChanged() method in order to update the UI, and I think this is more efficient way than setting up the new adapter every time whenever data is updated.
mMyAdapter.notifyDataSetChanged();

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