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();
Related
I have a ListView that is within a Fragment. In the onCreateView section I have set a onItemClickListener for the list, which highlights the selected item in the ListView. I have set two ImageButtons that navigate up and down the list. On selection a new Row is inflated that has its TextView's set to the content of the select item (for the purpose of retaining the highlighted selected state). However I am having difficulty adding that item back to the list. The app will not compile due to the line routines.add(selectedPos-1, str); it wants wants int location, Routine object. I believe the issue is with my construction of my SelectedAdapter class, but I have been unable to determine what to change/pass with regard to the Object.
IE:
public SelectedAdapter(Context context, int textViewResourceId,List objects) {
super(getActivity(), R.layout.listview_routines, routines); }
I would greatly appreciate any input as how to correct this issue; as well as any advice if there is a better way to maintain a selected state. Thanks for your help.
Fragment:
public static class FragmentRoutine extends Fragment {
DatabaseHandler db;
private ListView routineListView;
private List<Routine> routines = new ArrayList<Routine>();
ArrayAdapter<Routine> routineAdapter;
Routine longClickedItemRoutines;
private SelectedAdapter selectedAdapter;
public FragmentRoutine() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.routines,
container, false);
db = new DatabaseHandler(getActivity().getApplicationContext());
routineListView = (ListView) rootView.findViewById(R.id.routineList);
registerForContextMenu(routineListView);
db.closeDB();
if (db.getExerciseCount() != 0)
routines.clear();
routines.addAll(db.getAllRoutines());
populateList();
selectedAdapter = new SelectedAdapter(this.getActivity(), 0, routines);
selectedAdapter.setNotifyOnChange(true);
routineListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemRoutines = routines.get(position);
return false;
}
});
routineListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view,
int position, long id) {
selectedAdapter.setSelectedPosition(position);
}
});
routineListView.post(new Runnable() {
#Override
public void run() {
routineListView.setItemChecked(0, true);
}
});
// move up event handler
ImageButton btnMoveUp = (ImageButton) rootView.findViewById(R.id.btnMoveUp);
btnMoveUp.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveUp();
}
});
// move down event handler
ImageButton btnMoveDown = (ImageButton) rootView.findViewById(R.id.btnMoveDown);
btnMoveDown.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveDown();
}
});
setHasOptionsMenu(true);
return rootView;
}
// Move selected item "up" in the ViewList.
private void moveUp(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos > 0 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
//Problem Line Below
routines.add(selectedPos-1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos-1);
}
}
// Move selected item "down" in the ViewList.
private void moveDown(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos < routines.size()-1 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
routines.add(selectedPos+1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos+1);
}
}
public class SelectedAdapter extends ArrayAdapter<Routine>{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(getActivity(), R.layout.listview_routines, routines);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.selected_row, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
return(v);
}
}
private void populateList() {
routineAdapter = new SaveListAdapterT();
routineListView.setAdapter(routineAdapter);
}
public class SaveListAdapterT extends ArrayAdapter<Routine> {
public SaveListAdapterT() {
super(getActivity(), R.layout.listview_routines, routines);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_routines, parent, false);
Routine currentToDoSave = routines.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(currentToDoSave.getTagName());
return view;
}
}
}
This is my custom list adapter. I want to update the values in table using the update ImageButton in the list. On clicking it, the old values should be shown in a new activity and then the edited value must be stored in the database. However, I am unable to pass an intent inside the onClick() method.
Please suggest me a solution
public class CustomListAdapter extends BaseAdapter implements ListAdapter
{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
OnItemSelectedListener onItemSelectedListener;
public int pos;
String pass,pass2,edit,epass;
public CustomListAdapter(List list, Context context) {
this.list = (ArrayList<String>) list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
//pass2 = list.toString();
return list.get(pos);
}
//#Override
//public Long getItemId(int pos) {
//
// //just return 0 if your list items do not have an Id variable.
//}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_custom_list, null);
}
//Handle TextView and display string from your list
final TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
ImageButton editBtn = (ImageButton)view.findViewById(R.id.edit_btn);
//Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position);
pass = listItemText.getText().toString();
notifyDataSetChanged();
pass2 = pass.substring(0,pass.indexOf(' '));
System.out.println(pass2);
Moneydb.delete(pass2);
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
edit=listItemText.getText().toString();
epass = listItemText.getText().toString();
edit = epass.substring(0,epass.indexOf(' '));
Moneydb.edit(edit);
}
});
return view;
}
protected Context getContext() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return list.get(position).getId();
return 0;
}
public void clear() {
//CustomListAdapter collection = null;
// TODO Auto-generated method stub
list.clear();
notifyDataSetChanged();
}
I suggest you to assign and ContextMenu to your list view with two MenuItem, Edit and Delete and write associated code outside of adapter
or you can start Activity by :
Intent new_intent = new Intent(v.getRootView().getContext(),edit_activity.class);
new_intent.putExtra("Key","Value");
v.getRootView().getContext().startActivity(new_intent);
i think the first method is best ;)
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;
}
}
whenever user do tap on list item row i am trying to show dialog, but getting nothing whenever i do click on list item row, why?
Here I just want to update value of total by accepting new qty from user in dialog via show that value in place of quantity in a List row ....
CartActivity.java:
public class CartActivity extends Activity {
ListView mLstView1;
CartAdapter mViewCartAdpt;
final private static int DIALOG_QUANTITY = 1;
EditText update_quantity ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
mLstView1 = (ListView) findViewById(R.id.listView1);
mViewCartAdpt = new CartAdapter(CartActivity.this);
mLstView1.setAdapter(mViewCartAdpt);
mLstView1.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("deprecation")
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id)
{
showDialog(DIALOG_QUANTITY);
}
});
}
protected Dialog onCreateDialog(int id) {
AlertDialog dialogDetails = null;
switch (id) {
case DIALOG_QUANTITY:
LayoutInflater inflater = LayoutInflater.from(this);
View dialogview = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
dialogbuilder.setTitle("Image Information");
dialogbuilder.setView(dialogview);
dialogDetails = dialogbuilder.create();
break;
}
return dialogDetails;
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_QUANTITY:
final AlertDialog alertDialog = (AlertDialog) dialog;
Button updateQuantityButton = (Button) alertDialog
.findViewById(R.id.btn_login);
Button cancelbutton = (Button) alertDialog
.findViewById(R.id.btn_cancel);
update_quantity = (EditText) alertDialog
.findViewById(R.id.edit_new_qty);
updateQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
cancelbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
break;
}
}
// Called when the activity begins interacting with the user
#Override
protected void onResume(){
super.onResume();
mViewCartAdpt.notifyDataSetChanged();
}
}
CartAdapter.java:
public class CartAdapter extends BaseAdapter {
public static final String LOG_TAG = "CartAdapter";
public static final String KEY_TITLE = "title";
public static final String KEY_COST = "cost";
public static final String KEY_QTY = "qty";
public static final String KEY_TOTAL = "total";
Activity activity;
LayoutInflater inflater;
ImageButton mImgBtnDelete;
ListView listView;
private double itemamount = 0;
private int itemquantity = 0;
public CartAdapter(Activity a) {
// TODO Auto-generated constructor stub
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return Constants.sItem_Detail.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listrow_cart, null); // listrow_cart
vi.setClickable(true);
vi.setFocusable(true);
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
}
});
final TextView title = (TextView) vi.findViewById(R.id.title);
final TextView qty = (TextView) vi.findViewById(R.id.qty);
final TextView cost = (TextView) vi.findViewById(R.id.cost);
final TextView total = (TextView) vi.findViewById(R.id.total);
HashMap<String, String> item = new HashMap<String, String>();
item = Constants.sItem_Detail.get(position);
// Setting all values in listview
title.setText(item.get(com.example.sample.ItemsActivity.KEY_TITLE));
cost.setText(item.get(com.example.sample.ItemsActivity.KEY_COST));
qty.setText("1");
itemquantity = Integer.parseInt(qty.getText().toString());
itemamount = Double.parseDouble(cost.getText().toString());
total.setText(new DecimalFormat("##.#").format(itemamount*itemquantity));
return vi;
}
}
Take your Dialog inside your activity, where you have to do code for listiview click, inside click show your dialog,
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
//show dialog.
}
});
I can see, your dialog having two buttons and one editbox, and whatever values is to be input in editbox, you updating your list value with editbox value.
Grab editbox value and update your list array, which you are setting on adapter to fill your listview.
updateQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// here you have to fetch editbox value and update your arraylist and then notify your adapter.
}
});
I believe this is because onCreateDialog() and onPrepareDialog() should be overriden in an activity, not in the adapter.
Since you declared activity to be of type Activity, calling activity.showDialog() won't have any effect.
What you have to do, is to move those methods in the activity you want the dialogs to be displayed, then pass to the CardAdapter and instance of your activity and use it in the adapter.
new CardAdapter(MyActivity.this);
//...
public class CardAdapter .... {
public MyActivity activity;
//.......
activity.showDialog
}
Though, I would suggest to use DialogFragment instead.
you can use this way when click on item of the list view then open the dialog box and whatever changes or update in list then use setNotifyDataChanged() before set the adapter on list view
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
yourActivty.this.showDialog(DIALOG_QUANTITY);
}
});
Edit: My issue seems like BaseAdapter just wont post more than 1 Spinner. If I change the array's size to 0, it wont put anything, but anything more than 1 is truncating it. It never passes position 0 from getView() and it never shwows anymore than 1. I have been at it for hours. Is there a reason for this?
I am having an issue with adding Spinners dynamically in a ListView using a BaseAdapter. I tried it before as a test to make sure it could be done correctly in a test class, and it iterates the positions correctly. But now I am doing it again and its failing. What I mean by failing is instead of getView() creating the new Spinner, it never leaves position 0. It still runs. Just never adds more Spinners.
This is my code:
Main Adapter code
public class RemindersAdapter extends BaseAdapter{
Spinner[] shownReminders = new Spinner[1];
TextView[] removeReminders = new TextView[1];
String[] reminders = new String[1]; //this hlds the values of the coresponding spinner
RemindersAdapter mAdapter;
#Override
public int getCount() {
return shownReminders.length;
}
#Override
public Object getItem(int position) {
return shownReminders[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
Log.d("TAG", "A NEW SPINNER AND TEXTVIEW IS CREATED HERE WITH POSITION"+position);
if(view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.reminder_spinner, parent, false);
}
Spinner reminderSpinner = (Spinner)view.findViewById(R.id.reminder_spinner);
reminderSpinner.setTag(String.valueOf(position));
ArrayAdapter<CharSequence> reminderAdapter = ArrayAdapter.createFromResource(
parent.getContext(), R.array.reminders_array, android.R.layout.simple_spinner_item);
reminderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
reminderSpinner.setAdapter(reminderAdapter);
reminderSpinner.setOnItemSelectedListener(new MyOnReminderSelectedListener());
shownReminders[position] = reminderSpinner;
TextView remove = (TextView)view.findViewById(R.id.remove_reminder);
remove.setTag(String.valueOf(position));
removeReminders[position] = remove;
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("The Array positioning of this remove view is: ", ""+v.getTag());
}
});
return view;
}
public void addReminder() {
Log.d("addReminder METHOD", "The Add Reminder method is running");
Spinner[] temp = new Spinner[shownReminders.length+1];
TextView[] temp2 = new TextView[removeReminders.length+1];
String [] temp3 = new String[reminders.length+1];
for(int i = 0; i < shownReminders.length; i++) {
temp[i] = shownReminders[i];
temp2[i] = removeReminders[i];
temp3[i] = reminders[i];
}
shownReminders = temp;
removeReminders = temp2;
reminders = temp3;
mAdapter.notifyDataSetChanged();//this just makes the adapter refresh itself
}
public void giveYourself(RemindersAdapter adapter) {
mAdapter = adapter;
}
public class MyOnReminderSelectedListener implements OnItemSelectedListener{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
int position = Integer.parseInt(parent.getTag().toString()); //gets the position of the Spinner and puts it in the same index in the reminders array
reminders[position] = parent.getItemAtPosition(pos).toString();
for(int i =0; i < reminders.length; i++) Toast.makeText(parent.getContext(), i+": "+reminders[i], Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing for now
}
}//end of MyOnReminderSelectedListener innerclass
}//end of Class
What runs in the Activity
reminderList = (ListView)findViewById(R.id.reminders_list);
reminderAdapter = new RemindersAdapter();
reminderAdapter.giveYourself(reminderAdapter);
reminderList.setAdapter(reminderAdapter);
TextView addReminder = (TextView)findViewById(R.id.add_reminder);
addReminder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG", "The onClick is running !");
reminderAdapter.addReminder();
}
});
I am at a loss because my code looks exactly like my test code, with some modifications in order for it to work with my app. But the information used by the Adapter is pretty much the same. I am going to post the test code as well so you guys can see the code that works.
Test Code
public class RemindersAdapter extends BaseAdapter{
Spinner[] shownReminders = new Spinner[1];
ArrayList<TextView> removeSpinner = new ArrayList<TextView>();
Context mContext;
public RemindersAdapter(Context context) {
mContext = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return shownReminders.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return shownReminders[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
Log.d("TAG", "Number of times this is running"+position);
Log.d("TAG", "Address of the Spinner Object"+shownReminders[position]);
if(view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.reminder_spinner, parent, false);
}
Spinner reminderSpinner = (Spinner)view.findViewById(R.id.reminders_spinner);
reminderSpinner.setTag("1");
ArrayAdapter<CharSequence> reminderAdapter = ArrayAdapter.createFromResource(
parent.getContext(), R.array.reminders_array, android.R.layout.simple_spinner_item);
reminderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
reminderSpinner.setAdapter(reminderAdapter);
reminderSpinner.setOnItemSelectedListener(new MyOnReminderSelectedListener());
shownReminders[position] = reminderSpinner;
TextView remove = (TextView)view.findViewById(R.id.remove_reminder);
remove.setTag(position);
removeSpinner.add(remove);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = Integer.parseInt(v.getTag().toString());
removeSpinner.remove(pos);
Spinner[] temp = new Spinner[shownReminders.length-1];
for(int i =0; i < shownReminders.length; i++) {
if(i == pos || i > pos) {
temp[i-1] = shownReminders[i];
} else {
temp[i] = shownReminders[i];
}
}
//Here i should refresh somewhow
}
});
return view;
}
public void addReminder() {
Spinner[] temp = new Spinner[shownReminders.length+1];
for(int i = 0; i < shownReminders.length; i++) {
temp[i] = shownReminders[i];
}
shownReminders = temp;
}
/*
* Listener for when the reminder spinner gets a value the user entered
* */
public class MyOnReminderSelectedListener implements OnItemSelectedListener{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
//does nothing for now
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing for now
}
}//end of MyOnReminderSelectedListener innerclass
I also have a question as to why the Adapter runs itself so much. For examples, using the Log, I noticed it calls getView() twice for no apparent reason. Its weird that it has this behavior. I guess I don't understand BaseAdapter so well.
This error will happen if you put a ListView inside a ScrollView. ListView itself does vertical scroll so it must not be put into a ScrollView.
An adapter will call getView when listView needs a new item to show. So, if your listView has no scroll, no new item will be created, and no call to getView will be made.
But you should not store all spinner objects, or create new objects in getView. That`s because it will be slow and maybe waste of memory.