Extract string from custom object on listView item click - android

I have created my own class (Course) to hold multiple strings and pass the object to populate a list using ArrayAdapter and AsyncTaskLoader (the strings are being filled from a JSON api).
Let's say I have these 3 Strings inside my class:
private String mCourseTitle;
private String mTime;
private String mTrainer;
public String getCourseTitle() {
return mCourseTitle;
}
public String getTime() {
return mTime;
}
public String getTrainer() {
return mTrainer;
}
I want to set up an item click listener inside my Fragment that when tapped, shows a toast message with only the Course Title String and I'm kinda stuck...
How do I extract the title to show it in a Toast from the clicked item?
// Create a new adapter that takes an empty list of days as input
mAdapter = new DayAdapter(getActivity(), new ArrayList<Day>());
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
listView.setAdapter(mAdapter);
//on item click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Show the title
Toast.makeText(getContext(), Title, Toast.LENGTH_SHORT).show();
}
});

Here is the answer
//on item click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Course yourCourse = yourList.get(position);
String yourCourseTitle = yourCourse.getCourseTitle();
// Show the title
Toast.makeText(getContext(), Title, Toast.LENGTH_SHORT).show();
}
});

Related

ListView onItemClick get row from Database?

Im fairly new to Android development. I have a custom ListView that is populated with data from a DatabaseTable. The ListView-items consist of CATEGORY, DATE, TITLE and AMOUNT.
private class lvIncomeListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = ???;
displayItemClicked("List-item Clicked:",item);
}
}
Now, I want to add an OnItemClickListener to the ListView, so that when an item in the list is clicked, a DialogFragment will display the data from that particular row in the Database that is shown in the ListView, like
"Item Clicked: Category: food, Date: 17/10/25, Title: Restaurant, Amount: 20sek"
... how is the best way to go about to achieve this?
Since you have a custom adapter, I assume you have a custom class where you store your list data maybe like this:
public class YourListData {
private String catagory;
private String date;
public YourListData(){
}
public void setCatagory(String cat){ this.catagory = cat; }
public void setDate(String date){ this.date = date; }
public String getCatagory(){ return this.catagory; }
public String getDate() { return this.date; }
}
Now in your onItemClick method in your Activity get the list data like this:
mYourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
YourListData data = (YourListData) parent.getItemAtPosition(position);
String cat = data.getCatagory();
String date = data.getDate();
//...
//Send data to your fragment
}
});

How to get value of a ListView item, populated through FirebaseListAdapter

I have a ListView that I populate using the FirebaseListAdapter. Now I want the OnItemClickListener to show the value of the item clicked (the text displayed on the item) in a Toast.
ListView listView;
ListAdapter listAdapter;
mFirebaseRef = new Firebase("https://<firebase root ref>/posts");
mFirebaseQuery = mFirebaseRef.orderByChild("author_id").equalTo(id); //`id` is a variable defined earlier
listAdapter = new FirebaseListAdapter<Post>(this, Post.class, android.R.layout.simple_list_item_, mFirebaseQuery) {
#Override
protected void populateView(View view, Post post) {
String postTopic = post.getTopic();
((TextView) view.findViewById(android.R.id.text1)).setText(postTopic);
}
};
listView = (ListView) findViewById(R.id.postsList);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String topic = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(), "List Item Value: "+topic, Toast.LENGTH_LONG).show();
}
});
Instead of returning the text displayed on the item (as is in the case an ArrayAdapter is used), String.valueOf returns some reference to the model class I use - Post.class.
The output is something like this: com.example.android.model.Post#a1e1874
Can anybody tell me how to get the value of the list item in this case?
AdapterView.getItemAtPosition() returns a Post object, so:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Post post = (Post)parent.getItemAtPosition(position);
String topic = post.getTopic();
Toast.makeText(getApplicationContext(), "List Item Value: "+topic, Toast.LENGTH_LONG).show();
}

Getting ID value when clicking on listview

I'm having some trouble getting the correct id value when clicking on the listview.
I made a custom adapter since I'm drawing from SQLite data, I get the right text back but when I click on a row, I get a 0 index id back, which is not what I want.
I'm also using Sugar ORM, so I'm not sure if that requires some special work from me to get the id field.
I'm not sure what I should show you in terms of code, so whatever you think will help you, let me know and I'll post it.
Thanks
BoardArrayAdapter adapter = new BoardArrayAdapter(this, boards);
setListAdapter(adapter);
ListView lv = getListView();
registerForContextMenu(lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Board ID " + id, Toast.LENGTH_SHORT).show();
}
});
You need to override the getItemId() method in your adapter.
According to the SugarORM docs you can call getid()to return the db id.
ArrayList<Object> data;
#Override
public long getItemId(int position) {
return data.get(position).getid();
}
This is how I am using on my project (with SQLite and CustomListView).
getData method
public void getData(View view, long id)
{
//storing the ID into a public static variable and converting to int
CLIENTE_ID = (int)id;
//When the user touches on the field in the listview, I get the touched field's name and email
TextView textViewnome = (TextView) view.findViewById(R.id.tv_cliente_nome);
TextView textViewemail = (TextView) view.findViewById(R.id.tv_cliente_email);
//Stores both name and email of the touched field
String nome = textViewnome.getText().toString();
String email = textViewemail.getText().toString();
//store into static variable
CLIENTE_NOME = nome;
CLIENTE_EMAIL = email;
}
within onCreate:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
getData(view, id);
Log.d("myClass", "ID: " + view.getId());
}
});
I hope it helps! :)

How to access listview items generated by arrayadapter

I have tied my application to Firebase database and after being able to display them I also want to be able to select them and access their textview values. However .getValue() does not work for views. I know that my code is very messy and my selector is only working one way, but can you help me to find out what is going on. I will add a screenshot to make things more clear. At the moment when clicking on one of the items int num = Integer.parseInt(text) gives an error and the app will crash because the value I get from view is "Android.widget...", not what I want to get.
Screenshot pic:
Orders.java
public class Orders extends ActionBarActivity {
public final static String TOTAL_SUM = "com.nordscript.checkmate.SUM";
// Declare the UI components
private ListView foodList;
// Declare an ArrayAdapter that we use to join the data set and the ListView
// is the way of type safe, means you only can pass Strings to this array
//Anyway ArrayAdapter supports only TextView
private ArrayAdapter arrayAdapter;
private Firebase ref;
private Orders activ;
private ArrayList<String> dishes;
public int total;
#Override
protected void onCreate(Bundle savedInstanceState) {
activ = this;
dishes = new ArrayList<String>(20);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
// Initialize the UI components
foodList = (ListView)findViewById(R.id.listView1);
// Create a reference to a Firebase location
ref = new Firebase("https://xxxxxxxxxx.firebaseio-demo.com/Restaurants/Restaurant 2/Tables/Table 2/Orders");
// Read data and react to changes
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
Map s = snapshot.getValue(Map.class);
dishes.add(snapshot.getName() + " " + ((Map)snapshot.getValue(Map.class)).get("Price"));
Log.i("Test", dishes.toString());
arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());
// By using setAdapter method, you plugged the ListView with adapter
foodList.setAdapter(arrayAdapter);
}
#Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { }
#Override public void onChildRemoved(DataSnapshot snapshot) {
Map s = snapshot.getValue(Map.class);
dishes.remove(snapshot.getName() + " " + ((Map)snapshot.getValue(Map.class)).get("Price"));
Log.i("Test", dishes.toString());
arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());
// By using setAdapter method, you plugged the ListView with adapter
foodList.setAdapter(arrayAdapter);
}
#Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { }
#Override
public void onCancelled(FirebaseError arg0) { }
});
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = view.toString();
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.orders, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void toPayment(View view) {
Intent pay = new Intent(this, PaymentMethod.class);
pay.putExtra(TOTAL_SUM, total);
startActivity(pay);
}
}
What i understand from your question : Suppose when you click on 3rd item i.e "pudding 8", you want this value "pudding 8"(textview value). right??
If that so than you just have to get values from your ArrayList which you pass to the adapter on first place with the help of position attribute inside your setOnItemClickListener like this :
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = dishes.get(position);
// do what you want to do with this value.
}
});
Change your onClickListener() like that:
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = (String)parent.getItemAtPosition(position);
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
Or you can use SimpleAdapter for displaying string and integer values separately using two textviews in a separate xml layout. Using that you can get values on onclick() in a better way.
You need to gettext of that particular view, view.getText().toString();
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = view.getText().toString();
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
It may help you, but it is bad way:
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) arrayAdapter.getItem(position);
String[] split = item.split(" ");
int num = Integer.parseInt(split[1]);
total += num;
}
});
But it is very urge...
As for me, you need to extends Adapter, to collect into it your custom items, and after clicking gets it and takes integer value you need.
I know this might become a little too late but, hope this
helps someone who was looking for similar solution to Custom ArrayAdapter with multiple values.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListItems item = (ListItems) parent.getItemAtPosition(position);
System.out.println("Item: "+item.getName());
}
});

how to get position of clicked item in OnClickListener of Listview?

I want to get selected listview item onclicked listner of listview.
Right now I have implemented onItemClickListener but when I click on an item text then it is raised. I want to raise it on a listview row click.
Any idea how to achieve this? To get the text value of the list onClick listener?
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = lv1.getAdapter().getItem(position).toString();
//display value here
}
});
Try using this code.
lv1.setOnItemClickListener(new OnItemClickListener() { ![enter image description here][2]
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = lv1.getItemAtPosition(position).toString();
//display value here
}
});
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos = parent.getPositionForView(view);
Toast.makeText(this,pos + "",Toast.LENGTH_SHORT).show();
}
If your ListView items were populated from an array words using an ArrayAdapter (which is hopefully) and implemented using a class Word with kind of this constructor:
public class Word {
private String mValueA;
/** Image resource ID for the word */
private int mAudioResourceId;
/*
* Create a new Word object.
*/
public Word(String valueA, int audioResourceId) {
mValueA = valueA;
mAudioResourceId = audioResourceId;
}
/*
* Get the default translation of the word
*/
public String getValueA() {
return mValueA;
}
/**
* Return the audio resource ID of the word.
**/
public int getAudioResourceId() {
return mAudioResourceId;
}
}
And then you can set setOnItemClickListener to access clicked item for example to play audio defined in array for this list item.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//like this:
Word word = words.get(position);
//and use this position to play the audio from the array
//corresponding to its item
mMediaPlayer = MediaPlayer.create(SomeActivity.this, word.getAudioResourceId());
mMediaPlayer.start();
}
});
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
int pos = (int) adapterView.getPositionForView(view);
Toast.makeText(MainActivity.this, pos, Toast.LENGTH_SHORT).show();

Categories

Resources