Populate ListView with text and value from strings.xml - android

I'm new to android and want to populate listview items that have id as value and string as caption.
All I could find searching was that they suggest using string array like:
<string-array name="test">
<item>first item</item>
<item>second item</item>
</string-array>
What i'm looking for is something like:
<string-array name="test">
<item value="1">first item</item>
<item value="2">second item</item>
</string-array>
just like the option tags of a select in html

Create a new Activity (this will make a xml file (layout) and a Java class.
On the layout, create a Layot that has a ListView on int:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >
<ListView
android:id=”#+id/itemList”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:entries="#array/test"
/>
On your activity, you have to:
Create a ListView variable
Map your view on the XML on this variable
Get a list of Strings from your resource array-adapter
Instanciate an Adapter (an object that you have to set on your listview to get your list (in your case, of strings) and add them in your recycler view. You can create a customized class for your adapter it, but when dealing with Strings, you can use a simple one called ArrayAdapter).
Set your adapter on your ListView object
To do all of those things, you put this in your code:
public class MyActivity extends Activity {
// Creating variable
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Mapping with your XML view
listView = (ListView) findViewById(R.id.itemList);
/// Getting list of Strings from your resource
String[] testArray = getResources().getStringArray(R.array.test);
List<String> testList = Arrays.asList(test);
// Instanciating Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(),
android.R.layout.simple_list_item_1, testList);
// setting adapter on listview
listview.setAdapter(adapter);
}
}

This will help you to retrieve string by position..
String[] some_array = getResources().getStringArray(R.array.your_string_array)

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

Spinner Android adapter in main Activity

Trying to simply get a Spinner going in my Application but the lines (commented out, the app works fine without these 2 lines) give me errors every time I try to start the Activity. I setup an Array in Strings.XML to be used in conjunction with the Spinner to view the data.
My XML contains a Spinner like so:
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
In Strings.XML I have my Array:
<string-array name="spinner_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
My Main Activity, 2 lines that are commented cause error.
public class BusPurchase extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spinner_array, android.R.layout.simple_spinner_item);
super.onCreate(savedInstanceState);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//spinner.setAdapter(adapter);
setContentView(R.layout.activity_bus_purchase);
}
Log Cat Displays this:
http://chopapp.com/#cbz5r823
call setContentView before accessing views from xml layout as:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bus_purchase); // set layout here
Spinner spinner = (Spinner) findViewById(R.id.spinner);
//..your code here
}
because you are trying to access views before setting layout for Activity
You are getting a Null Pointer on your references to spinner (R.id.spinner) because you are trying to reference items in your layout before you inflate the layout. Try calling setContentView(R.layout.activity_bus_purchase); first thing in your onCreate() method and see if that doesn't fix it.

How to fill a ListView with a string-array?

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

How to create listview in android? How many methods to be used?

I want to know about basics to create ListView.
How many methods to use the create ListView.
Hey i too new to android, there are two different ways to implement listview. 1) we can assign listview by giving values in main.xml.
<ListView android:id="#+id/ListView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
public class ListviewExample extends Activity
{
private ListView lv1;
private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
}
}
2) In second method, we can assign values in string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="countries_array">
<item>Bahrain</item>
<item>Bangladesh</item>
<item>Barbados</item>
<item>Belarus</item>
<item>Belgium</item>
<item>Belize</item>
<item>Benin</item>
</string-array>
</resources>
String[] countries = getResources().getStringArray(R.array.countries_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
This tutorial should guide you
http://developer.android.com/resources/tutorials/views/hello-listview.html
Take a look at the ApiDemos sample code, particularly the group of examples dealing with list views (follow the Views link and scroll down).

Changing a divider with setDivider in a ListActivity without a custom ListView?

I can't seem to get a customized divider, using a Drawable I've defined, to work when using a ListActivity and not creating a custom ListView. It almost seems like when the VM creates its own ListView for me, with the ListActivity, it uses a theme with the default divider provided; and if I try to provide one, no dividers appear in the ListView at all.
I know that I can create a custom ListView using XML and define android:divider on that ListView, and this does recognize my custom divider Drawable. But I would prefer to just let the ListActivity create its own ListView, if I can figure out how to get my own divider working on it.
Here's the code I'm using now:
public class Categories extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] OPTIONS = {
"Hello",
"Goodbye",
"Good Morning",
"Greetings",
"Toodaloo"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, OPTIONS);
setListAdapter(adapter);
ListView lv = getListView();
PaintDrawable sage = new PaintDrawable(R.drawable.sage);
lv.setDivider(sage);
lv.setDividerHeight(1);
}
}
I figured it out. The issue had nothing to do with the ListActivity generating a ListView for me. It was in how I was defining the divider in Java code.
There are two ways that I see to define the divider (border between ListView rows) on a ListView that is automatically inflated from a ListActivity, if you want to define the color in XML:
Method 1:
In res/values/colors.xml, put the following:
<resources>
<color name="sage">#cceebb</color>
</resources>
In your ListActivity-extending class, do this:
ListView lv = getListView();
ColorDrawable sage = new ColorDrawable(this.getResources().getColor(R.color.sage));
lv.setDivider(sage);
lv.setDividerHeight(1);
Method 2:
In res/values/colors.xml:
<resources>
<drawable name="sage">#cceebb</drawable>
</resources>
And in your class that extends ListActivity:
ListView lv = getListView();
ColorDrawable sage = new ColorDrawable(this.getResources().getColor(R.drawable.sage));
lv.setDivider(sage);
lv.setDividerHeight(1);
To set divider in listview programatically:
These code put inside in your .java Class
ListView lv = (ListView) findViewById(R.id.lv);
lv.setDivider(getResources().getDrawable(R.drawable.drawable_divider));
lv.setDividerHeight(1);
Creating Drawable: {res > drawable > drawable_divider.xml}
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ececec"></solid>
</shape>
Try this code:
searchText.setBackgroundColor(getResources().getColor(R.color.wordColorBlack));
ListView lv = getListView();
lv.setDivider(getResources().getDrawable(R.drawable.divider2));
lv.setDividerHeight(2);

Categories

Resources