2

I'm having issues passing data in between fragments in a tablayout / viewpager. I have a Tablayout with four tabs, and switching is enabled using the viewpager. I am trying to save data from FirstTabFragment, SecondTabFragment and ThirdTabFragment, and retrieve them in the last tab = ReviewFragment. I have implemented saving data in to SharedPreferences, and this works for the first and second fragment, the data in the third fragment is not saved and shows as empty when the ReviewFragment is opened.

FirstFragment is a Listview, the string in the the selected listview item is saved. SecondFragment, is an editText, value inputed is saved when the next button is pressed. ThirdFragment is also a Listview, and the code in FirstFragment is same as in this fragment, but doesnt work as intended.

What I mean by doesnt work as intended is: The value in the ThirdFragment is actually saved into SharedPreferences but is not retrieved immediately when the ReviewFragment is opened. I knew this because when I close the app and reopen it, it shows the saved value from the SharedPreferences.

Below is my code from the ThirdFragment and ReviewFragment

ThirdFragment

  private SharedPreferences memory1;
    private SharedPreferences.Editor edt1;

    private ListView listView;
    private ArrayAdapter<String> listAdapter;

    public MtnPaymentMtdFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.payment_method, container, false);



        // Find the ListView resource.
        listView = (ListView) v.findViewById(R.id.mtn_plv);

        // Create and populate a List
        String[] p_method = new String[]{"ATM - MasterCard - Visa - Verve", "Online Bank Transfer", "Bank Deposit", "Recharge Card", "Mobile Banking"};
        ArrayList<String> p_methods = new ArrayList<String>();
        p_methods.addAll(Arrays.asList(p_method));

        // Create ArrayAdapter using the list.
        listAdapter = new ArrayAdapter<String>(this.getActivity(), R.layout.item_row3, p_methods);

        // Set the ArrayAdapter as the ListView's adapter.
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String selectedFromList = (listView.getItemAtPosition(i).toString().trim());

                switch (i) {
                    case 0:
                        MtnReviewFragment fragment = new MtnReviewFragment();
                        Bundle bundler = new Bundle();
                        bundler.putString("payment_mtd", selectedFromList);
                        fragment.setArguments(bundler);
//                        memory1 = getActivity().getPreferences(0);
//                        edt1 = memory1.edit();
//                        edt1.putString("payment_mtd", selectedFromList);
//                        edt1.apply();
                        ((MtnActivity) getActivity()).setCurrentItem(3, true);
                        break;
                    case 1:
//                        String selectedFromList1 = (listView.getItemAtPosition(i).toString().trim());
                        memory1 = getActivity().getPreferences(0);
                        edt1 = memory1.edit();
                        edt1.putString("payment_mtd", selectedFromList);
                        edt1.apply();
                        ((MtnActivity) getActivity()).setCurrentItem(3, true);
                        break;
                    case 2:
//                        String selectedFromList2 = (listView.getItemAtPosition(i).toString().trim());
                        memory1 = getActivity().getPreferences(0);
                        edt1 = memory1.edit();
                        edt1.putString("payment_mtd", selectedFromList);
                        edt1.apply();
                        ((MtnActivity) getActivity()).setCurrentItem(3, true);
                        break;
                    case 3:
//                        String selectedFromList3 = (listView.getItemAtPosition(i).toString().trim());
                        memory1 = getActivity().getPreferences(0);
                        edt1 = memory1.edit();
                        edt1.putString("payment_mtd", selectedFromList);
                        edt1.apply();
                        ((MtnActivity) getActivity()).setCurrentItem(3, true);
                        break;
                    case 4:
//                        String selectedFromList4 = (listView.getItemAtPosition(i).toString().trim());
                        memory1 = getActivity().getPreferences(0);
                        edt1 = memory1.edit();
                        edt1.putString("payment_mtd", selectedFromList);
                        edt1.apply();
                        ((MtnActivity) getActivity()).setCurrentItem(3, true);
                }
            }
        });
        return v;
    }
}

ReviewFragment

private SharedPreferences memory;
private SharedPreferences.Editor edt;
private TextView rev_bundle_result;
private TextView rev_mob_result;
private TextView rev_pmtd_result;
public static SharedPreferences savedSharedPreference;
public static String filename = "nameValue";
private static final String REGISTER_URL = "http://zzzzzzzzz.com/xxxxx/register.php";


public MtnReviewFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.review_layout, container, false);
    rev_bundle_result = (TextView) v.findViewById(R.id.rev_bundle_result);
    rev_mob_result = (TextView) v.findViewById(R.id.rev_mob_result);
    rev_pmtd_result = (TextView) v.findViewById(R.id.rev_pmtd_result);
    Button make_payment = (Button) v.findViewById(R.id.make_payment_but);

    memory = getActivity().getPreferences(0);
    String bundles = memory.getString("bundle_name", "empty");
    String mob_number = memory.getString("mob_number", "empty");
    String payment_mtds = memory.getString("payment_mtd", "empty");
    String p_amount = memory.getString("amount", "empty");

    rev_bundle_result.setText(bundles);
    rev_mob_result.setText(mob_number);
    rev_pmtd_result.setText(payment_mtds);
  • Fourth tab is rendered as soon as you reach the third layout. Refresh your fourth tab when user switches to that tab. `setUserVisibleHint` – kushpf Mar 27 '16 at 10:49

4 Answers4

1

This is a bit old and you've probably found the solution already, but just in case someone else ends up here and needs the answer...

I think your problem might be because, in your ReviewFragment, you're getting the data from SharedPreferences in the onCreateView() method.

Your ReviewFragment is probably being created when you scroll to the ThirdFragment. ViewPagers usually create some of the fragments ahead of time, to improve performance when the user scrolls. So when your ReviewFragment.onCreateView() is called, the ThirdFagment hasn't saved its data to the SharedPreferences yet. Add a breakpoint to your ReviewFragment.onCreateView() and check if that's what's happening.

I think you'd have to add an OnPageChangeListener to your ViewPager and make ReviewFragment get the data from SharedPreferences only when it becomes visible. Also, check out Fragment.setUserVisibleHint(). It used to not work properly with ViewPagers, but I've heard that's been fixed.

Danilo Carvalho
  • 395
  • 2
  • 12
0

Try to use commit() intead apply() for SharedPreferences if you want to be sure that your changes have been saved before continue.

apply() make the changes asynchronously, while commit() save the changes synchronously. https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

Also, I have seen your code and you call and cast your container activity, you should use the listener pattern that android advices. Read the guidelines or starts with this post for that: Send data between fragments in a pagerAdapter

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Gonzalo
  • 1,781
  • 15
  • 29
  • I have tried that Gonzalo, it was the same. Didnt work. – Oluleye IResþekt Idowu Dec 18 '15 at 14:25
  • Try to use `commit()` and see what it returns. – Gonzalo Dec 18 '15 at 14:29
  • Thanks Gonzalo, but its still the same, I tested it before. What do you think could cause it. data sent is not shown in the ReviewFragment immediately, but when I close and reopen the app, the value shows. I even added a progressdialog because I thought probably sharedpreferennces needed a few seconds to save the value. But its still the same. – Oluleye IResþekt Idowu Dec 18 '15 at 15:09
0

The logic of viewpager getview method creates only left and right side fragment without itself. you can try to set page limit setOffscreenPageLimit().

But it is not useful load all fragment. Maybe this solve your problem.

Anil KARA
  • 21
  • 4
0

Here is the solution for sending data to tablayout / viewpagers fragment from fragment.

Community
  • 1
  • 1
dharmx
  • 694
  • 1
  • 13
  • 20