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")
}
});
Related
I have GridView which shows a list of thumbnails. After clicking on one of them I'd like to navigate to another activity with detailed view of a corresponding "thing".
How should I store some additional data/identifiers such that on click I can pass it to the detailed activity? By default I only get position and id. I'd like to somehow store my custom identifier which I use to query external services for details.
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent intent = new Intent(this, MovieDetails.class);
intent.putExtra(MY_ID, <some_extra_ID>);
startActivity(intent);
}
});
EDIT:
For example, I have a dynamic list of dishes with only photos of that dish (using GridView). When user clicks on one of them I want to show a detailed view with a recipe and comments.
For that I need to pass name of that dish to load information in the detailed view.
Actually it is as good as a click listener can get as it passes the view, position and id. However you can improve the data you get by defining a unique item id inside your adapter.
If you are using an ArrayAdapter or SimpleAdapter the id is usually the same as position but for a CursorAdapter or SimpleCursorAdapter the id returns the row id of the table.
Now you can extend you adapter and return the desired id inside the getItemId method:
public class MyAdapter extends ArrayAdapter<MyItem>{
...
#Override
public long getItemId(int position) {
return myItems.get(position).myUniqueId;
}
}
this is my situation:
I want to pass a listener to a view generator for using it. but the problem is in my listener I want to use that View to get some data. some how twisted...
is that a way to pre-define a View like a interface that Listener should attach to?
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
//but I can not do this and use spinner cause it is not defined
String text = spinner.getSelectedStrings().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
};
generateSpinner(attributes, listener);
I'm working on MVC project in android and this issue come out from there, cause I should separate creation and Logic to View and Presenter. So my presenter force view to generate a spinner with given logic.
You have answered more than half of your question yourself. Make an interface like this:
public interface MyViewCallback
{
void run(View view);
}
Now, you can store a instance of this interface and call its run() method from your View's scope whenever you need to - for example,
MyViewCallback callback;
// ... on some action
callback.run(this);
You can create a setter for this callback and use it to register a callback.
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/
This question already has answers here:
How to create interface between Fragment and adapter?
(6 answers)
Closed 8 years ago.
I have a ListView Adapter in which are names, prices and ImageButtons (of Cancel) for every product(Listview row), Listview has its own Onclick Event which is used to edit clicked Product/Row. My question is how should I pass a number(position) of ImageButtons that are in this ListView back to a Fragment so i can delete that row. its been bothering me for quite a while. Here is the code
Code from Adapters Class receiptListAdapter ( i can paste whole code if necessary )
...
ImageButton test = (ImageButton)view.findViewById(R.id.imgBtnDelete);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test.setTag(position); // this is working and i get the position from the ImageButtons inside dynamic Clickable ListView
}
});
...
Code from Fragment ReceiptItemsFragment (Where i want to get that number)
...
public void deleteProduct(int number){
//note: this is working if am calling it from the fragment, but i need it to call from adapter
receiptItemArrayList.remove(number);
TextView txtTotalAmmount = (TextView) getView().findViewById(
R.id.txtReceiptTotalAmmount);
double totalAmmount = getTotalAmmount(receiptItemArrayList);
txtTotalAmmount.setText("Sum: " + String.valueOf(totalAmmount));
receiptListAdapter.notifyDataSetChanged();
}
...
I tried
like this ((ReceiptItemsFragment)context).deleteProduct(position);
but i get Cannot cast from Context to ReceiptItemsFragment
I tried it static but then I cant run the code from Fragment. Should I try to use Interface to pass data and how (i know only how to do that between fragments and activity)? any suggestions?
I'd suggest you let your Activity implement AdapterView.OnItemClickListener and add it as a Listener to your ListView. Inside the Activity:
listView.setOnItemClickListener(this);
And from the Activty, you can simply call the method on the fragment:
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id){
//something like this, to get the product id
deleteProduct(listView.getAdapter().getItem(position).getId());
}
I have a simple app where the user selects one of the US states and the state selected is to be used to list all of the counties in that state. In onCreate, I built an arrayadapter called Stateadapter, and set it to the spinner object "spinState". I then initialized a listener class StateOnItemSelectedListener. Outside of onCreate, I have the StateOnItemSelectedListener class that will read which State was selected in the spinner, and then perform the rest of the app's tasks.
I have two problems: when single stepping thru the code in debug mode, the "parent.getItemAtPosition(pos).toString" does not return the string value of the selected state (though numerous web examples suggest this should work).
Second, when running, the app fires the listener when going thru onCreate and all appears well until the user selects the spinner on the ui, and the app then does a force close.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinState = (Spinner)this.findViewById(R.id.spinState);
ArrayAdapter<String> Stateadapter = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item, array_spinState);
Stateadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinState.setAdapter(Stateadapter);
spinState.setOnItemSelectedListener(new StateOnItemSelectedListener());
}
public class StateOnItemSelectedListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View itemSelected, int pos, long id)
{ State = spinState.getItemAtPosition(pos).toString();
//Do Stuff base on State;
}
public void onNothingSelected(AdapterView<?> parent)
{ //Do nothing here
}
}
Try doing what they do in the Spinner Tutorial, they create the adapter in a different way, but eventually they use the same code to access to selected item and it works.
What is the error in log cat from the force close, and what getItemAtPosition does return?