Passing Data from ListViews Adapter to Fragment [duplicate] - android

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());
}

Related

Inflating views on listview item

I have a listview. What I've implemented in that listview is that when user clicks a list item a 2 button view is inflated to replace the content of that list item like this:
This works fine but what I want is when I click the second list item the first one should come back to its original layout. Currently, it is like this:
This is my code implemented in onClick method of listview:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView planName = view.findViewById(R.id.planNameText);
TextView planDate = view.findViewById(R.id.planDateText);
ImageView planImage = view.findViewById(R.id.homePlanImageView);
planName.setVisibility(View.INVISIBLE);
planDate.setVisibility(View.INVISIBLE);
planImage.setVisibility(View.INVISIBLE);
RelativeLayout rl_inflate = (RelativeLayout)view.findViewById(R.id.rl_inflate);
View child = getLayoutInflater().inflate(R.layout.inflate, null);
rl_inflate.addView(child);
}
});
Thanks.
Maybe you need to initialice a boolean variable to check if is clicked or not and refresh all the views. I really recommend you to use a RecyclerView and use 2 viewHolders. If you want information about this check this. If you implement a recycler with 2 viewholder it will be easier than the way that you want to implement it, and you can use notifyDataSetChanged to refresh the recycler. Whatever, you will need anyways a boolean to check if is clicked or not.

Android Problems

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")
}
});

Get the listItem ID in a onClick method of SetOnClickListener method of an adapter?

I have an activity which lists objects from an array objects through a custom adapter. The row of this adapter contains several EditText's and a layout which is clickable and does the deleting of that object selected. My intention is the object can be updated by clicking on the item (which shows another activity) and deleting by clicking on the layout. So that, I have to implement the updating and the deleting by differents setOnItemClickListener's.
I have done the updating just setting an setOnItemClickListener to the listView of objects and sending the whole object to a new activity through putExtra and getIntent.
The problem is with the deleting. I have implemented an OnClickListener directly on the adapter, like this:
holder.layoutEliminar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Here call to an Async Task to delete the object but, what about t the id object???
}
That code goes fine when I click on the layout of the row but I don't know the way to obtain the id of the object selected in the listView. Does anybody know how??
Do not hesitate to ask me for more code or details.
Please excuse my English, not native.
You can set a tag for the view on your getView:
holder.layoutEliminar.setTag(theIdOfYourObject);
Note that View.setTag(Object tag) takes an Object as parameter (documentation). I will assume that you want to set the id of the object to delete as String for the tag.
And then, on your onClick
holder.layoutEliminar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout layoutEliminar;
// Retrieve your layoutEliminar from v
// ...
// Get the id of the object to delete from the tag
String id = (String) layoutEliminar.getTag();
}
};
I already did with the help of #Antonio. I didn't use Tag's, I have used the instruction getItem(position).getId() into the method onClick to refer the id of the object (don't know if it's the best and more efficient way to do). Like this:
holder.btnEliminar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("PedidosAdapter dd: ",String.valueOf(getItem(position).getId()));
//Async Task for deleting the object with that ID
}
});

How do I update ListView in another Fragment?

I have an Activity which holds a ViewPager with 2 Fragments. One fragment is for adding items to ListView and another fragment is holding the ListView.
I've been trying for almost 3 days now without any positive results. How do I update the other fragment's ListView from the first fragment?
I'm trying to call the method that updates ListView from the Activity that holds ViewPager but it doesn't work.
Calling the method from ViewPager activity :
#Override
public void onPageSelected(int position) {
library.populateListView(getApplicationContext());
aBar.setSelectedNavigationItem(position);
}
This is the populateListView method:
public void populateListView(Context context){
CustomListViewAdapter customAdapter = new CustomListViewAdapter(getDatabaseArrayList(context), getActivity());
if (lView != null)
{
lView.setAdapter(customAdapter);
}
customAdapter.notifyDataSetChanged();
}
However this doesn't work because the lView variable (ListView) is null because the fragment isn't shown at the moment when this is being called.
I am assuming that function populateListView() is a function of the Fragment containing the ListView. You are calling populateListView() on every call to onPageSelected. Should you not check what is the position that is being selected. Anyway the populateListView() method should be a public method of the Fragment containing ListView. And You Can Instantiate The Fragment from the Viewpager adapter in the Activity and than call this method. In That way the listView should not be null.
#Override
public void onPageSelected(int position) {
ListViewFragment frag=(ListViewFragment)adapter.instantiateItem(viewPager, 1);
//here adapter is the ViewPager Adapter and you must supply the viewpager that contains
//the fragments and also the position of the fragment to instantiate.
//For example 0 or 1 etc.
frag.populateListView(getApplicationContext());
aBar.setSelectedNavigationItem(position);
}
Understand Fragments
Please see this link. I have gone in great detail explaining the concept of fragments.
Pay particular attention to the definition of rootview:
public void onActivityCreared(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
// Do stuff on creation. This is usually where you add the bulk of your code. Like clickListners
// You can define this object as any element in any of your xml's
View rootview = inflater.inflate(R.layout.xml_the_fragment_uses container,false);
rootview.findViewById(R.id.your_id).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do something
}
});
}
In the above case I defined a button for an on click listener, but you can just as easily define a ListView along with its appropriate methods.
Alternate Solution
A second method could be using getView or getActivity (check the communicating with activity section).
For example:
ListView listView = (ListView) getView().findViewById(R.id.your_listView_id);
OR (more likely solution for your problem)
View listView = getActivity().findViewById(R.id.list);
Please read this post for additional information.
Good Luck.
To do this safely, you have to keep your listview data in a higher level Parent-Activity not the fragments. Make your MainActivityclass singleton class by making the constructor private and create a getInstance method that return the only initialized instance of your `MainActivity.
This will allow you to keep your data instance safe from being re-initialized or lost. Then, in onResume of your fragment re-set the data (get it from the MainActivity) to your listview adapter and call notifyDataSetChanged() method from the adapter instance.
This will do the trick.

Delete an item from the listview and refresh it on a button click in each row

Hi a am struggling with this part. I want to simply delete an item from the listview when the button on that row is clicked.
I have tried
holder.button.setText("End");
holder.button.setTag(position);
holder.button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) v.getTag();
app_details.remove(index.intValue());
notifyDataSetInvalidated();
}
});
But it's behavior is unpredictable I mean when click on the button on a row it delete the another item from the listview.
Any one have some idea?
Thanks
I have faced the same problem & finally get rid out of it. Have to tried
holder.button.setOnItemClickListener Follow the steps to do what you want:
Implement OnItemClickListener in your current activity class.
set button which delete item from list view to setOnClickListener.
Set list view to setOnItemClickListener listener in your anonymous inner class (e.g., in OnClickListener).
notifyDataSetChanged()
Call this Activity once again Using Intent.
here for Example: I take one list view listVw ->
holder.button.setText("End");
holder.button.setTag(position);
holder.button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your needed stuffs...
listView.setOnItemClickListener(this);
}
});
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
//Do your stuff here...
}
You want to uses an instance of the ArrayAdapter since that adapter has the remove method. Otherwise you will need to implement your own remove method and have you custom Adapter extend BaseAdapter. Here is an example of what methods you need to call to remove an item from the list and tell the Adapter to refresh the list.
m_adapter.remove(o);
m_adapter.notifyDataSetChanged();
You want to call notifyDataSetChanged() instead of notifyDataSetInvalidated(). Here is the difference ....
notifyDataSetChanged() - Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
notifyDataSetInvalidated() - Notifies the attached observers that the underlying data is no longer valid or available.

Categories

Resources