Add Intent to OnItemClickListener - android

I have a listview ,I want that every button open different Activity.
listview there are many options,Each option will lead to another activity.
I didn't know how to do this.
Thanks.
Java
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] adobe_products = getResources().getStringArray(
R.array.adobe_products);
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
R.id.label, adobe_products));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String product = ((TextView) view).getText().toString();
Intent i = new Intent(getApplicationContext(), mavo.class);
i.putExtra("product", product);
startActivity(i);
} });}}
listen_item XML
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>

I'm just guessing since you didn't say what went wrong with your code. Maybe the ArrayAdapter is using more than simply a TextView for the layout of each list item, so you can't simply pull the TextView out the way you're doing it.
Try this instead for getting the product string:
String product = adobe_products[position];
You will have to make String[] adobe_products final.
EDIT:
Based on what I think you're asking, try this:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Class<? extends Activity> activityToStart = null;
switch (position){
case 0:
activityToStart = MyProduct0Activity.class;
break;
case 1:
activityToStart = MyProduct1Activity.class;
break;
//etc.
}
Intent i = new Intent(getApplicationContext(), activityToStart);
startActivity(i);
} });

Okie.. So here is what i understand from your comments. You have a listview and each item in the listview is a textview. And when you click on each item, you need to go to different screen / Activity.
If it is the case...
replace this code
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String product = ((TextView) view).getText().toString();
Intent i = new Intent(getApplicationContext(), mavo.class);
i.putExtra("product", product);
startActivity(i);
}
with this..
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Switch(position){
case 0:
String product = ((TextView) view).getText().toString();
Intent i = new Intent(AndroidListViewActivity.this, FIRST_SCREEN.class);
i.putExtra("product", product);
startActivity(i);
break;
case 1:
String product = ((TextView) view).getText().toString();
Intent i = new Intent(AndroidListViewActivity.this, SECOND_SCREEN.class);
i.putExtra("product", product);
startActivity(i);
break;
// Repeat the same for all screens
...
...
...
}
}
Note ::: I have not tested this code. This is just to give you an idea on how to do it.
Hope this helps..

Related

Android: Starting a new activity onListViewItem click

I've an Activity containing a basic Listview. The functionality works as follows:
click a listview item -> get the listview item name -> pass the name with intent and start a new activity.
Everything is working except for the start of a new Activity. Its just not responsive and I cannot see why. I would really appreciate an extra pair of eyes to look over this.
listView = getListView();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, foodNames);
listView.setAdapter(adapter);
listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView parentView, View childView, int position, long id) {
TextView tv = (TextView) listView.getSelectedItem();
String value = tv.getText().toString();
Log.v("DEBUG","Name of item clicked" + value);
Intent intent = new Intent(childView.getContext(), FoodItemActivity.class);
intent.putExtra("FoodName", value );
startActivity(intent);
}
public void onNothingSelected(AdapterView parentView) {
}
});
I think you are missing line
startActivity(intent);
:-)
try it this way:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(view.getContext(), FoodItemActivity.class);
intent.putExtra("FoodName", value );
startActivity(intent);
}
});
this will solve your question, and if still problem arises, then do confirm that all the child controls are focusable=false and clickable=false.

How to handle the click event in Listview in android?

The below is my testing code to create the list view, the list view display successfully, however, there is error in click event. I would like to create an intent to send a hardcode message to an new activity. However, it show error for the line
Intent intent = new Intent(context, SendMessage.class);
So , the problem is , what should I provide for this class?
Also , instead of hard code the output message, how to capture the data in list view row and pass to the new activity? e.g. BBB,AAA,R.drawable.tab1_hdpi for the first row.
Thanks.
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
members.add(new ListEntry("BcxvBB","AcxvAA"));
members.add(new ListEntry("BvBB","AcxsvAA"));
members.add(new ListEntry("BcxvBB","AcxsvzAA"));
members.add(new ListEntry("Bcxadv","AcsxvAA"));
members.add(new ListEntry("BcxcxB","AcxsvAA"));
ListView lv = (ListView)findViewById(R.id.listView1);
Log.i("testTag","before start adapter");
StringArrayAdapter ad = new StringArrayAdapter (members,this);
Log.i("testTag","after start adapter");
Log.i("testTag","set adapter");
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(context, SendMessage.class);
String message = "abc";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
}
I can not see where do you declare context. For the purpose of the intent creation you can use MainActivity.this
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
String message = "abc";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
To retrieve the object upon you have clicked you can use the AdapterView:
ListEntry entry = (ListEntry) parent.getItemAtPosition(position);
ListView has the Item click listener callback. You should set the onItemClickListener in the ListView. Callback contains AdapterView and position as parameter. Which can give you the ListEntry.
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, SendMessage.class);
String message = entry.getMessage();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
Error is coming in your code from this statement as you said
Intent intent = new Intent(context, SendMessage.class);
This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent
android.content.Intent.Intent(Context packageContext, Class<?> cls)
You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to
Intent intent = new Intent(MainActivity.this, SendMessage.class);
Also for sending your message from this MainActivity to SendMessage class please see below code
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
startActivity(intent);
}
});
Please let me know if this helps you
EDIT:-
If you are finding some issue to get the value of list do one thing declear your array list
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
globally i.e. before oncreate and change your listener as below
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, members.get(position));
startActivity(intent);
}
});
So your whole code will look as
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
members.add(new ListEntry("BcxvBB","AcxvAA"));
members.add(new ListEntry("BvBB","AcxsvAA"));
members.add(new ListEntry("BcxvBB","AcxsvzAA"));
members.add(new ListEntry("Bcxadv","AcsxvAA"));
members.add(new ListEntry("BcxcxB","AcxsvAA"));
ListView lv = (ListView)findViewById(R.id.listView1);
Log.i("testTag","before start adapter");
StringArrayAdapter ad = new StringArrayAdapter (members,this);
Log.i("testTag","after start adapter");
Log.i("testTag","set adapter");
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
startActivity(intent);
}
});
}
Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.
First, the class must implements the click listenener :
implements OnItemClickListener
Then set a listener to the ListView
yourList.setOnItemclickListener(this);
And finally, create the clic method:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at ",
Toast.LENGTH_SHORT).show();
}
//get main activity
final Activity main_activity=getActivity();
//list view click listener
final ListView listView = (ListView) inflatedView.findViewById(R.id.listView_id);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String stringText;
//in normal case
stringText= ((TextView)view).getText().toString();
//in case if listview has separate item layout
TextView textview=(TextView)view.findViewById(R.id.textview_id_of_listview_Item);
stringText=textview.getText().toString();
//show selected
Toast.makeText(main_activity, stringText, Toast.LENGTH_LONG).show();
}
});
//populate listview
According to my test,
implements OnItemClickListener -> works.
setOnItemClickListener -> works.
ListView is clickable by default (API 19)
The important thing is, "click" only works to TextView (if you choose simple_list_item_1.xml as item). That means if you provide text data for the ListView, "click" works when you click on text area. Click on empty area does not trigger "click event".

Passing a variable from a listview to another activity

I have been struggling using some tutorial for passing a listview option to a new activity and make it the title (I will do other stuff with it later). I have set up a OnClickListener by what is best to put inside it
ListView listView1 = (ListView) findViewById(R.id.sportslist);
String[] items = { "Archery", "Badminton", "Cricket", "Dodgeball", "Equestrian", "Football", "Golf", "Handball", "Ice Hockey", "Ju Jitsu", "Karate", "Lacrosse", "Mountain Biking", "Netball" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
?????
}
});
Thanks
EDIT:Extra code
final TextView changetitle = (TextView) findViewById(R.id.detailedsocietyname);
changetitle.setText(name);
For of all you will need to get the item that was selected:
final String selected = items[position];
Or as doctoror drive has suggested
final String selected = (String) parent.getSelectedItem();
Then you will need to pass that string as an extra to your new activity
Intent i = new Intent(getApplicationContext(), MyClass.class);
i.putExtra("name", selected);
startActivity (i);
And then finally in your next activity
Intent in = getIntent();
String name = in.getStringExtra(("name"));//gets name from intent
public void onItemClick(AdapterView parent, View view,int position, long id)
String str = items[position];
Intent in = new Intent(getApplicationContext(), NextClass.class);
in.putExtra("itemkey", str);
startActivity (in);
}
in public void onItemClick(AdapterView<?> parent, View view,int position, long id) add this code.
Intent i = new Intent(getApplicationContext(), NextClass.class);
i.putExtra("selectedItem", items[position]);
startActivity (i);
for getting value in NextClass Activitiy :
String SelectedItem = getIntent().getStringExtra("selectedItem");
Add the following to you Activity where you have listview
following is the variable that will contain the value that you want to pass to other activity
Declare it before Oncreate statement
// Activity_1
public final static String send_to_other_activity="ListViewSelected_ID";
Add the following code to the listView1.setOnItemClickListener
Intent i= new Intent(Recipe_List.this,Recipe_View.class);
i.putExtra(send_to_other_activity, string.valueof(position));
// itz (key-value) pair on the left key thru which u will access it on other place. on the right value that you want to pass
// Iam passing posiion to other activity here
startActivity(i);
Now on other activity extract this value from the key by adding following statement to the oonCreate of other activity
//Activity_2
getdata_from_list =getIntent().getStringExtra(Activity_1.send_to_other_activity);
now you have teh desired value in getdata_from_list

Adding multiple event to listview

I searched stackoverflow but couldnt find a answer(sure there is one somewhere) but I am trying to add a activity for each listview input. I can manage it with one intent but how do I give each listview input a seperate activity. So to be clear, I want to make every item have a serperate activity.
Currently use this code to initiate a activity but want individual activities for each item.
public class ListviewActivityActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.list_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), BMICalculatorActivity.class);
startActivity(i);
}
});
}
Have tried adding this but it failed to work
private static final int ACTIVITY_0 = 0;
private static final int ACTIVITY_1 = 1;
private static final int ACTIVITY_2 = 2;
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent();
// Set up different intents based on the item clicked:
switch (position)
{
case ACTIVITY_0:
intent.setClass(this, listview.activty.BMICalculatorActivity.class);
break;
case ACTIVITY_1:
intent.setClass(this, listview.activty.BodyLog.class);
break;
I know its probally simple to sort so any help would be amazing. Thanks
I think you want something like this :
Intent i = null;
switch (position)
{
case ACTIVITY_0:
i = new Intent(getApplicationContext(), BMICalculatorActivity.class);
break;
case ACTIVITY_1:
i = new Intent(getApplicationContext(), BodyLog.class);
break;
}
if(i != null)
{
startActivity(i);
}
Try something like this:
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i;
// selected item
String product = (String) lv.getItem(position);
if(product.equals("photoshop"))
i = new Intent(ListviewActivity.this, Photoshop.class);
else if (product.equals("final cut pro"))
i = new Intent(ListviewActivity.this, FinalCutPro.class);
else
i = new Intent(ListviewActivity.this, Generic.class);
startActivity(i);
}
});
Another option would be to make a POJO that held the name of the listview entry and the class to call. And add an array of those instead of an array of Strings. This will require using an ArrayAdapter of some kind. Then when you get the Item, you simply call startActivity(new Intent(listviewActivity.this, myPojo.classToCall); You should be able to find a good example of that somewhere on SO...

Listview , open new activity onClick

Hey everyone I've looked for hours trying to find a solution to this, my goal is to have a Listview when it opens well open another activity. Well actually I got it to be able to open another activity when its click but how do I get it so that each list item will open its own activity? I am terribly sorry if this question is already answered but the links I found doesn't really describe what the code is doing [Yes i am a newbie :)]
this is the code im using
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] countries = getResources().getStringArray(R.array.countries_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.newfile, countries));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Intent myIntent = new Intent(view.getContext(), Html_file.class);
startActivityForResult(myIntent, 0);
}
});
}
}
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 1) {
//code specific to first list item
Intent myIntent = new Intent(view.getContext(), Html_file1.class);
startActivityForResult(myIntent, 0);
}
if(position == 2) {
//code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(), Html_file2.class);
startActivityForResult(myIntent, 0);
}
}
});
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position ) {
case 0: Intent newActivity = new Intent(this, i1.class);
startActivity(newActivity);
break;
case 1: Intent newActivity = new Intent(this, i2.class);
startActivity(newActivity);
break;
case 2: Intent newActivity = new Intent(this, i3.class);
startActivity(newActivity);
break;
case 3: Intent newActivity = new Intent(this, i4.class);
startActivity(newActivity);
break;
case 4: Intent newActivity = new Intent(this, i5.class);
startActivity(newActivity);
break;
}
}
If you have some limited number of list you can use switch case here on position
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Intent myIntent = new Intent(view.getContext(), Html_file.class);
startActivityForResult(myIntent, 0);
}
});
If you know which activity is to be opened when different list items are clicked, then just assign id or tag to the list items.
In the callback of onItemClick, you have a parameter View,
use it to get id or tag to differentiate them and call respective Activity.
// Add ArrayList and ArrayAdapter:
final ArrayList<String> listItems = new ArrayList<String>();
listItems.add("image_one");
listItems.add("image_two");
listItems.add("image_three");
ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, listItems);
myListView.setAdapter(myArrayAdapter);
// Add ArrayList of Classes:
final ArrayList<Class> intents = new ArrayList<Class>();
intents.add(image_one.class);
intents.add(image_two.class);
intents.add(image_three.class);
// Click on list item to open Class from ArrayList of Classes:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Intent listIntent = new Intent(getApplicationContext(),
intents.get(position));
startActivity(listIntent);
}
});
SEE IMAGE OF CLASS NAMES HERE

Categories

Resources