Please explain Array Adapters and their purpose. Even better [closed] - android

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Better yet can someone explain this program point by point?
package com.paad.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class ToDoList extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate your view
setContentView(R.layout.main);
// Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
// Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
// Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
todoItems);
// Bind the array adapter to the listview.
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
}

ToDoList is the activity that defines the UI elements of the screen that user sees.
UI elements of the screen are defined in the layout /res/layout/main.xml
One of the UI element in the layout main.xml is a ListView whose ID is myListView
ListView can be something that acts as a container for list items. So all list view needs to know is, how many items are in the list, and how the each list item looks like?
An adapter is something that knows about the list items and how to represent or draw each list item on the screen.
Above example makes use of ArrayAdapter and its constructor takes 3 parameters having information about the list items
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
todoItems);
First argument is Context to access system services and resources ( you need layout inflater to create list item view )
Second argument defines the layout of the list that defines how the list item appears in listview. Here layout android.R.layout.simple_list_item_1 which is defined by framework is used.
Third argument is the information about the list item, typically this information is used to create view for the list item.
Finally created Adapter is given to the ListView
myListView.setAdapter(aa);
Now ListView calls the functions of Adapter to get the views of list item and populates in the container.
If the list items are changed ( here todo list ) Adapter can let the ListView know about it by calling notifyDataSetChanged.
aa.notifyDataSetChanged();
You can have a look at the implementation of ArrayAdapter to get more clarity.
Hope this helps you!

In simple terms, an Adapter is a collection handler that returns each item in the collection as a view. ArrayAdapter is one of many adapters available in Android. Others include, ListAdapter, GalleryAdapter, CursorAdapter, etc. Have a look at Android references

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set. Adapter

Related

Android ListView Tutorial with onclick and images

i want to make a listview having images on each row and if one item is clicked, user will be taken to another activity
i have 26 activities-
Activity_a
Activity_b
Activity_c
Activity_d
and so on...
and i want to have alphabet images at each row (i already have the images)
i found this tutorial on http://www.ezzylearning.com/tutorial.aspx?tid=1659127
Here is how my app should look like http://www.imagesup.net/?di=413818360350
And here is my .java file
package com.Rohit.MyApp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView1 = (ListView) findViewById(R.id.listView1);
String[] items = { "Milk", "Butter", "Yogurt", "Toothpaste", "Ice Cream" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
}
}
You should only use one activity and start it with a bundle. 26 Activities is just plain wrong.
You can use an OnItemSelectedListener on the List view and start an activity with:
Intent i = new Intent(this,ABCActivity.class);
i.putExtra("LETTER",selectedLetter);
startActivity(i);
That's assuming you figured out how to get the selectedLetter.
I think you are looking for a good tutorial link on Custom Array Adapters, here you go. And then just setOnClickListener for the image view.
For good coding practice, don't ever use so many activities. Consider reusing some of them or use Fragments

Android - Show textview by clicking on listview item

I am creating my very first Android application, but i stuck unfortunately. The application would be very simple: On the starting page there is a ListView with items like:
1st group
2nd group
3rd group
...
By clicking on any of these items a new page would show up with a single textview element that would have some description. Like you click on '1st group' item, the listview gets hidden, and a new page appears with '1st group description' text.
So far I can show the listview with the items, but when I click on them, nothing happens (i guess I miss some basic stuff, but as a very newby, i cannot find it out easily).
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.view.*;
public class SimpleListViewActivity extends Activity {
LinearLayout.LayoutParams layoutParams;
LinearLayout ll;
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// populate the List of groups
String[] GROUP = getResources().getStringArray(R.array.group);
ArrayList<String> GrList = new ArrayList<String>();
GrList.addAll( Arrays.asList(GROUP) );
// Create ArrayAdapter using the list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, GrList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
ll = (LinearLayout)findViewById(R.id.LinearLayout);
layoutParams = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView t = (TextView) findViewById(R.id.textView1);
String[] DESC = getResources().getStringArray(R.array.desc);
t.setText(DESC[position]);
ll.addView(t);
//This is the point that is wrong for sure (and others maybe also). I cannot get the textview shown
}
});
}
}
Thanks for your help.
Have you tried displaying a toast message or setting a breakpoint within your onItemClick() method to verify that its not being reached? My guess is that it is and you are running into one of the issues described here:
Refreshing a LinearLayout after adding a view
I am assuming your R.layout.main is holding a listview and a linear layout with ids R.id.mainListView, and R.id.LinearLayout respectively.
Example: I left out some of the obvious attributes you would need like height width etc..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
>
<ListView android:id="#+id/mainListView" />
<LinearLayout android:id="#+id/LinearLayout" />
</RelativeLayout>
In your on item click, all you will do is add a textview as you have done, then set the mainListView.setVisibility(View.INVISIBLE) and ll.setVisibility(View.VISIBLE).
If your R.layout.main is not using a RelativeLayout as the root node, but is instead using a LinearLayout you should still be able to achieve the same effect by setting the Visibilities to View.GONE if you want it to hide, and View.VISIBLE if you want it to show.
To revert back to being able to see the list view I would override onBackPressed() in the activity, to invert the Visibilities on the two items. Also remember to remove all views from the linear layout so that the next time an item in the group is selected it will be the only item in the linear layout when it is added.
There are much easier ways to accomplish this, such as firing off a new activity for viewing the next item, but seems you are keeping everything within one activity. I would also think about using a ListActivity instead of base activity class.
Hope this helps.
First off stop using the word page. Call it an activity (gotta get you in the Android zone)
Once the click happens start a new activity like so:
mainListView.setOnItemClickListener(new OnItemClickListener() {
String textToPass = GrList.get(position)
Intent i = new Intent(getBaseContext(), SecondActivity.class);
i.putExtra("textToPass", textToPass);
startActivity(i);
}
You'll obviously need to have that second activity with its corresponding layout file defined. Also in the second activity look up how to get the bundle and extras from the first activity in order to get the textToPass String

How to show previous list view using back button

Suppose I have displayed a list view(say lv1) of 3 items. when clicked on any of them I get new list view(say lv2). when again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. lv2 and again when back button is pressed I want to show list view lv1. can anybody tell me how I can do this?
If you want to shown different listviews in different activities. Follow Shailendra Rajawat's guide. Every time you click on an item, start a new Activity. So by default, when you press back button, the previous activity will be shown.
If you want to achieve this function within one activity. Use a variable to indicate which listview should be currently shown. Something like:
private int listIndex=0; every time you click on an item:listIndex++; and call setContentView(lvX); to show new listView.
Override the onBackPress() method:
if(listIndex>0) *so at the first listView backbutton will be ignored */
listIndex--;
switch(listIndex) {
case 0:
setContentView(lv0); break;
/* some other cases*/
........}
Something like this.
EDIT: I tested my method. Actually, there are three ways to refresh the listView.
package viewTest.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
public class ViewTestActivity extends Activity {
private ArrayAdapter<String> adapter0;
private ArrayAdapter<String> adapter1;
private String[] array0;
private String[] array1;
private ListView lv0;
private ListView lv1;
private RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array0 = getResources().getStringArray(R.array.LV0);
array1 = getResources().getStringArray(R.array.LV1);
adapter0 = new ArrayAdapter<String>(this, R.layout.item, array0);
adapter1 = new ArrayAdapter<String>(this, R.layout.item, array1);
lv0 = new ListView(this);
lv1 = new ListView(this);
layout=(RelativeLayout)findViewById(R.id.layout);
lv0.setAdapter(adapter0);
lv1.setAdapter(adapter1);
lv0.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//Method1: change the adapter to refresh the listview
// lv0.setAdapter(adapter1);
//Method2: use the layout to remove and add views
// layout.removeAllViews();
// layout.addView(lv1);
//Method3: setContentView() directly;
setContentView(lv1);
}
});
// layout.addView(lv0);
setContentView(lv0);
}
}
what you have described here it is obvious in Android Activity life cycle because when you hit back button it finish the current Activity and show the top most Activity on Stack . So please explain what problem you are getting here .
You can put some boolean to true if the second list view is showing. When back button is pressed, look at the boolean and change the listView to the first one.
as a neat and clean approach every screen you want to show on back press , should be on activity stack , so for every such views start a new activity even if they have same UI components .
if this approach is not suitable save data of every visible entity on navigations they reset views as per need by overRiding onBackPress().

Adapter for list view

please guide me with this program. Why do we need to use an array adapter to show the list? What is this "adapter", and can we display things directly in the ListView, without an adapter? Like, can we set setListAdapter(names) instead of setListAdapter(adapter);? Thanks.
Here is the code:
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] names = {
"Elliot","Geoffrey","Samuel","Harvey","Ian","Nina","Jessica",
"John","Kathleen","Keith","Laura","Lloyd"
};
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
names);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
From the android API reference,
An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.
It basically a set of interfaces that determine how the data will be handled by the list. You can use different pre-made adapter classes in your lists or create your own if you want to present custom data.
Take a look at this page in the Dev Guide: http://developer.android.com/guide/topics/ui/binding.html
Lars Vogel has a nice tutorial also: http://www.vogella.de/articles/AndroidListView/article.html
The Adapter acts as both a container for the information you want to display, and allows you to change how it is displayed by over-riding the getView() method of the adapter. Normally, by default, the adapter will call the toString() method of the Object used to create the Adapter and set the text in the TextView that is referenced in the layout provided by android.R.layout.simple_list_item_1... but by over-riding the adapter's getView(), you can have a more complicated layout display for the list.
To answer the initial question... you must use an adapter with a ListView.
This is how I do it and it works for me:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListViewDemo extends Activity {
// --------- Create your string array, adapter and ListView
String[] items = {"Cars", "Money","Vacation","Electronics",
"Shoes","Jewelry", "Buku bucks","Cash","Ham","Swag","Straight Cash","Homies","Roll Dawgs","Nate Dogg","Wiz Khalifa","Mac Miller","Chitty Bang",
"Sam Adams","Technine","Kanye West","Rims","Escalade","Spreewells","Chrome Rims","24's",
"Lebron James","Dwayne Wade","Andre Iguodala","Allen Iverson","Jodi Meeks",
"Levoy Allen","Mo Williams","Eric Snow","Alien Iverson","Laptop","Phone","Tablet"};
ArrayAdapter<String> adapter;
ListView cashList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cashList = new ListView(this);
// create the array adapter<String>(context, layout, array)
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
// add the adapter to the list
cashList.setAdapter(adapter);
// set the list as the content view
setContentView(cashList);
}
}

Android Custom Spinner - What is the useable result?

I have a custom spinner (customized for formatting). It works fine and shows the result of the selected array item. The string array with my data is called mydata[].
I want to do something with that result - I've tried hours of changes but, it seems I don't know what the container is for the selected result - it just displays automatically. The mNumber refers to a case select in a class (it's result is based on what's passed into-it).
My question(s) - refer to the * WHAT DO I USE HERE * shown in the code's last line:
1. What is the container for the result?
2. How to access and syntax it?
Here's the code:
Thank you!
**[declared in onCreate]**
Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
MySpinnerAdapter adapter = new MySpinnerAdapter(this, R.layout.mspinner, R.id.text,mydata);
spinner.setAdapter(adapter);
**[declared outside of onCreate]**
#SuppressWarnings("unchecked")
private class MySpinnerAdapter extends ArrayAdapter{
public MySpinnerAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
final TextView woof =(TextView)findViewById(R.id.TextView07);
woof.setText(String.valueOf(dogday.mNumber(*** WHAT DO I USE HERE ? ***)));
}
}
EDITED - FOR MY RESPONSE TO COMMONSWARE (too many characters for a comment box).
Thanks. You know the result that gets displayed in a spinner (by default) when something's selected - that's the piece of data I need. I want to use it as an argument for a call.
The user selects something in the spinner - The selected item will be used to make some choices in the class method (dogDay), which takes a data argument for mNumber(data) and returns a result (just like a function).
I want to do some math calcs with the result. First, I want to display what's coming back (for now) so, I'm using the dogDay.mNumber(data) as an argument for woof.text.
My question is this, How to get the piece of data (the thing the user selected in the Spinner)? How did the spinner know what to display for my selection - that's what I want? I tried using something like getSelectedItem (or whatever the it was - I can't remember just now) but, it crashes.
Is their an easier way to custom format a spinner? (and get the data) I searched hi and low for info and found only one applicable to android 1.5/later (I want a spinner with all black background and red text - I can do it via the way shown in my code using a the custom layout).
Thanks - I got a bit long winded!
EDITED - with full code
Here's a full code with the custom spinner and the call you suggested. As I mentioned, I already tried it - it only shows the first item in the list - never the selected one. I use the result of getSelectedItem as an argument for the string... I tried it from both within and outside the adapter...
package com.bt.junk;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MyMaincode extends Activity {
private static String mydata[] = {"one", "two", "three"};
int poop;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// DECLARATIONS ------------------------------------------------
Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
MySpinnerAdapter adapter = new MySpinnerAdapter(
this,R.layout.custom_spinner_row,R.id.text, mydata );
spinner.setAdapter( adapter );
poop = spinner.getSelectedItemPosition();
}//end onCreate ********************************************
// METHODS, CLASSES, etc ---------------------------------------
#SuppressWarnings("unchecked") //<-- I added that
private class MySpinnerAdapter extends ArrayAdapter{
public MySpinnerAdapter(Context context, int resource,
int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
final TextView sayWhat = (TextView) findViewById(
R.id.TextView01);
sayWhat.setText(String.valueOf(mydata[poop]));
}//end MySpinnerAdapter
}//end class MySpinnerAdapter
}//end activity
Your question makes little sense to me. I am assuming that "I want to do something with that result" means "I want to find out the selected item's position in the array". If that assumption is correct, you can get the selected position for a Spinner by calling getSelectedItemPosition(). This will be 0 when the Spinner first appears, unless you change the position yourself.
Your code is also very strange, IMHO. The constructor of an ArrayAdapter should not be attempting to manipulate a widget.

Categories

Resources