How to reference OnListItemClick in ListActivity - android

I am working on an android app, and I am having difficulties with ListActivity. I would like to have a different Activity start depending on which item in the list is clicked.
I made a list and referenced it with setListAdapter in java, but I am not sure how to reference in the OnListItemClick. I assume I need to reference the position in the list.
With Activity and Buttons, I can set the OnClickListener and use a switch statement with a case for each Button. What is the equivalent for ListActivity?
Here is my code:
public class Options extends ListActivity implements {
String myHistory[]= { "Item 1", "Item 2", "Item 3" };
//---Set ListView---
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String> ( Options.this,
android.R.layout.simple_list_item_1, myHistory)));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
//--if click position 1, do below
//--Intent a = new Intent("show Item 1's corresponding page");
//--startActivity(a);
//--if click item in position 2, do below
//--Intent b = new Intent("show Item 2's corresponding page");
//--startActivity(b);
//--if click item in position 3, do below
//--Intent c = new Intent("show Item 3's corresponding page");
//--startActivity(c);
}
}

I'm not sure there are other ways of doing it, but I do it this way:
I set the click listener on the activity class (not on the adapter one, which I think makes more sense).
SAve an array of the classes you wish to call:
Class[] classList = new Class[]{class1.class, class2.class....};
add the listener to the listview
lv.setOnItemClickListener(listviewClickListener());
Then the onItemClickListener method:
private OnItemClickListener listviewClickListener() {
OnItemClickListener clickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//And then call the corresponing one
Intent I= new Intent(thisActivity, classList[i]);
int id = listOfObjects.get(position).getId();//do whatever you want with the object on the postition "position"
Bundle bundle = new Bundle();
bundle.putInt("id", id);
i.putExtras(bundle);
thisActivity.startActivity(i);
}
};
return clickListener;
}
I didn't test the array of class literals, but I guess it should work..
Edit: I'm considering you want to create different activities for each item (which thinking about it doesn't make much sense (not having the context) as all items on a list view belong to the same group, and therefor might probably be used in the same way). Otherwise you don't need the list of activities, and just add the one you wish to the intent.

as looks there are only few and certain data in list not at run time because each item has a separate activity (like a menu list of game) so I will suggest to go short and simple .......
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Intent a;
switch(position){
case 1:
a = new Intent("show Item 1's corresponding page");
break;
case 2:
a = new Intent("show Item 2's corresponding page");
break;
case 3:
a = new Intent("show Item 3's corresponding page");
break;
if(null!=a)
startActivity(a);
}
}

you must have to use Adapter object and set that with the ListView Object.
ListView listView= getListView();
Adapter medicineListAdapter = new ArrayAdapter<String>(
Options.this, android.R.layout.simple_list_item_1, myHistory);
listView.setAdapter(medicineListAdapter);
Add this and in Class implements onItemClickListener .This refer that onItemClick method.

onListItemClick(ListView l, View v, int position, long id)
position Corresponding your item of myHistory
you can judge position to do something :
switch (position) {
case 1:
Intent a = new Intent("show Item 1's corresponding page");
//--startActivity(a);
and so on...

Related

Disable GridView items on click

I have a GridView that is generated dynamically from SQLite database entries. An activity is started when a user taps on one of the GridView items. During the time from the tap and the activity launch, there is a split second where the user can rapidly tap other Gridview items which initiates their onItemClickmethod. Is there a way so all the GridView items onItemClick methods are disabled after selecting one?
Here is the code:
gridView = (GridView) findViewById(R.id.gridView);
nautsList = db.getAllNauts();
nautsGridAdapter = new AwesomenautGridViewAdapter(this, R.layout.gridview_item, nautsList);
gridView.setAdapter(nautsGridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
//do stuff
Intent intent = new Intent(AwesomenautSelectionActivity.this, AwesomenautSoundActivity.class);
startActivity(intent);
}
});
I would use this simple solution. It is successfully used in our apps.
Make a global boolean itemsLocked and set it to true as soon as you click. Set it back to false just before startActivity. Finally, in method onItemClick add
if (itemsLocked) return;
EDIT: method onItemClick
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
if (itemsLocked) return;
itemsLocked = true;
//do stuff
Intent intent = new Intent(...);
itemsLocked = false;
startActivity(intent);
}

How do I replace an item in a listview?

I have a listview which is populated by an array adpater. A user starts on activity a and after clicking an item in the listview is taken to activity b where they can edit the item they clicked. The edited item from B is sent back to A through an intent after the user returns to A. I want the original item clicked in A to be replaced with the data received from the intent from B.
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
// setListAdapter(adapter);
final ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;
Bundle fromedit = getIntent().getExtras();
if (fromedit != null) {
String edit = fromedit.getString("BENG");
int ps = fromedit.getInt("POSITION");
}
//onclicklistener for the listview
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Notes.this, EditNote.class);
intent.putExtra("KEY", values.get(position).toString());
intent.putExtra("POSITION", position);
startActivity(intent);
}
});
Thanks!
In your original activity you need to keep an int variable referring to the selected item index on the list. So your onItemClick() would look like that:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentSelected = position;
Intent intent = new Intent(Notes.this, EditNote.class);
intent.putExtra("KEY", values.get(position).toString());
intent.putExtra("POSITION", position);
startActivity(intent);
}
When you return from the activity where you modify the data you need to update the item of your values list and call adapter.notifyDataSetChanged().
Have you tried to update your list by calling mList.set(index, Object); and then refreshing the Adapter to update ListView displayed data?
You can use the ArrayList#set() method, thus if your 'values' dataset is an ArrayList.
The java.util.ArrayList.set(int index, E element) replaces the element at the specified position in this list with the specified element.
modify your code as follows:
//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;
Bundle fromedit = getIntent().getExtras();
if (fromedit != null) {
String edit = fromedit.getString("BENG");
int ps = fromedit.getInt("POSITION");
values.set(ps, edit);
adapter.notifyDataSetChanged();
}

Listview Search issue

I have a listview that working perfet.Today I added a search function to the listview using this code
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
The problem: I have 114 items on my listview and the selected item depends on the position, when I do search and press on the item that I found it will return the position 1, I want to return the position of that item before the search.. not the new position, is there anyway to solve it?!
Nope, it will return the position of the item based on the current lenght of your list view/adapter.
Why would it matter?
If you want to start a different activity based on the item clicked, there are many ways to do it. Using the position in the list to choose the activity works ONLY when the positions are fixed, which is not your case, since the user can filter the items.
Instead, start the activity based on the content of the item clicked.
Say for instance, your listview is populated using the following items:
public static final String [] PLANETS = {
"Mercury",
"Venus",
"Earth",
"Mars",
"Jupiter",
"Saturn",
"Uranus",
"Neptune",
};
Using the following ArrayAdapter:
mAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, R.id.text1, PLANETS);
Then you can edit your OnItemClickListener to start the activity based on the actual planet selected, not the position selected.
private AdapterView.OnItemClickListener mOnPlanetOnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int iistPosition, long l) {
//Notice I don't get the value from the String array
//Rather, I tell the adapter to give me the text from the selected item.
String planet = mAdapter.getItem(iistPosition);
Intent newActivity = new Intent(Example.this, NextActivity.class);
newActivity.putExtra("planet", planet);
}
};
If you are using a custom adapter it's even easier.
EDIT It is unfortunate that because of the way your mp3 files are named you must depend on the list position to get appropiate file.
In that case you could try a few workarounds, for instance:
If your list view is populated with a set ArrayList or just a List, you could first get the text of the item selected, and then get the actual array position based on the text of the item selected.
Like this:
private AdapterView.OnItemClickListener mOnPlanetOnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int iistPosition, long l) {
//get the text of the current item
String planet = mAdapter.getItem(iistPosition);
//get the position of this planet in the original unfiltered array
int actualListPosition = PLANETS_ARRAY.indexOf(planet);
//handle the click based on the actualListPosition
}
};
I hope that helps

Setting tag for listview item when using SimpleAdapter

I would like to store some data (let's say ID) in each ListView item and retrieve it later on clickItem listener.
I know how to do that if I create my own adapter. But is it possible to set a unique tag for each item if I am using SimpleAdapter?
Without overriding at least getView(), you will have trouble setting tags with every Adapter's view recycler.
However you can simply pass a custom layout with a TextView that has its visibility set to GONE or INVISIBLE and bind data from your List of Maps (List<Map<String, ?>>). Later you can easily fetch this TextView in an OnItemClickListener.
i think this will help you in case you want to identify imageview uniquely by tag like this
//add this in your getview() method
ImageView imageView = new ImageView(_context);
imageView.setTag(1);
and then on listview's/imageView's click check its tag like this
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Tag = (Integer) arg1.getTag();
}
}
There is a method inside SimpleAdapter for that. It's called ViewBinder. Try to include this code immediately after “SimpleAdapter adapter = new SimpleAdapter(this, Maps, R.layout.search, from, to);” and before “setListAdapter(adapter);” (Inside your onCreate Method).
#Override
public void onCreate(Bundle savedInstanceState) {
//...
String[] from = new String[] {"ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN"};
int[] to = new int[] { R.id.textView_1, R.id.textView_2, R.id.textView_3, R.id.textView_4, R.id.textView_5, R.id.textView_6, R.id.textView_7};
SimpleAdapter adapter = new SimpleAdapter(this, Maps, R.layout.search, from, to);
SimpleAdapter.ViewBinder binder = new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object object, String value) {
System.out.println("view= "+view);
System.out.println("view.toString()= "+ view.toString());
System.out.println("view.getId()= "+ view.getId()); //The return value will be decimal (not hexadecimal). You can have this value as a global string for later use.
System.out.println("view.getVisibility()= "+ view.getVisibility());
System.out.println("view.equals((TextView) view.findViewById(R.id. textView_5))= "+ view.equals((TextView) view.findViewById(R.id.textView_5)));
if (view.equals((TextView) view.findViewById(R.id.textView_5)))
{
TextView textView_five = (TextView) view.findViewById(R.id. textView_5);
//Change color/answer/etc for textView_5
}
//OR
if (view instanceof TextView) {
//Do stuff
return true;
}
return false;
}
};
adapter.setViewBinder(binder);
setListAdapter(adapter);
}//End of onCreate
setViewValue method will be called for each R.id.textView_1, R.id.textView_2, R.id.textView_3, R.id.textView_4, R.id.textView_5, R.id.textView_6, R.id.textView_7 that you have in “adapter”. The setViewValue method will be called each View/each time one of the above R.id’s is being drawn.
Then, when the user clicks on one of the ListView items and u want to change it, override onListItemClick Method.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (v.equals((TextView) v.findViewById(R.id.textView_5)))
{
TextView textView_five = (TextView) v.findViewById(R.id. textView_5);
textView_five.setText(“stuff”);
//Change color/answer/etc for textView_5
}
}

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...

Categories

Resources