Android ListView Tutorial with onclick and images - android

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

Related

Android changing activity issues, crashes on selection

So, what I'm trying to do is have a main menu and then press a button, it loads a list of countries.
now I've seemed to have set it up right, no errors I can see, but the app crashes before I load this activity (the lists) the main menu is fine, and I added another button with a blank activity which loads just fine.
logCat is giving me these errors
E/ArrayAdapter: You must supply a resource ID for a TextView
D/AndroidRuntime: Shutting down VM
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
and I'm not sure what it's asking for beyond the textView
heres my XML:
<ListView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#f897"
android:dividerHeight="1dp"
android:listSelector="#0f0"/>
and my Java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class countries extends AppCompatActivity {
ListView simpleList;
String countryList[] = {"India", "China", "Australia", "Portugal", "USA","England", "NewZealand", "Germany", "France","South Africa"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countries);
simpleList = (ListView)findViewById(R.id.text1);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_countries, countryList);
simpleList.setAdapter(arrayAdapter);
}
}
any help?
change:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_countries, countryList);
to:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,countryList);
your code not work because you use default ArrayAdapter with custom item layout
You array adapter expects the layout to be a TextView, but it look like R.layout.activity_countries is an activity layout?
You should create a custom adapter and custom view for each listview's row. Check it here: Custom Adapter for List View

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: how to set click events on ListView?

I'm looking to be able to open up a new view or activity when I click on an item in my ListView.
Currently I have a list of restaurants, and when i click on a particular restaurant I want it to open up another screen that will show its address, google map etc.
What I need help with is knowing how to set click events on the items in the list.
At the moment I dont have a database of the items, they're just Strings.
Can someone help me with getting me to this stage?
Thanks alot.
package com.example.androidrestaurant;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.ListActivity;
public class Dundrum extends ListActivity {
TextView selection;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, DUNDRUM));
getListView().setTextFilterEnabled(true);
}
static final String[] DUNDRUM = new String[] {
"Ananda",
"Brambles Cafe", "Brannigans", "Buona Sera",
"Cafe Mao", "Cafe Mimo",
"Dante", "Douglas & Kaldi Terrace Cafe",
"Eddie Rockets",
"Frango's World Cuisine",
"Nando's",
"Overends Restaurant # Airfield House",
"Pizza Hut",
"Roly Saul",
"Siam Thai","Smokey Joes","Sohag Tandoori",
"TGI Friday","The Rockfield Lounge", "Winters Bar" };
};
You need to do like this :
// Store your listview into local variable
ListView lv = getListView();
lv.setTextFilterEnabled(true);
// Bind onclick event handler
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Put in your code here, what you wanted trigger :)
}
});
If you are using the ListView in a ListActivity, override onListItemClick(). Otherwise, use setOnItemClickListener() with the ListView. In either case, you are given a position that is the index into your array.
See here for an sample project.

Categories

Resources