Why is my BaseAdapter class not incrementing the position in getView? - android

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.

Related

Listview postion not working properly

I have list view. I want to change color of clicked row. But only 0,1 and 2 indexes are correctly colored others are not working properly likewise if i clicked on 4th row the 5th one row color changes and sometimes if i clicked on 7th row then none of row is colored. Please Help
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,final int position, long id) {
for (int i = 0; i < lv.getChildCount(); i++) {
if(position == i ){
lv.getChildAt(i).setBackgroundColor(Color.BLUE);
}else{
lv.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
}
public abstract class CustomAdapter extends BaseAdapter implements SeekBar.OnSeekBarChangeListener {
Context context;
ArrayList<HashMap<String, String>> countryList;
ArrayList<HashMap<String, String>> mStringFilterList;
LayoutInflater inflter;
public ImageView img2,img3;
Handler mHandler = new Handler();
SeekBar songProgressBar;
SelfUpdatingSeekbar self;
public boolean isStarted = true;
public static final int UPDATE_FREQUENCY = 500;
public static final int STEP_VALUE = 4000;
public final Handler handler = new Handler();
public final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
public CustomAdapter(Context applicationContext, ArrayList<HashMap<String, String>> countryList) {
this.context = applicationContext;
this.countryList = countryList;
mStringFilterList = countryList;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return countryList.size();
}
public void updateData(ArrayList<HashMap<String, String>> countryList) {
this.countryList = countryList;
notifyDataSetChanged();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.list_itemss, null);
view.setTag(position);
String hello = String.valueOf(countryList.get(position));
String s = hello;
int s1 = s.lastIndexOf("=");
int s2 = s.lastIndexOf("}");
strSub = s.substring(s1+1,s2/*s.lastIndexOf("=")*/);
Log.d("Hello",hello);
String henno1 = String.valueOf(hello.length());
Log.d("hellya",strSub);
TextView country = (TextView) view.findViewById(R.id.textView);
country.setText(strSub);
uniqueItemIdCount = countryList.size();
Log.d("PrintIdss", String.valueOf(uniqueItemIdCount));
ImageView twitt = (ImageView)view.findViewById(R.id.button5);
twitt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TweetComposer.Builder builder = new TweetComposer.Builder(context)
.text(strSub);
builder.show();
}
});
ImageView fb = (ImageView)view.findViewById(R.id.button6);
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle(strSub)
.setContentDescription(
"Top Hollywood Songs")
.setContentUrl(Uri.parse("http://www.moremovies.com/"))
.build();
shareDialog.show(linkContent);
}
});
songProgressBar = (SeekBar) view.findViewById(R.id.songProgressBar);
songProgressBar.setOnSeekBarChangeListener(this);
songCurrentDurationLabel = (TextView)view.findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView)view.findViewById(R.id.songTotalDurationLabel);
img2 = (ImageView)view.findViewById(R.id.button3);
img2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int songIndex = position;
String hellos = String.valueOf(countryList.get(songIndex));
int s1 = hellos.lastIndexOf("=");
int s2 = hellos.lastIndexOf("}");
String strSubs = hellos.substring(s1+1,s2/*s.lastIndexOf("=")*/);
selelctedFile.setText(strSubs);
currentSongIndex=songIndex;
playSong(currentSongIndex);
}
});
}
You have to manage the position and the background of yourself because in your adapter as you are reusing the cell. Kindly check your adapter you will get it.
And to achieve what you want. You have to update your adapter and implement the click listener in the Adapter view.
Try to subtract the position of your listview:
for (int i = 0; i < lv.getChildCount(); i++) {
if(position - lv.getFirstVisiblePosition() == i ){ //<-Here
lv.getChildAt(i).setBackgroundColor(Color.BLUE);
}else{
lv.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
}
You need to implement the two background options, because the adapter will reuse your layout.
So you need to keep track of the selected items (not layouts), as i see you are using a HashMap to populate your adapter so, create a List with the selected positions and when you are populating your adapter do something like :
//Globals Variables
List<int> SelectedList = new ArrayList<>();
//On select event
SelectedList.add(position);
//On deselect event
SelectedList.remove(position);
//On get view
if(SelectedList.contains(position){
// Background selected
}else{
// Explicit set the background to the default
}
If you want to start with play buttons and on click change to pause the one clicked and all others back to play then inside your adapter where you initialize the play/pause button do :
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,final int position, long id) {
for (int i = 0; i < lv.getChildCount(); i++) {
Button PlayPause = v.findViewById(R.id.play_pause_button)
ButtonPlayPause.setImageResource("play resource")
}
playPause.setImageResource("pause resource")
}
}
}
});
Code may have some syntax errors but you get the idea.

Delete an item from Array List contact to Custom List View always delteing the latest one

I have a custom list view, contains delete button and spinner (the spinner contain A-E characters).
And I have an issue with deleting the true row from my custom list view.
Custom list view code:
public class customListView extends BaseAdapter
{
public Activity context;
ArrayList<MyActivity.UserProperties> userPropertieses;
public String[] spinnerValues;
public LayoutInflater inflater;
public customListView(Activity context, ArrayList<MyActivity.UserProperties> userPropertieses, String[] spinnerArray)
{
super();
this.context = context;
this.userPropertieses = userPropertieses;
spinnerValues = spinnerArray;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() { return userPropertieses.size(); }
#Override
public Object getItem(int i) { return null; }
#Override
public long getItemId(int i) { return 0; }
class ViewHolder
{
Button btnRemove;
Spinner spinner;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup)
{
final ViewHolder holder;
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.custom_layout, null);
holder.spinner = (Spinner) view.findViewById(R.id.spinner);
holder.btnRemove = (Button) view.findViewById(R.id.bu_Remove);
// populate spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(view.getContext(), android.R.layout.simple_spinner_item, spinnerValues);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setFocusable(true);
holder.spinner.requestFocus();
holder.spinner.setAdapter(dataAdapter);
view.setTag(holder);
// remove user implementation
holder.btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("custom list view debug", "i = " + i); // debug. verify i value is correct
((MyActivity) context).deleteUser(i);
}
});
}
else
holder = (ViewHolder) view.getTag();
return view;
}
}
And my main activity code looks like this:
public class MyActivity extends Activity
{
ListView listView;
ArrayList<UserProperties> userProperties = new ArrayList<UserProperties>();
customListView adapter;
SensorManager sensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
for (int i = 0; i<5; i++) {
userProperties.add(new UserProperties());
}
listView = (ListView) findViewById(R.id.listView);
String[] spinnerValues = new String[] {"A", "B", "C", "D", "E"};
adapter = new customListView(MyActivity.this, userProperties, spinnerValues);
listView.setAdapter(adapter);
}
public void deleteUser (int index)
{
Log.i("debug", "Removing item " + index); // the index is really true and the true node deleting from the ArrayList but somehow the latest delete from the UI
userProperties.remove(index);
adapter.notifyDataSetChanged();
}
}
When I click on the Remove button deleteUser method called with the right index. but although the right node deleting from userProperties ArrayList somehow after notiftDataSetChanged is still alive
and the latest node delete.
So, How can I delete the right node/row (from the ArrayList and UI...)
Thank you!
EDIT:
Just to be clear, i variable contain true index. The true node deleted from the ArrayList. but something append after I called notify method.
I prefer to stay with BaseAdapter and not implement ArrayAdapter. Thank you!
EDIT 2:
After more debugging I found out my question was wrong. the true row really deleted just spinner values somehow update their values. I cannot close the question because it already answered. Thanks.
((MyActivity) context).deleteUser(i);
This line will always delete the first value from the ListView
You can use CAB (contextual action bar)
See if the code helps you(it's basically a ListActivity with a custom adapter to hold the status of checked items(+ different background)):
public class CABSelection extends ListActivity {
private ArrayList<String> mItems = new ArrayList<String>();
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i = 0; i < 24; i++) {
mItems.add("Name" + i);
}
// R.layout.adapters_cabselection_row is a LinearLayout(with green
// background(#99cc00)) that wraps an ImageView and a TextView
mAdapter = new SelectionAdapter(this,
R.layout.adapters_cabselection_row, R.id.the_text, mItems);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.cabselection_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
StringBuilder sb = new StringBuilder();
Set<Integer> positions = mAdapter.getCurrentCheckedPosition();
for (Integer pos : positions) {
sb.append(" " + pos + ",");
}
switch (item.getItemId()) {
case R.id.edit_entry:
Toast.makeText(CABSelection.this, "Edited entries: " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.delete_entry:
Toast.makeText(CABSelection.this, "Deleted entries : " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.finish_it:
nr = 0;
mAdapter.clearSelection();
Toast.makeText(CABSelection.this, "Finish the CAB!",
Toast.LENGTH_SHORT).show();
mode.finish();
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
nr = 0;
mAdapter.clearSelection();
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " rows selected!");
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
l.setItemChecked(position, !mAdapter.isPositionChecked(position));
}
private class SelectionAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
public SelectionAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
v.setBackgroundColor(Color.parseColor("#99cc00")); //default color
if (mSelection.get(position) != null) {
v.setBackgroundColor(Color.RED);// this is a selected position so make it red
}
return v;
}
}
}
Another way
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
getView(final int i,
Do not make i final. You did that to use i in onClick(). But that is not possible. So remove the final. Add:
holder.btnRemove.setTag(i);
And in onClick:
int position = v.getTag();
..deleteUser(position);
Maybe you have to cast something somewhere..
Remark: You have to set the tag always. So do it just before return view;.
Please do not use an i for position.

How to update values in database using an update image button in custom list adapter?

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 ;)

Listviews with EditText behavior

i've noticed an extrage behavior on my app that has a ListView with three EditTexts,
the problem is that whenever i select one textedit and move away from focus and come back the text i wrote in the first row i selected either desapears or moves to a different row, also when an edittext is focused and i go down in the list it seems that i have selected the edittext in the same position but 10 or 11 rows after the one im actually focusing(the one i can write to).
any knowledge on that case?
also im new to android so i dont know if thats supposed to happen.
this is the List im using.
public class In_List {
private int id;
private String text;
private float a;
private float Qty;
public In_List (int id, String text, float a, float Qty) {
this.id = id;
this.text = text;
this.a = a;
this.Qty= Qty;
}
public String get_text() {
return text;
}
public float get_a() {
return a;
}
public int get_id() {
return id;
}
public float get_Qty() {
return Qty;
}
}
here is the adapter:
public abstract class List_Adapter extends BaseAdapter {
private ArrayList<?> ins;
private int R_layout_IdView;
private Context context;
public Lista_adaptador(Context context, int R_layout_IdView, ArrayList<?> ins) {
super();
this.context = context;
this.ins = ins;
this.R_layout_IdView = R_layout_IdView;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R_layout_IdView, null);
}
onInsert (ins.get(position), view);
return view;
}
#Override
public int getCount() {
return ins.size();
}
#Override
public Object getItem(int position) {
return ins.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public abstract void onInsert (Object insert, View view);
}
and here is the main activity. it has a popup window that i used to fill the value of Qty but i its not included.
public class MainActivity extends Activity {
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listing);
ArrayList<In_List> data = new ArrayList<>();
for(int i=0; i<100; i++){
data.add(new In_List(i, "Item Number :"+i+1, i*2,0));
}
list = (ListView) findViewById(R.id.ListView_listing);
list.setAdapter(new List_Adapter(this, R.layout.entry, data){
#Override
public void onInsert(Object entr, View view) {
if (entr != null) {
TextView id_Text = (TextView) view.findViewById(R.id.textView_id);
if (id_Text != null)
id_Text.setText(((In_List) entr).get_id());
TextView info_Text = (TextView) view.findViewById(R.id.textView_info);
if (info_Text != null)
info_Text.setText(((In_List) entr).get_text());
TextView inside_Text = (TextView) view.findViewById(R.id.textView_inside);
if (inside_Text != null)
inside_Text.setText(((In_List) entr).get_a());
TextView Qty_Text = (TextView) view.findViewById(R.id.textView_qty);
if (Qty_Text != null || Qty_Text.getText().toString().equals(0))
Qty_Text.setText(((In_List) entr).get_Qty());
Qty_Text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Add_Qty();
}
});
}
}
});
// list.setOnItemClickListener(new OnItemClickListener() {
// #Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// In_List chosen = (In_List) parent.getItemAtPosition(position);
//
// CharSequence text = "Selected: " + chosen.get_textoDebajo();
// Toast toast = Toast.makeText(MainActivity.this, texto, Toast.LENGTH_LONG);
// toast.show();
// }
// });
}
}
now, when i scroll down through the list the Qtys that i have entered either disappear or move to another row.
fixed. i wasn't stablishing Qty_Text value at all. also made a method to save into the adapter array.
EditTexts in generally are very tricky. And using them inside a ListView is almost impossible. The special behaviour of EditTexts for example to always automatically assume focus combinded with the View recycling of the ListViews messes with the ListView and causes a lot of problems. I would suggest you look for another solution. For example placing the EditText inside the HeaderView of the ListView is fine, as the HeaderView is not recycled as you scroll through the ListView.

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();

Categories

Resources