How to fill a ListView with a string-array? - android

I want to show these itens at my ListView
<string-array name="bookmark_titles">
<item>Google</item>
<item>Bing</item>
<item>Gmail</item>
</string-array>
I have a method that gets these values.
public static Collection getBookmarks(Context context) {
Collection bookmarks = new Collection();
String[] titles = context.getResources().getStringArray(R.array.bookmark_titles);
for (int i = 0; i < titles.length; i ++) {
bookmarks.add(titles[i]);
}
return bookmarks;
}
How can I call the method getBookmarks in my main.java to fill the ListView?
I have already created a ListView. It is:
<ListView
android:id="#+id/my_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#ECECEC"
android:dividerHeight="1sp" />
main.java
I am trying to do something like this:
ListView lv = (ListView) findViewById(R.id.my_listView);
ArrayList<Bookmark> my_array = BookmarkCollection.getTestBookmarks(context);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, my_array);
lv.setAdapter(adapter);

You can create your adapter with a one liner, check out the static method ArrayAdapter createFromResource(Context context, int textArrayResId, int textViewResId)
The first argument will probably be your Activity, the second is R.array.bookmark_titles, and the third is a layout to use.
To clarify based on the comments, the method accepts int, which is exactly what the constants in your generated R class are stored as.
Here's a complete example, assuming this is being called from an Activity:
ArrayAdapter<CharSequence> aa = ArrayAdapter.createFromResource(this, R.array.bookmark_titles, android.R.layout.simple_list_item_1);
myListView.setAdapter(aa);
In this case, android.R.layout.simple_list_item_1 refers to an XML layout that is provided by the Android SDK. You can change this if needed.

You can do this with an ArrayAdapter and have it use either an Array or a List to give it data
lv.setAdatper(new ArrayAdapter<String>(context, R.layout.some_layout_to_use, R.id.some_textview_in_layout, listData);

Related

confused about Textview and Listview for displaying a list

I tried a few different layouts to get deeper in possibilities and variances.
I started with an array to display the items in an listview that worked fine.
Now I wanted to display items that I got out of a database via JSON.
I get the following error: You must supply a resource ID for a TextView
I used the same XML-file, that worked before, here my all_products.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#color/colorPrimaryDark"
android:dividerHeight="1px">
</ListView>
</LinearLayout>
In my java class I used the code that I used before for the array adapter, I changed only the parameter which should be displayed. Here part of my AllProductsActivity.java:
private void processValue(ArrayList<String> result) {
{
ArrayAdapter adapter = new ArrayAdapter<String>(AllProductsActivity.this, R.layout.all_products, result);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
result comes from my asynctask. here a snippet as well:
JSONArray jsonArray = new JSONArray(result.toString())
ArrayList<String> listdata = new ArrayList<String>();
for(int n = 0; n < jsonArray.length(); n++)
{
JSONObject object = jsonArray.getJSONObject(n);
listdata.add(object.optString("nr"));
}
return listdata;
protected void onPostExecute( ArrayList<String> result) {
pdLoading.dismiss();
processValue(result);
}
Why I get the error? And perhaps what about using only a Textview. As I was searching for the toppic, I found different threats where people using Textviews instead of Listview.
EDIT: So it works I added another xml file, mytextview.xml
<TextView android:id="#+id/mytext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#color/colorPrimaryDark"
android:dividerHeight="1px"
xmlns:android="http://schemas.android.com/apk/res/android">
and changed the adapterstatement to the following:
ArrayAdapter adapter = new ArrayAdapter<String>(AllProductsActivity.this,
R.layout.mytextview,R.id.mytext , result);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
when you use custom layout R.layout.all_products then Adapter don't know about the view to set the data from data list
so simply you need to tell the adapter , the ID of your text view to set data on .
ArrayAdapter adapter = new ArrayAdapter<String>
(AllProductsActivity.this,
R.layout.all_products,R.id.your_text_view_id, result);
// ^^^^^^^^^ pass the text view ID
ArrayAdapter (Context context,
int resource,
int textViewResourceId,
T[] objects)
or
If you just want to display your data without any custom layout then can use in build android resource layout as
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,result);
in Pavneet's first solution take care that:
resource: is the resource containing a textView not your xml file that contain the list itself (not R.layout.all_products)
textViewResourceId: the ID of the textView contained in the resource
When instantiating your ArrayAdapter, the id you provide must be from a layout containing only a TextView. That is what the error You must supply a resource ID for a TextView means

Android : loop through all items in a listview

Want to get quick answer how to list all items on my listview, in order to print out a list or share to a notepad app etc. That is, to get a variable with following information from the listview: "apple", "banana", "orange". Below is my listview. Thanks
String[] values = new String[] { "apple", "banana", "orange" };
listItems = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
listItems.add(values[i]);
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
listItems);
// Assign adapter to ListView
listView.setAdapter(adapter);
Your question says,
Loop through all items in a listview.
I understand from your code that you want to add the items from String array to ArrayList.
But, you can pass String array directly as a third parameter to your ArrayAdapter.
Look at the suggestions provided by Android studio for ArrayAdapter. You can pass String[] or ArrayList too :
Either you can pass String[] or if you wanted to loop through all String[] items to ArrayList, you can simply do by a single line.
Collections.addAll(arrayList,values);
arrayList - ArrayList
values - String[]
instead of,
listItems = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
listItems.add(values[i]);
}
And in comment section, you said
I think I may add/remove item at a time to the listView later.
In this case, you can have some button to reload the list to show the old items + added new items or to show the list except the items which you've deleted. I'll add below how you have to achieve it.
Have a button AddMore in your layout and whenever you want to add new items, then do like this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
arrayList.add("lemon"); // this adds item lemon to arraylist
arrayList.add("Pomgranete");
arrayAdapter.notifyDataSetChanged(); // this will refresh the listview and shows the newly added items too
}
});
You can delete the item similarly by passing the position of the item in arrayList,
arrayList.remove(arrayList.get(i)); // i is the position & note arrayList starts from 0
So, by summing up everything, here's the full working code :
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] values = {"Apple", "Orange", "Banana"};
List<String> arrayList;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
button = (Button)findViewById(R.id.button);
arrayList = new ArrayList<String>();
Collections.addAll(arrayList,values); // here you're copying all items from String[] to ArrayList
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
arrayList.remove(arrayList.get(2)); // here i remove banana since it's position is two. My ordering of items is different so it removed banana. If i use ordering from your quest, it will remove orange.
arrayList.add("lemon"); // adding lemon to list
arrayList.add("Pomgranete"); // adding pomgranete
arrayAdapter.notifyDataSetChanged(); // this used to refresh the listView
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ADD MORE"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/button" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/button" />
</RelativeLayout>
Output :
List with pre-defined 3 items and one button to load more items.
List with old 3 items + newly added 2 items (Here i didn't use arrayList.remove)
List with old items except deleted item + newly added 2 items (Here i used arrayList.remove to remove banana by arrayList.remove(arrayList.get(2));)
As I understand you want to create an ArrayAdapter, later add a few items to it and at some point retrieve all items from it, right?
Since you use ArrayAdapter you can just iterate over its content:
String[] items = new String[adapter.getCount()];
for(int i = 0; i < adapter.getCount(); i++){
items[i] = adapter.getItem(i);
Log.d("TAG", "Item nr: " +i + " "+ adapter.getItem(i));
}
ArrayAdapter documentation
Since you already have an array AND an arraylist in your code it should be easy.
But if you want to loop later and you have only your listview, I believe there is a getter for the adapter in your listview, and if you cast the given adapter to ArrayAdapter, it should then have a getter to the the items you are looking for.
ArrayAdapter<String> adapter = (ArrayAdapter<String>)mListView.getAdapter();
for(int i=0; i<adapter.getCount();i++){
String item = adapter.getItem(i);
/*...*/
}
You don't need to loop or anything just pass the array directly to the adapter.
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
values);
the new ArrayAdapter took an array as a third parameter.

GetListAdapter returning null in Android

I have an activity that extends ListActivity. In its onCreate method I perform below:
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(new InteractiveArrayAdapter(this, model));
I set a custom adapter for my listview widget defined in xml layout.
My custom adapter, InterativeArrayAdapter, extends ArrayAdapter. Model is a class that I have built to manage listview items data.
My problem is in the activity that extends ListActivity: When I handle a button click I perform the following:
public void onClickCompareButton(View view) {
InteractiveArrayAdapter adapter;
Set<Integer> checkedItems;
Iterator<Integer> it;
Model element;
adapter = (InteractiveArrayAdapter) getListAdapter();
checkedItems = adapter.getCheckedItems();
it = checkedItems.iterator();
int size = checkedItems.size();
for (int i = 0; i < size; i++) {
element = adapter.getItem(it.next());
// TODO
}
}
The problem is the cast:
adapter = (InteractiveArrayAdapter) getListAdapter();
adapter gets null value so next line crashes:
checkedItems = adapter.getCheckedItems();
Any ideas on how to solve this?
The problem should be with the way you set the adapter to your list.
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(new InteractiveArrayAdapter(this, model));
Since you extend ListActivity the ListView should be by default available to your Activity. So you should try this,
setListAdapter(new InteractiveArrayAdapter(this, model));
setListAdapter(adapterObj) - is available when you extend an ListActivity.

xml string-array to listView not working

public class Menu extends Activity {
String[] categories;
ListView lv;
Cursor cursor;
Context context;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categories = getResources().getStringArray(R.array.Categories_Array);
lv = (ListView) findViewById(R.id.listViewCategories);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.activity_main,
getResources().getStringArray(R.array.Categories_Array));
lv.setAdapter(adapter);
}
...
}
I keep getting an "unfortuneately Bible CYB has stopped working" when I run the app
The problem you have is that you are giving your ArrayAdapter a full Activity's layout to inflate. What you want to do is pass it the row's layout it should use for each of the individual rows it should inflate:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, // or other basic row layout
getResources().getStringArray(R.array.Categories_Array));
You have set the activity_main.xml to the activity and use the same in the constructor of ArrayAdapter. To display the a single string in each row
Change this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.activity_main,
getResources().getStringArray(R.array.Categories_Array));
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.simple_list_item_1,
categories);
where simple_list_item_1.xml is the layout from the android framework
http://androidxref.com/4.4.3_r1.1/xref/frameworks/base/core/res/res/layout/simple_list_item_1.xml
And the constructor
public ArrayAdapter (Context context, int resource, T[] objects)
Added in API level 1 Constructor
Parameters context The current context. resource The resource ID for a
layout file containing a TextView to use when instantiating views.
objects The objects to represent in the ListView.
Instead of using a array adapter try using a list adapter.. it wud give it a custom layout u designed ..
lv = (ListView) findViewById(R.id.listViewCategories);
ListAdapter adapter = new SimpleAdapter(this,
/*id for your custom layout for ex: R.layout.activity_main*/,
getResources().getStringArray(R.array.Categories_Array),/*Here write the id of the text view where u want to display the info.. forex: R.id.tvExample*/);
lv.setListAdapter(adapter);

Android ListView: don't show all strings

I show a listview from the following string:
String[] values = new String[] { test1, test2, test3 };
The variables:
private String test1 = "test";
private String test2 = "test";
private String test3 = "test3";
Now I don't want to show the strings that contain "test" in my listview.
Like this:
if (String == "test") {
*don't show in ListView*;}
And I want it to test all Strings at once if they contain "test"
How is it possible?
EDIT: Here the adapter code:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
Yup...
if (values[i].equals("test")) // i being the iterator of your for-loop
OR
if (values[i].contains("test"))
contains is a slow(er) string function though.
You might want to use an ArrayList though... that way you can just add all those objects to the array list, then iterate through it... and remove them as you go...
// Do something to add all items to your array list
...
// Iterate through the list, removing what doesn't need to be there
for (int i = 0; i < arrayList.size(); i++){
if (arrayList.get(i).contains("test"))
arrayList.remove(i);
}
...Then set 'arrayList' (or whatever you've called it) as the string list for your adapter. If you use the same constructor it'll look like this...
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, arrayList.toArray());
all the time, if you want compare 2 strings use the equals methode
read this about The equals() method
You should be using a filter on your ListView. Look at these examples:
(Simple iterating) http://androidsearchfilterlistview.blogspot.com/2011/06/android-custom-list-view-filter.html
(getFilter()) Filtering ListView with custom (object) adapter
Like others have posted, you compare String objects using .equals(), but if you are trying to only display certain items in your ListView you should use the getFilter() method like described in the link I posted.
edit: I found you a nice SO example.

Categories

Resources