I have a ListView in a Fragment where I need to be able to detect when an item in the ListView is selected. I need the list item to throw a flag or something along those lines so that a method in the Main Activity which houses the Fragments can detect whether or not the ListView was acted upon. I need a method in the Main Activity basically like this:
public void doSomething(){
if(Fragment ListView onItemClick is detected){
//--- do something
} else {
//--- don't do anything
}
}
The OnItemClickListener in the Fragment ListView that needs to indicate that it's been acted upon looks like this:
list_LV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor getPathCursor = (Cursor) list_LV.getItemAtPosition(position);
String cursorSDFStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("sdfdate"));
String cursorCalDateStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("caldate"));
String cursorURLStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("path"));
String cursorTitleStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("title"));
String cursorbodyStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("body"));
Intent slpI = new Intent("com.myapp.LISTVIDEO");
slpI.putExtra("SDFKey", cursorSDFStr);
slpI.putExtra("CalDateKey", cursorCalDateStr);
slpI.putExtra("PathKey", cursorURLStr);
slpI.putExtra("TitleKey", cursorTitleStr);
slpI.putExtra("bodyKey", cursorbodyStr);
startActivity(slpI);
}
});
You should follow the steps google outlined here http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
You can alternately use broadcasts or something like Otto http://square.github.io/otto/
Related
I have a problem that i am trying to solve using android to develop and app for a trivia quiz so i need to start a quiz based on the category chosen. The problem is as follows:
Question 1
I cant seem to figure out how to pass the item selected from a ListView i can pass what is selected using spinner but not a list selection.
private String getCategory(){
final String category[] =new String[1];
final ListView list = (ListView) findViewById(R.id.soloList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View View, int position, long id) {
category[0] =(String) (list.getItemAtPosition(position));
}
});
return category[0];
}
That is the part of the code is use and cant seem to get it to work and my question is how do i make it work? I call the method within main but nothing ever gets passed.
Thanks.
About Q1 :
You have function that return String it's ok but what's wrong that not made code work is ItemClickListener
First let me tell you about Interfaces in Java :
As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off. - link
The problem in this code is that you set kind of interface on each item click, but you function not wait for item click callback to return result !
the way you can handle is :
1: Create Interface for Callback when user select new item on listview
public interface category {
public void getCategory(String itemTitle);
}
2: set callback to you Activity Fragment or ...
public class ProjectList extends Fragment implements category
3: Override callback function
#Override
public void getCategory(String itemTitle) {
// do something with new item !
}
4: Call callback function when item selected
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View View, int position, long id) {
ProjectList.this.getCategory("newitem-String")
}
});
I am still stuck with this issue, can anyone help. It seems that my problem is that I cant update the data list. I have tried every solution that I've searched for on google etc.. but half the time i'm not even sure that I'm doing the correct thing.
I've used the onResume() to call notifyDataSetChanged, it didn't work. I've tried putting a refresh method into the adapter which i then called in OnResume(). Again it didn't work. Some people suggest clearing the adpater (adapter.clear();) in onResume and then using the addAll() function to relist the data but nothing works.
There has to be a simple solution to this. I have literally been stuck on this for 2 days now. very frustrated.
Here's my Fragment code again...
enter code here
public class SavedAppFragment extends ListFragment {
private static final String TAG = "AppClicked"; //DEBUGGER
private ArrayList<App> mSavedApps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Populate the ArrayList
mSavedApps = SavedAppData.get(getActivity()).getApps();
AppAdapter adapter = new AppAdapter(mSavedApps);
setListAdapter(adapter);
}
//LIST ITEM CLICKED: /*Control what happens when list item is clicked: I.E. Load up a quiz while putting an EXTRA key containg the package name of the App to be launhced should the user get the question correct */ #Override public void onListItemClick(ListView l, View v, int position,long id) { //Return the crime for the list item that was clicked App c = ((AppAdapter) getListAdapter()).getItem(position); Log.d(TAG, "was clicked");
//Start the Activity that will list the detail of the app
Intent i = new Intent(getActivity(), Quiz_Activity.class);
String name = c.getPackage();
i.putExtra("packagename", name);
startActivity(i);
}
private class AppAdapter extends ArrayAdapter {
private ArrayList<App> mSavedApps;
public AppAdapter(ArrayList<App> apps) {
super(getActivity(), 0, apps);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//If we weren't given a view, inflate one
if (null == convertView) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_app, null);
//((AppAdapter) getListAdapter()).notifyDataSetChanged();
}
((AppAdapter) getListAdapter()).notifyDataSetChanged();
//Configure the view for this crime
App c = getItem(position);
TextView nameTextView = (TextView) convertView.findViewById(R.id.app_name);
nameTextView.setText(c.getName());
// nameTextView.setText(applicationInfo.loadLabel(packageManager));
TextView packageTextView = (TextView) convertView.findViewById(R.id.app_package);
packageTextView.setText(c.getPackage());
CheckBox appCheckBox = (CheckBox) convertView.findViewById(R.id.app_checked);
appCheckBox.setChecked(c.isChecked());
//Return the view object to the ListView
return convertView;
}
}
}
THANKS!!!
When you return to Activity B, the previous Activity B hasn't been destroyed. Thus, it skips the onCreate. Move all of the stuff you want to make sure happens every time into the onResume. I think you want to make your Adapter a class variable (I'll call it mAdapter) in onCreate, and add code that will get data from the list directly. If you need to do something, put a "refresh" function in the adapter. I'm assuming you have a custom Adapter, because I've never heard of AppAdapter. If you don't, then extend AppAdapter and add that functionality. Thus, your onCreate should look like this:
mAdapter = new AppAdapter(mSavedApps);
setListAdapter(mAdapter);
Your onRefresh could update the data contained in the adapter by some new update function, like so:
mAdapter.update(SavedAppData.get(getActivity()).getApps());
I'm new to Android. I'm working on a listView-based app: you have a main menu, when you click an item, a new activity starts with another menu; when you click again, a new activity starts with the content you selected. Since I've quite a lot of menu items, I've to create a listener which handles all possible cases, so I've something similar:
#Override public void onItemClick(AdapterView<?> listAdapter, View v, int position, long id) {
String text = ((TextView)v).getText().toString();
//main menu
if (text.equals(K.getStringById(K.ID_MAIN_THEORY))) {
...
} else if (text.equals(K.getStringById(K.ID_MAIN_EXERCISE))) {
...
}
else if (text.equals(K.getStringById(K.ID_MAIN_TABLES))) {
...
}
//here other menus' items: lots of items
...
//back item
else if (text.equals(K.getStringById(K.ID_BACK))) {
activity.finish();
}
Intent i = new Intent(...);
startActivity(i);
}
* K is a class that holds ids' references
There's a way I can avoid hard-coding listener behavior?
** PS: the lists' TextViews don't render properly: text appears light grey, not black! O.o
It's more useful to use the position rather than the view to switch the action of the click event. Your ListView should be populated from some sort of List, therefore when the onClick fires, giving you the position, you can reference that position in the List to know what was clicked.
If you want to click on item and in result it goes to another activity, for example if you have three item and when you click on item A it will redirect you to activity A and if B then to B and so on,
lstview.setOnItemClickListener(new OnItemClickListener()
{
private String input;
public void onItemClick(AdapterView<?> v, View arg1, int index,long arg3)
{
if(index==1)
{
Intent intnt=new Intent(v.getContext(),A.class);
startActivity(intnt);
}
else if (index==2)
{
Intent intnt=new Intent(v.getContext(),B.class);
startActivity(intnt);
}
else
{
Intent intnt=new Intent(v.getContext(),C.class);
startActivity(intnt);
}
}
}
Here in this case you are going to different activities on selection the items in a list view, put your comments for further query.
I solved this way: I think it's pretty good.
//This in K class, where MAPPED_HIERARCHY is a static field
static void activity(android.app.Activity a) {
MAPPED_HIERARCHY = new HashMap<String, ArrayList<String>>();
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.app_name), K.array2list(a.getResources().getStringArray(R.array.menu_main)));
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.main_theory), K.array2list(a.getResources().getStringArray(R.array.menu_theory)));
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.main_exercise), K.array2list(a.getResources().getStringArray(R.array.menu_exercise)));
....
}
static ArrayList<String> getArrayListByString(String string) {
ArrayList<String> copy = new ArrayList<String>(MAPPED_HIERARCHY.get(string).size());
for (String s : MAPPED_HIERARCHY.get(string))
copy.add(s);
return copy; //defensive copy
}
//This in my listener class
#Override public void onItemClick(AdapterView<?> listAdapter, View v, int position, long id) {
String text = ((TextView)v).getText().toString();
ArrayList<String> params = K.getArrayListByString(text);
Intent i = new Intent(...);
i.putExtra("params", params);
activity.startActivity(i);
}
I have a map which links an arraylist containing the menu items with the string wihich causes the menu to be displayed; on the click event, I simply retrieve the arraylist according with the selected item's text.
I try to get the value of a selected Item within a custom adapter on a listview. I try this with following code:
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
View curr = parent.getChildAt((int) id);
TextView c = (TextView)curr.findViewById(R.id.tvPopUpItem);
String playerChanged = c.getText().toString();
Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();
}
At the beginning, if I click, the values are good, but once I scrolled and I click on another Item, I get the wrong value of that clicked item... Any idea what is causing this?
The parameter v is the current row. so use:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);
String playerChanged = c.getText().toString();
Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();
}
(Or you could use getChildAt(position) but this would be slower.)
Understand you might be able to simplify this more depending on your layout.
Just Small Change is Required
TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);
Since you are using custom view you need to pass the View argument in your OnItemClickListener then you need to use that value to get the Details of TextViews present in that
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(ListOfAstrologers.this,AstroProForUser.class);
i.putExtra("hello",adapter.getItem(position).getUsername() );
startActivity(i);
}
});
Here username is a string field declared in a class and you must over ride getItem() method in adapter class to get the details of inflated row when you click.
I dont have much experience but I think if you want to pass a variable from an OnClick (which is an anonimous class) to the outside of the onClick and to the other activity, you want to pass it via Intent intent.putExtra... (it's quite easy)
Otherwise you might end up using "public static" variable, which might be a memory leak...
i hava got the code below. i want to start an activity when i click on a single item on the list. however when i do nothing happens. I alsow want every item to refer to the same intent calld "com.whiskey.app.view" and send a id variable that was given by the sql query. I browsed trough the code several times but i cant seem t get it to work.
public class MainScreen extends Activity implements OnItemClickListener{
public ListView whiskeylist;
public String[] DataArryWhiskey;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start db view of whiskey
DBConfig whiskeyrows = new DBConfig(this);
whiskeyrows.open();
DataArryWhiskey = whiskeyrows.getDataInArray();
whiskeyrows.close();
whiskeylist = (ListView)findViewById(R.id.listofWhiskey);
whiskeylist.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , DataArryWhiskey));
// End db view of whiskey
}// end onCreate
// catch itemclick event from the main list.
public void onItemClick(AdapterView av, View v, int position, long l)
{
// TODO Auto-generated method stub
String[] listitem_data = DataArryWhiskey[position].split(","); // break passed sting into a array comma seperated
Bundle passingitems = new Bundle();
passingitems.putString("whiskey_id", listitem_data[0]);
Intent currentintent = new Intent("com.wiskey.app.view");
currentintent.putExtras(passingitems);
startActivity(currentintent);
}
Although the above answers work, I think that the problem in your current implementation is that you don't call:
whiskeylist.setOnItemClickListener(this);
I think this should do the work!
If your activity only cotains this ListView, you should use a ListActivity.
These are made specifically for activities that only contain lists.
One of the methods for ListActivities is onListItemClick. That one is specifically for clicking on items in lists, as the name says.
The reason your code doesn't work is because onItemClick isn't generally used for clicking in Lists, but for clicking other objects in Activities.
Try changing your code based on the samples here: ListActivity
Derive your class from ListActivity and remove the implements OnItemClickListener
Put below code in onCreate
setListAdapter(whiskeylist);
And then have this as your onItemClick
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String[] listitem_data = DataArryWhiskey[position].split(","); // break passed sting into a array comma seperated
...your code....
startActivity(currentintent);
}
Also refer to:
ListActivity
ListView
You have not added listener for click actions, try adding:
whiskeylist.setOnItemClickListener(this);
at the end of onCreate
You might also write anonymous OnItemClickListener as in here:
http://developer.android.com/resources/tutorials/views/hello-listview.html