Update ListView within Fragment from DialogFragment - android

I have a ListView in Fragment, in which I want to add new item. DialogFragment is used to enter new item and on pressing "Yes" the item is dynamically added to the ListView. I have tried many solution but I cannot get it to work.

I will answer my own question.
In your Activity that implements interface defined in your DialogFragment
public void onCreateMatchDialogPositiveClick(DialogFragment dialog , String itemsToAdd) {
//Your Fragment Class containing listview to be updated
MyListViewFragmentClass fragment = (MyListViewFragmentClass) getSupportFragmentManager().findFragmentById(R.id.myListview);
if(fragment != null){
//fragment is available
fragment.addItemToListView(itemsToAdd);
}
}
Then in your fragment containing listview to add item dynamically
public void addItemToListView(itemToAdd){
matchList.add(itemToAdd); //Add item to your dataset
adapter.notifyDataSetChanged();//Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh
}

Related

fetch and store data in recycler view from other activity selected list items in android

how to store only selected item list data in recycler view from other activity list.
i used this code -- successfully select data but don't know how to add only selected data items in new activity recycler view -
i used this code snippet ite working fine-
//
https://en.proft.me/2018/03/3/multi-selection-recyclerview/
StringBuilder stringBuilder = new StringBuilder();
for (ExcercisesSelectedModel.DataBean data : getList()) {
if (selectedIds.contains(data.getId()))
stringBuilder.append("\n").append(data.getName());
Change
public interface OnClickAction {
public void onClickAction();
}
to
public interface OnClickAction {
public void onClickAction(Item item);
}
In adapter class, on item click
receiver.onClickAction(item);
In Activity class
private List<Item> selectedItem = new ArrayList()
public void onClickAction(Item item) {
selectedItem.add(item);
}
Now use this selected item list in new activity.
Edit: Don't forget to use or rename the interface to Callback, something along the lines of ActivityCallback or OnClickCallback.
This is for the sake of naming conventions.
A simple flag isSelected in parent list will save your day.
So whenever user select/unselect the item just change the value of isSelected flag to true or false.
Now you have a final list from which you can easily identify selected items, simple store in separated list named selectedItemList.
At last use the selectedItemList and fill your Recycleview. Hope it make sense.

How to show JSON data in fragments?

I have four swipeable fragments on an activity in tabbed view mode.Each fragment should show JSON data from an API.
There are two problems
The first problem is that only in first fragment I am able to get the data.
And the second problem is that when swiping to next fragment I lost the data received in the first fragment.
I have four layouts for each of the fragment.
I am using custom listview to show the data.
*After creating fragment and getting theJSON data I am using custom list view to show it in the first fragment using aeroFirst method as below but I am not able to do the same in the other fragment. Creating fragments,JSON parsing and aeroFirst method are all in MainActivityclass *
snip of the code
private void aeroFirst(List<Details> mList) {
// layout = (LinearLayout) findViewById(R.id.linear);
for (Details bean : details) {
final String urlChar = bean.getUrl();
if (bean.getResType().equals("Videos"))
{
ListView listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, mList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + urlChar, Toast.LENGTH_SHORT)
.show();
There must be an activity behind all four fragments, right? Store the values in that activity so that all four fragments can access the JSONs. This might not be the best in style, but the other solution involves saving it into shared preference or similar approach.
Another way to do this is to load everything in the activity, and then put the JSONs into arguments as bundles for each fragment.

Programmatic fragment within fragment within viewpager duplication

I have a very simple ToDo list app with multiple categories the user can add an item to. The architecture looks something like this:
http://i.imgur.com/WA3dtcU.png
I am using a ViewPager and each view is a fragment that I instantiate in the ViewPagerAdapater:
public Fragment getItem(int i) {
ToDoCategoryModel cat = categories().get(i);
ToDoCategoryView view = ToDoCategoryView.newInstance(cat);
return view;
}
Within each of these category the user can add new Item Fragments to a Linear Layout.
A very strange thing happens though. I start off on Category 1 (C1) Which currently has 1 Item in the list. Then scroll to C2 then scroll again to C3. Then I scroll back to C2. The ViewPager asks my ViewPagerAdapter to re-create C1 as it was destroyed after having scrolled 2 pages away from it. This is fine, I just create a brand new fragment (as the code above shows). However, when I now scroll back to C1, instead of 1 Item being shown (as you would expect) there are 2 items shown. They are a duplicate of each other.
The code I use to add the Item fragment to the Category fragment is:
public void addToDoItem(ToDoItemModel model) {
ToDoItemView newItem = ToDoItemView.newInstance(model, this);
getChildFragmentManager().beginTransaction().add(_linearLayout_items.getId(), newItem, "sameTag"+count++).commit();
}
If I change this code to add new TextView instead of fragments:
public void addToDoItem(ToDoItemModel model) {
ToDoItemView newItem = ToDoItemView.newInstance(model, this);
TextView tv = new TextView(getActivity());
tv.setText(newItem.getModel().getName());
_linearLayout_items.addView(tv);
}
It works fine! There are no duplicate items shown.
So what is wrong with adding fragments dynamically using the child fragment manager within a view pager?
Thanks.

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.

ViewPager updates listView in fragment B from a fragment A

I have a ViewPager with two Fragments. On the first one, there are buttons (it is a menu) and they represent different categories. On the second one, it is a listView which display data.
I am looking for a way to change the data to display on the listView when the user click on one of the menu items.
For example : the user click on the menu item 1 (fragment 1), the listView on the fragment 2 have to be updated with the corresponding data.
I read the documentations from Google Android developer about fragments but I couldn't work it out, I didn't find a solution to my problem.
Maybe I'm missing something ?
EDIT : I tried to clear my ListView by clearing the list of data (ArrayList> listItems) with listItems.clear(). I didn't find how to do adapter.clear(), it seems that this method doesn't exist in the class Adapter.
So to summarize : I created an update method in my fragment which contains the ListView (Fragment2). I called it through a callback method in the main activity, that part seems to work (I checked it with debug mode).
In the update method of my Fragment 2, I clear data with listItems.clear() and then the OnActivityCreated() of the fragment is executed. In it, there is the call of my thread which download data and then it create the ListView in OnPostExecute.
Here is a sample of my code (fragment2) :
// After data are ready
lvListe = (ListView) getView().findViewById(R.id.lvListe);
lvListe.setSelected(true);
lvListe.setScrollingCacheEnabled(false);
adapter = new LazyAdapter(getActivity(),
getActivity().getBaseContext(), listItems,
R.layout.affichageitem, new String[] { "image", "title",
"subtitle" }, new int[] { R.id.img_title,
R.id.titre_main, R.id.soustitre_main });
lvListe.setAdapter(adapter);
lvListe.setClickable(true);
lvListe.setOnItemClickListener(onItemClickListener);
// Update method :
public void update(String requete, String type)
{
this.type = type;
this.requete = requete;
listItems.clear();
}
The way that I would probably do it is to create a callback method in the Activity hosting the ViewPager and also a method in the second Fragment to update the data.
Then you would call it like:
class Fragment1...
{
...
callBackUpdate(data);
}
class Activity...
{
...
public void callBackUpdate(String data)
{
Fragment2.update(data);
}
}
class Fragment2...
{
...
public void update(String data)
{
//do whatever
}
}
The developers page shows how to create a callback method to the Activity.
edit: Actually that's how the Developer's page says to do it. They create the interface OnArticleSelectedListener for the callback.
edit: I'm assuming you are using this library for the LazyLoader: https://github.com/thest1/LazyList
If so, then you can just add the method to clear the data yourself. To do so, add a method like this in ListAdapter:
public void clear()
{
data = new String[](); //depends on what data is, if it's a List then just call data.clear() for example
imageLoader=new ImageLoader(activity.getApplicationContext()); //clear the images
notifyDataSetChanged(); //notify the adapter that the data has changed
}
This might not exactly fit how you currently have it, but you should get the idea.
Try using something known as a FragmentTransaction manager at http://developer.android.com/reference/android/app/FragmentTransaction.html
and also the FragmentManager http://developer.android.com/reference/android/app/FragmentManager.html
Check out some of the questions on stackoverflow related to FragmentManager and FragmentTransaction to figure this out. All you need to do is replace the fragment with a new one which is inflated by a particular xml

Categories

Resources