I want to get a random list item from a list on click of button in android. Can someone guide me to a tutorial or example where I can find how this can be done, or if someone has already done something like this can i see a sample code. I'm clueless as how to get by it. Need help.
public class RandomActivity extends Activity {
String arr[]={"A","B","C","D","E"};
ListView list;
p v onCreate(Bundle saved) {
list = (ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,arr);
list.setAdapter(adapter);
}
public void onRandom(View v){
list.getAdapter().getItem(new Random().nextInt(list.getCount()));
}
}
Still not getting the size() method so i substitutedit with getCount().But not generating a random value;
Use the Random class (http://developer.android.com/reference/java/util/Random.html)
list.get(new Random().nextInt(list.size()))
Since Kotlin 1.3:
list.random()
If the list is empty, it will throw NoSuchElementException. Docs
If you can't use Kotlin, then #tom's answer is your way to go.
Related
I want to create an ArrayList, add values to it from different other activities and then show it as a listview in some another activity. I know how to create a list view but I am don't know how to create an ArrayList globally and add values to it via other activities. It would be really helpful if you can provide me with a sample code for the full problem. I don't want to go for any advanced method, as it is for a beginner college project and I want to explain my implementation method properly.
Basically, it's a shopping app where I am storing the name of bought products in an ArrayList on the click of a button. And then showing the final list in listview on the cart activity.
First, create a class to hold the ArrayList globally:
public class ListHolder {
public static List<String> list = new ArrayList<>();
}
Use the array list in any activity you want:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
... // Init views
// Obtain the list
List<String> list = ListHolder.list;
// Maybe add something to it
list.add("sample");
// Set the list to your adapter to render it by your ListView
yourAdapter.setData(list);
yourAdapter.notifyDataSetChanged();
}
}
I have a ListView in my android app that does sorting. For example, when I clicked Name, it sorts by name.
Here is the code:
private class MyListAdapter extends ArrayAdapter<Person> {
private final ArrayList<Person> people;
//.......
public void sort(SortBy x) {
switch (x) {
case NAME:
this.sort(new OrderByName());
sortedBy = "NAME";
break;
Here is the Comparator:
private static class OrderByName implements Comparator<Person> {
#Override
public int compare(Person s1, Person s2) {
return s1.getName().compareTo(s2.getName());
}
}
When I click Name to sort the listview by name.. I got the list sorted but the old row of data still remains.. and associates with another row...
I am fairly new to Android... And I really need some help on debugging this issue. Thanks in Advance!
After sorting the list, just use the notifyDataSetChanged() method to your ArrayAdapter object. It will refresh the list. I'm assuming, you're not creating more than one ArrayAdapter object.
//notify that the list changed adapter.notifyDataSetChanged();
First check whether your ArrayAdapter have latest values in it.If it is updated with latest values used below :
adapter.notifyDataSetChanged(); // notify the listview to update items in the list.
Hope these helps you.
I am trying to take an AutoCompleteTextView and, through an OnListItemClickListener, return an ID from a database. To be more specific, I want a user to be able to type something in, click on one of the options that pops up, and then, rather than completing the typed word, the click returns an ID associated with that word to the user.
I know that, through a custom adapter, I can return an id through a Spinner, but I want a user to be able to type in what they're looking for. Is there some way to do this through AutoCompleteTextView, or does another class exist where I can do this?
Thank you!
AFIK there is no such class with both the functionalities.
You can try the following code which does that...
final AutoCompleteTextView mAutoCompleteTextView;
final ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_dropdown_item_1line,
getResources().getStringArray(R.array.items));
mAutoCompleteTextView = (AutoCompleteTextView) view.findViewById(R.id.name_txt);
mAutoCompleteTextView.setAdapter(mAdapter);
mAutoCompleteTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
mAutoCompleteTextView.showDropDown();
}
});
I have an application developed to get all the third party applications installed and to display them on a list view! this is been done by an extended baseAdapter. In this list I do an uninstallation of a selected application using this code :
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + Packname));
startActivity(intent);
Now what I want is to update the list view with the changed data so that the user can get updated application list. how can I achieve this. I found that notifyDatasetchanged method but it can only be used for simple listviews! what are the options that I have and please let me know of any tutorials to achieve my outcome!
thank you.
What do you mean only for simple listviews? How is yours different? You should be able to call notifyDataSetChanged on your custom adapter class after deleting one of your items. You can create a function to do it...
private ArrayList<Object> list;
public void deleteItem(int index){
list.remove(index);
notifyDataSetChanged();
}
you will have an adapter (something that extends BaseAdapter probably) that you set into the ListView using setAdapter(...). add a method to your adapter implementation class that sets the underlying objects that are backing the list. make sure to call notifyDataSetChanged() at the end. something like,
public class MyAdapter extends BaseAdapter<String> {
private List<String> strings;
...
void setModel(List<String> strings) {
this.strings = strings;
this.notifyDataSetChanged();
}
}
simply calling your adapter's setModel(...) will cause the ListView to update.
I've been playing around with ArrayAdapters and I've reached a point where I'm getting different results from two almost identical ArrayLists + ArrayAdapter combinations.
The first one:
An ArrayList of 'Restaurant' objects, an ArrayAdapter that uses this ArrayList and a ListView that binds this ArrayAdapter.
private ArrayList<Restaurant> model = new ArrayList<Restaurant>();
private ArrayAdapter<Restaurant> restaurantAdapter = null;
...
public void onCreate(Bundle savedInstanceState){
...
restaurantAdapter = ArrayAdapter<Restaurant>(this, android.R.layout.simple_list_item_1, model);
...
listView.setAdapter(restaurantAdapter);
...
}
The second one:
An ArrayList of String objects, an ArrayAdapter that uses this ArrayList and a AutoCompleteTextView that binds this ArrayAdatper.
private ArrayList<String> prevAddressList = new ArrayList<String>();
private ArrayAdapter<String> addListAdapter = null;
...
public void onCreate(Bundle savedInstanceState){
...
addListAdapter = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, prevAdddressList);
...
autoCompleteField.setAdapter(addListAdapter);
...
}
I have a save button, on click, I'm creating a restaurant object with a name and an address and adding it to the first adapter, additionally, I want to create a list of previously used address so they are "auto completed" next time they are typing it, so I'm taking the text, and adding it to the second adapter.
...onSave = new View.OnClickListener(){
...
restaurantAdapter.add(r); //r is a Restaurant object.
addListAdapter.add(autoCompleteField.getText().toString());
...
}
Now, everything is working properly. I get the Restaurants displayed in a ListView. The AutoComplete is working as expected.... but I noticed something when I was checking the values while debugging:
The actual ArrayLists, model (Restaurant) is getting updated after adding an object to the adapter , but prevAddressList (String) is not.
Unless, I set the AutoCompleteTextField empty.... then, the prevAddressList gets updated after adding something to the second adapter.
Already tried using notifyDataSetChanged(), but it makes no difference (and it is set to true on every adapter by default anyway).
Other behavior that differs between the two adapters is that in the first one (Restaurant), values are going to the mObjects field, while in the second one (String) they are going to mOriginalValues instead.
I'm completely stomped. The only difference between those two adapters is that one is type "Restaurant" and the other is type "String".
Any ideas? Maybe I'm missing something very obvious? Let me know if you need the full code.
thanks
Instead of adding it to the adapter, try adding the object to your list and then calling notifyDataSetChanged on your adapter. The adapter should pick up your changes and your list of course will have the object you just added.
For anyone coming here from google:
Unable to modify ArrayAdapter in ListView: UnsupportedOperationException
This might explain the behavior, although I have to test it myself.