I have an android spinner item, in which the lines are made up of a TextView and an ImageView (a star, to mark that the user has marked that particular item as a favourite). Now, when a user favourites an item, I want to make the star appear next to that item in the spinner list, so I want to redraw the spinner to show the updated images. How do I do this?
What I'm doing now is that I'm creating a whole new spinner, with the appropriate images. This makes my spinner set the selected item to the first item in the list, which is annoying - I want it to stay the same. I have tried
spinner.setSelection(selectedItem);
This works for ANY number other than the number I actually want (the position of the currently selected item), then it sets the selected spinner item to the first in the list again.
So: how can I redraw the list with the updated information without having to recreate the whole list, or alternatively, how can I recreate the list and still preserve the spinner item selection?
To clarify: here's what I'm doing
// Callback for "favourite"-button
star.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View arg0) {
// Toggle favourite
getActiveSelection().setStarred(getActiveSelection().isStarred() ? false : true);
reloadText();
createSpinner();
}
});
private void createSpinner() {
spinner = ((Spinner)findViewById(R.id.spinner));
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
// Populate spinner item list
for(int i=0; i<N; i++) {
SpinnerItem item = getSpinnerItem(i);
map = new HashMap<String, Object>();
map.put("Name", item.getName());
map.put("Icon", (item.isStarred() ? "On" : "Off"));
list.add(map);
}
MySpinnerAdapter aspn = new MySpinnerAdapter(this, list,
R.layout.spinner, new String[] { "Name", "Icon" },
new int[] { R.id.spinnerrow, R.id.spinnerrowicon });
spinner.setAdapter(aspn);
spinner.setSelection(getActiveSelection().getSpinnerPosition());
}
You may just update spinner adapter - let it know which item is starred when user clicks on the star icon (star.setOnClickListener...). What I would do:
In adapter construction, you pass only list of "Name" fields, no need for icon (all not starred by default)
You add separate function to adapter to set starred item (setStarred(String name))
On initial call, invoke setStarred to set initial selection (if any)
in star.setOnClickListener implementation, call setStarred for starred item on adapter which you obtain as (MySpinnerAdapter)spinner.getAdapter()
Or just try:
spinner.setSelection(getActiveSelection().getSpinnerPosition(),true);
That worked for me to update the spinner...
You need to call notifyDataSetChanged() on your spinner adapter when your data has changed.
Related
Because android automatically moves new items to the bottom of list view I want that to be reversed. In any case my condition is met, I want to add new items on top of list view.
I have seen this post here but I don't know how to add that to my code, here it is:
if(condition){
listView = (ListView) findViewById(R.id.ListView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, R.layout.list_b_text, R.id.list_content, ArrayofName);
listView.setAdapter(adapter);
}
Just simply add every item at position 0 of your ArrayList so when you call listView.notifyDataSetChanged(); it will show latest items on top.
for (Object obj : objectList) {
ArrayofName.add (0, obj); // this adds new items at top of ArrayList
}
objectList is basically an ArrayList or List of Object or String (whatever is your case). If you want to add items one by one, remove for loop. This loop actually iterates every item of objectList and adds it in your ArrayList at top position.
Using the following code, when an item from the list is selected it updates a data table. The problem is when there are several items listed, regardless of which one is selected, it always updates the first listed item showing rather than the one selected. Thanks in advance!
Edited-Updated. Incorporated (position) and tried to simplify a bit of the code. Still will not capture the selected item, always returns the top item showing on the listview, regardless. The DB controller is working fine, all else is good except this...
setContentView(R.layout.list_messages);
ArrayList<HashMap<String, String>> phraseList = controller
.getUnreadMessage();
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(
ReadUnReadMessages.this,
phraseList,
R.layout.view_list_messages,
new String[] { "mFromName", "mToAddress", "mBody",
"mToName", "messageTime", "mFromAddress", "mRead",
"messageId" },
new int[] { R.id.messageFrom, R.id.messageToAdd,
R.id.messageBody, R.id.messageTo, R.id.messageTime,
R.id.messageFromAdd, R.id.readCode, R.id.messageId });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg) {
#SuppressWarnings("unchecked")
HashMap<String, String> queryValues = (HashMap<String, String>)parent.getItemAtPosition(position);
messageBody = (TextView) findViewById(R.id.messageBody);
readCode = (TextView) findViewById(R.id.readCode);
messageId = (TextView) findViewById(R.id.messageId);
String readCode = "1";
queryValues
.put("messageId", messageId.getText().toString());
queryValues.put("mRead", readCode);
queryValues.put("mBody", messageBody.getText().toString());
controller.markMessage(queryValues);
this.callSplash(view);
}
public void callSplash(View view) {
Intent objSplash = new Intent(getApplicationContext(),
Splash.class);
startActivity(objSplash);
}
});
It's hard to tell exactly how you were expecting it to work, but it seems like your central problem is that you are ignoring the 'position' parameter to onItemClick. This is Android's way of telling you which item was clicked. Somehow you need to pass that parameter, or else the corresponding item object that you fetch first from the adapter, on to the functions you call from onItemClick:
this.insertData(position);
Otherwise those functions would have to guess which item was clicked. And apparently that is what they are doing: they are assuming the first item was clicked.
I am new in Android development. I have MultiselectionListview in my app.I want to delete all the items selected, But for it i have to call a function from Sqlite Db.I have to pass selected item positions in the form of array. I am getting position as follows :
SparseBooleanArray checked = lv_del.getCheckedItemPositions();
for (int i= 0; i<=checked.size();i++)
{
int[] posArr = new int[checked.size()];
// Item position in adapter
int position = checked.keyAt(i);
if(checked.valueAt(i))
{
posArr [i] = (int) adapter.getItemId(position);
}
}
}
but its not working, how can i pass selected items positions via array ??
any help will be appreciated.
You can use an additional button outside the listview as an ok button.And write the code for creating the list of items using position array and call the delete function with that list in the listener of ok button.
I have a listview displaying list of items and a button at the bottom. On click of button, i'am displaying one alert dailog box to take input from user and adding that input to the listview. 1. How can i make sure the new input/entry should add always at top of listview? (Right now it is adding at bottom always)2. Is it possible to position the list view at the new entry? (i.e if the new entry is added at top, the list should be positioned at the top)Please guide me.
Inside onCreate()...
list = (ListView)findViewById(R.id.planetList);
adapter = new ArrayAdapter<String>(MyListViewActivity.this,
R.layout.my_list_row, R.id.planetNameTextView);
for (int i = 0; i < planetNamesArray.length; i++) {
adapter.add(planetNamesArray[i]);
}
list.setAdapter(adapter);
After taking input from user ....
adapter.add(newPlanetNameEnteredByUser);
adapter.notifyDataSetChanged();
you can use listview.setStackFromBottom(false) to fill your listview from top.
this link may help you.
http://developer.android.com/reference/android/widget/AbsListView.html#setStackFromBottom%28boolean%29
Yes you can do that, have two List.
List<String> old = new ArrayList<String>(); // contains your list content
List<String> new = new ArrayList<String>();
Now, when you want to add new content to ListView then add it first to the new ArrayList,
new.add("new content");
new.addAll(old); // add all the old contents
new.setSelection(position_you_want);
adapter.notifyDataSetChanged();
Add the object in array list
ArrayList<String> List= new ArrayList<String>();
ListView ListName= (ListView)findViewById(R.id.playerdata);
with
List.add(index, "value");
public void add (int index, E object)
Since: API Level 1
Inserts the specified object into this ArrayList at the specified location. The object is inserted before any previous element at the specified location. If the location is equal to the size of this ArrayList, the object is added at the end.
Parameters
index the index at which to insert the object.
object the object to add.
Throws
IndexOutOfBoundsException when location < 0 || > size()
and set list adapter
ListName.setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1 , List));
I'm using the following code to populate listview
Oncreate method:
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.more_custom_row_view, new String[] {"title","desc"}, new int[] {R.id.text1,R.id.text2});
populateList();
setListAdapter(adapter);
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
private void populateList() {
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("title","Previous Searches");
temp.put("desc", "View your search history");
list.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("title","Settings");
temp1.put("desc", "Update your account settings");
list.add(temp1);
}
when i go to another activity and come back to this acitivity it duplicate list items
each time any one guide me what mistake am i doing?
The problem is that you are using a static list for your items and not clearing or reinstantiating it in your onCreate method.
The list will stay in memory as long as your program is running because it is defined static. If you are returning to the activity the items are again added to the list. You could use clear() to remove all items from the list in your populate list call before filling it again.
Simple, check adapter.isEmpty() before populating
This is a snippet from my own codebase.
private void populateWithAppPackages() {
//DON'T continue if the adapter is not empty; prevents duplicates
if(!mAdapter.isEmpty()){
return;
}
/* ... populate the list ... */
}
DON'T clear() the list adapter!!
clear() and repopulating list every time the activity or the fragment are visited is a very expensive set of operations. You would be better of intelligently populating the list as above.
removing final from the list resolved my problem.