refreshing listView of a fragment from MainActivity - android

it is really strange, many people has asked this question but not even one useful answer
I have a MainActivity class
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
with 3 actionbar tabs (sections 1,2,3) each section has its own fragment in the package
public class FragmentA extends Fragment
public class FragmentB extends Fragment
public class FragmentC extends Fragment
in the FragmentA I have a listView with its arraylist adapter.
in the MainActivity I fetch some data and put it in the sqlite database.
as soon as new data are added to database I want to notify the listview that the dataset is changed and populate the new data
it sounds easy but I have really got stucked in that !
I just want to know how to do this refresh, rebuild, recreate ... what ever it is from MainActivity
if any one can help ? thanks

in your activity.
this.fragment.adapter.notifyDataSetChanged();

Hehe.
Is this the poor idea?
public interface INotifyDataChange {
public void notify(Object dataChanged); // Object stand for whatever you want. :">
}
You MainActivity
MainActivity {
public static INotifyDataChange notifier;
public void inSomeMethod() {
// do input data.
if (notifier != null) {
notifier.notify(dataWillBeAttached);
}
}
}
Your Fragment:
FragmentA or B, or C implements INotifyDataChange {
onCreateView() {
MainActivity.notifier = this;
}
#Override
public void notify(Object data) {
Toast.make(..., "I've changed data " + data.toString(), ...).show();
yourListView.notifyDataSetChanged(); // or anything like this.
}
}

The simplest is to use a Local Broadcast manager. developer.android.com/reference/android/support/v4/content/… You can register your UI to receive a broadcast which you can fire when the data has been saved in the database. When the UI receives this event you can notify your adapter to refresh the list view

Related

Pass Spinner Selected Items from Fragment to Activity [duplicate]

This question already has answers here:
Passing data between a fragment and its container activity
(16 answers)
Closed 5 years ago.
Do not understand fully fragment life-cycle.
Case:
Click FrameLayout from Activity to move to Fragment is working.
Problem:
In Fragment there are two spinners and one SubmitButton, when selected both spinner values, the clicking ofSubmitButton, should display those values from spinner back to the Activity's two Textviews . But, I am unable to do that.
My Solution:
I tried to use Intent, putExtras and then getExtras , but as we are in Fragment, Intent is not going to work for Fragment. Bundle also not helping.
P.S. Need someone who understand good Fragment's life-cycle. Read many posts from stackoverflow and other tutorials. Not found what I meant.
Do not want external libraries as such eventBus
Two ways you can do that
1) Casting getActivity() as your Activity and call the specific method and pass parameter.
public class MyActivity extends AppCompatActivity {
public void setData(String value){
// do whatever with the data
}
}
public class MyFragment extends Fragment{
public void someMethod(){
((MyActivity)getActivity).setData(your_data);
}
}
2) Create an interface and pass the value to activity.
public class MyActivity extends AppCompatActivity implements SpinnerListener{
#Override
public void onSpinnerItemSelected(String value){
// do whatever with the data
}
public interface SpinnerListener {
void onSpinnerItemSelected(String value);
}
}
public class MyFragment extends Fragment {
private SpinnerListener spinnerListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceOf MyActivity)
spinnerListener = ((MyActivity)context);
}
public void someMethod() {
if(spinnerListener != null)
spinnerListener.onSpinnerItemSelected(your_data);
}
}
Note: The safe method is using interface.

Communication between two adapters in android?

I have two views In a single activity StackView and Gridview and 2 corresponding adapters .when I clicked on StackView item it should flip the grid item in Gridview and vice versa?
// activity classs
public class SampleActivity extends Activity implements
OnGridChangeListener {
public void onCreate(bundle){
// replace this with your adapter class.
Adapter adapter = new adapter(this);
}
#override
public void OnGridChange(){
//here you go.
// write code to do what you want.
}
// interface to communicate with activity
public interface OnGridChangeListener {
public void OnGridChange()
}
// adaptor class
public class Adaptor extends "you apapter class to extend"{
OnGridChangeListener onGridChangeListener ;
public Adapter(OnGridChangeListener listener){
onGridChangeListener =listener
}
public getView(){
public void onclick(){
onGridChangeListener.OnGridChange("pass you data");
}
}
}
As per your question this is what i get -
You have a Activity with two independent views which has their own adapters. So when there is changes in one of the adapter you want it to be reflected into another adapter.
The simple solution for your query would be -
When there is a change in first adapter you reflect the change to the activity. after that call the function in the second adapter to reflect the change you want in second adapter.
For this you have to define an interface in first adapter and implement this is activity.
When the first adapter changes call the interface method and this will reflect in activity.
Then call method in second adapter to do the changes you want.
Code example -
MainActivity.Java
public class MainActivity extends AppCompatActivity implements FirstAdapter.callBackMethods {
FirstAdapter firstAdapter;
SecondAdapter secondAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstAdapter = new FirstAdapter(MainAtivity.this.getApplicationContext());
//do all the declaration and operation of first adapter. Pass context along with your required params.
secondAdapter = new SecondAdapter();
//do all the declaration and operation of second adapter.
}
//callback method of first adapter
#override
public void callback(){
//changes have been done in FirstAdapter and this methos is fired.
//now do do the changes in SecondAdapter as per req.
if(secondAdapter != null){
secondAdapter.reflectChanges();
}
}
}
FirstAdapter.class
I am taking example of recylerview adapter.
public class FirstAdapter extends RecyclerView.Adapter<FirstAdapter.ViewHolder>{
public FirstAdapter(Context context){
this.context=context;
}
/*
all the boilerplate codes and business logic
*/
//when you want to reflect the changes
callBackMethods callBackMethods = (callBackMethods) context;
callBackMethods.callback();
//this will fireup the implementation in the MainActivity.
public interface callBackMethods{
public void callback();
}
}
SecondAdapter.class
This is where the changes will be reflected.
public class SecondAdapter extends RecyclerView.Adapter<SecondAdapter.ViewHolder>{
/*
all the boilerplate codes and business logic
*/
public void reflectChanges(){
/*
This method will be called from the MainActivity. pass whatever params you want to pass from Activity and do the changes you want to do in the SecondAdapter.
*/
}
}
I hope this solves your problem. Happy coding...

keep data persistent between fragments

I am trying to build a wizard with the help of the ViewPager, in each step the user will input that data and at the end all data inserted should be presented to the user before final confirmation and send all data to the server.
What i would like to know are the following:
how can I keep data persistent so at the final fragment everything will be presented to the user? I would like to use a method that will be the best in terms of performance and efficiency.
On which event (onDestroy?, onDetach?) should the data be saved when the user press the "Next" button to move the next step in the wizard?
keep in mind that on each step more data should be kept.
I saw solution for wizards for android however my issue with them is that they are not RTL supported so with the ViewPager I can set the initial step using setCurrentitem() method.
https://github.com/romannurik/Android-WizardPager
https://github.com/Nimrodda/WizarDroid
Appreciate your assistance
I think it is more yours architecture design decision.
For example all your Fragments classes should implement custom interface vs onPause() method. For what, you sinking, main Fragment.class have one onPause()? It because when you load fragments in view pager adapter, he present only one but really he load 3 or more fragments from fragmentsArray and cache them, and when you only on first fragment onPause() has worked on second and third fragment and so on.... at StackOverflow was decision for this problem like :
public interface FragmentLifeCycle {
void onPauseFragment(); } ///for saving your data you must implement it in all fragments from view Pager
public class SomeFragment extends Fragment implements FragmentLifeCycle {
#Override
public void onPauseFragment() {
//save your data here
}}
public class NewHomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.........
//..........
final ViewPager.SimpleOnPageChangeListener listener = pageChangeListener(YourPagerAdapter);
YourViewPager.addOnPageChangeListener(listener);
}
private ViewPager.SimpleOnPageChangeListener pageChangeListener(final FragmentPagerAdapter adapter) {
return new ViewPager.SimpleOnPageChangeListener() {
int currentPosition = 0;
#Override
public void onPageSelected(int newPosition) {
FragmentLifeCycle fragmentToHide = (FragmentLifeCycle) adapter.getItem(currentPosition);
fragmentToHide.onPauseFragment();
currentPosition = newPosition;
}
};
}}
But its only one decision , i see at this problem decorator or state machine design pattern.

how to pass data from a java class to a fragment in android

So i have a FragmentPagerAdapater called SectionsPagerAdapter and a fragment called TeamFragment where I display data from a specific team. So basically I don't want to create different fragments for each team. That is an overkill. I just want 1 fragment which basically connects to the backend then collects the data based on the team then displays that data. But I dont know how to pass the Team name(a string type) from SectionsPagerAdapter to the TeamFragment so that in TeamFragment, I can easily know what to retrieve from the backend. My backend in parse.com. Please help me figure this out and learn. Thanks
So this is was solved my problem. In my sectionsPagerAdapter class i had the below code
Bundle args = new Bundle();
args.putString("TeamName", team);
TeamFragment teamFragment = new TeamFragment();
teamFragment.setArguments(args);
In onCreateView of my TeamFragment, i had the following
Bundle bundle = this.getArguments();
mTeam = bundle.getString("TeamName");
hope this can help someone else. Thanks
Communicating data into fragments is typically done through a simple setter function that is called by the activity that instantiates or contains the fragment:
public class MyActivity extends FragmentActivity {
#Override
protected void onCreate(Bundled savedInstanceState) {
// ...
TeamFragment fragment =
(TeamFragment) (getSupportFragmentManager().findFragmentById(fragmentId));
fragment.setTeamName(teamName);
// ...
}
For communicating data back to the activity, is typically done using a fragment-specific "Listener" interface. This listener can be attached using the same method (by calling a method on the fragment in the parent activity to register the listener) or it can be done by requiring that the parent Activity implement the listener interface, and casting the parent activity to this listener interface in onAttach() (though the latter approach is not as clean of an approach). Example:
public class MyActivity extends FragmentActivity {
#Override
protected void onCreate(Bundled savedInstanceState) {
// ...
TeamFragment fragment =
(TeamFragment) (getSupportFragmentManager().findFragmentById(fragmentId));
fragment.setTeamName(teamName);
fragment.setTeamSelectedListener(new TeamSelectedListenerImpl());
// ...
}
Or:
public class TeamFragment extends Fragment {
public interface TeamSelectedListener {
// ...
}
// ...
#Override
protected void onAttach(Activity activity) {
teamSelectedListener = (TeamSelectedListener) activity;
}
// ...
}
public class MyActivity
extends FragmentActivity
implements TeamFragment.TeamSelectedListener {
// ...
}

What callback exists for a FragmentActivity, ie. onAllFragmentsHaveBeenCreated()?

I am trying to find a callback for my FragmentActivity that happens 'after' all of the fragments have called 'onCreateView'.
The reason for this is that my Fragment implement my interface:
public interface LifeCycleFragment {
public void onResumeFragment();
}
and when i call the fragment from MyActivity:
class MyActivity extends Activity
onCreate()
fragment.onResumeFragment()
getActivity() ends up being null:
class MyFragment extends Fragment implements LifeCycleFragment
#Override
public void onResumeFragment() {
Log.e(TAG, "- ON RESUME -");
FragmentActivity activity = getActivity();
// *****ACTIVITY IS NULL HERE AND THAT'S A PROBLEM ***//
I am not sure how to tackle this problem and any help would be appreciated.
Place getActivity() in override onActivityCreated method, and save it in the class for onResumeFragment(). I hope the Activity is still kept the same during onPause().
Would you like sample code to communicate between Fragment and Activity? I posted an answer in SO about it # Passing data between fragments contained in an activity. The respective Google webpage is # Communicating with Other Fragments.
Good luck and have fun...

Categories

Resources