Passing data between Fragments in View Pager

半世苍凉 提交于 2020-02-02 10:38:48

问题


Need help in passing data between Fragments in View Pager! We tried passing data as bundle inside Fragments. Inside the Fragment.getInstance() method and tried getting the data from the other Fragment.getArguments().

Activity Code

package com.northerly.bumpr;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.widget.TextView;


import com.northerly.bumpr.Fragment.EnterOtp;

import com.northerly.bumpr.Fragment.MobileNumber;
import com.northerly.bumpr.utils.NonSwipeableViewPager;


public class LoginActivity extends AppCompatActivity {

public static NonSwipeableViewPager mPager;
PagerAdapter mPagerAdapter;
private static final int NUM_PAGES = 2;
public static Bundle myBundle = new Bundle();
public static TextView tv;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);


    mPager = (NonSwipeableViewPager) findViewById(R.id.pager);

    mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);
    mPager.setOffscreenPageLimit(0);

    mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When changing pages, reset the action bar actions since they are dependent
            // on which page is currently active. An alternative approach is to have each
            // fragment expose actions itself (rather than the activity exposing actions),
            // but for simplicity, the activity provides the actions in this sample.
            invalidateOptionsMenu();
        }
    });





}

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }



    @Override
    public Fragment getItem(int position) {
        switch (position) {

            case 0:
                return MobileNumber.newInstance();

            case 1:
                return EnterOtp.newInstance();

        }
        return MobileNumber.newInstance();
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }
}






}

Fragment Code:

package com.northerly.bumpr.Fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.net.nsd.NsdManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.IntRange;
import android.support.design.widget.Snackbar;    
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.northerly.bumpr.HomeActivity;
import com.northerly.bumpr.LoginActivity;
import com.northerly.bumpr.R;
import com.northerly.bumpr.common.ConnectionDetector;
import com.northerly.bumpr.common.OfferInfoChild;
import com.northerly.bumpr.common.OfferInfoGroup;
import com.northerly.bumpr.utils.DBHandler;
import com.northerly.bumpr.utils.GarageGetterSetter;
import com.northerly.bumpr.utils.GlobalData;
import com.northerly.bumpr.utils.PreferenceConnector;
import com.northerly.bumpr.utils.Webservice;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import static android.R.id.list;


public class MobileNumber extends Fragment {

Button cont;
EditText ph_no;
ConnectionDetector detector;
FrameLayout mobil_num_lay;
public static String mobile;

private OnFragmentInteractionListener mListener;

public MobileNumber() {

}

public static MobileNumber newInstance() {
    MobileNumber fragment = new MobileNumber();
    return fragment;
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup)          inflater.inflate(R.layout.fragment_mobile_number, container, false);

    cont = (Button) rootView.findViewById(R.id.cont);
    ph_no = (EditText) rootView.findViewById(R.id.s_ph);

    mobil_num_lay=(FrameLayout)rootView.findViewById(R.id.mobile_number_lay);

detector=new ConnectionDetector(getActivity());
    cont.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (ph_no.getText().toString().length()!=0 && ph_no.getText().toString().length()!=10)
            {
                final Snackbar snackbar = Snackbar.make(mobil_num_lay,     "Please Enter a valid  Mobile Number", Snackbar.LENGTH_SHORT);

                snackbar.setAction("Dismiss", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        snackbar.dismiss();
                    }
                });

                // Changing message text color
                snackbar.setActionTextColor(getResources().getColor(R.color.colorAccent));
                snackbar.show();



            } else {
                mobile="+91"+ph_no.getText().toString();
                if (detector.isConnectingToInternet()) {
                    new AsyncLogin(getActivity()).execute();
                } else {
                    Toast.makeText(getActivity(),     getResources().getString(R.string.internet_connection_exception),
                            Toast.LENGTH_SHORT).show();
                }
            }

//                GoSignUp.myBundle.putString("Timer","on");



        }
    });

    return rootView;
}

public interface OnFragmentInteractionListener {

    void onFragmentInteraction(Uri uri);
}

public void timerOn() {

    new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {

            LoginActivity.tv.setText("0:" + millisUntilFinished / 1000);

        }

        public void onFinish() {

                LoginActivity.tv.setText(getResources().getString(R.string.resend_otp));

        }
    }.start();
}

public class AsyncLogin extends AsyncTask<String, String, Void> {
    String response;
    Dialog dialog;
    private final WeakReference<FragmentActivity> mainActivityWeakRef;

    public AsyncLogin(FragmentActivity mainActivity) {
        super();
        this.mainActivityWeakRef = new WeakReference<>(mainActivity);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (mainActivityWeakRef.get() != null && !mainActivityWeakRef.get().isFinishing()) {
            dialog = new Dialog(getActivity());
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.custom_dialog);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialog.show();
        }
    }

    protected Void doInBackground(String... args) {
        try {
            JSONStringer userJson = null;
//              userJson = new JSONStringer().object().key(GlobalData.user_id)
//                      .value(PreferenceConnector.readString(getActivity(), PreferenceConnector.USER_ID, ""))
//                      .endObject();

            userJson = new JSONStringer().object().key(GlobalData.username)
                    .value(mobile)
                    .endObject();

            String url = GlobalData.serverName + GlobalData.user_status;

            response = Webservice.PostDataAlter(url, userJson);

        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        //Below code is added to avoid Fragment not attached to activity error
        if(isAdded()){
            getResources().getString(R.string.app_name);
        }

        Log.d((mainActivityWeakRef.get() != null) + "", "onPostexecute");
        if (mainActivityWeakRef.get() != null && !mainActivityWeakRef.get().isFinishing()) {
            if (dialog.isShowing()) {
                /* Dismiss the progress dialog after sharing */
                dialog.dismiss();
            }
            ArrayList<OfferInfoGroup> GrpList = new ArrayList<OfferInfoGroup>();
            try {
                System.out.println("response "+ response.toString());
                JSONObject jsonobj = new JSONObject(response);
                String UserDetails = jsonobj.getString(getResources().getString(R.string.response_status));

                System.out.println("Hi"+UserDetails);


                if (UserDetails.equals(getResources().getString(R.string.response_register)))
                {

//                        String     otp_verify=jsonobj.getString(getResources().getString(R.string.verify_otp));
//                            PreferenceConnector.writeString(getActivity(),PreferenceConnector.OTP_VERIFY,otp_verify);

                    String result1 = jsonobj.getString(getResources().getString(R.string.response_results));
                    JSONArray arr = new JSONArray(result1);
                    String result2 = jsonobj.getString(getResources().getString(R.string.response_results2));
                        JSONArray arr2 = new JSONArray(result2);
                    String result3 = jsonobj.getString(getResources().getString(R.string.response_results3));
                    JSONArray arr3 = new JSONArray(result3);

                    System.out.println("Hello"+arr);
                    for (int i=0;i<arr.length();i++)
                    {
                        String userid = arr.getJSONObject(i).getString(GlobalData.reg_id);
                        PreferenceConnector.writeString(getActivity(),PreferenceConnector.USER_ID,userid);
                        String name=arr.getJSONObject(i).getString(GlobalData.name);
                        PreferenceConnector.writeString(getActivity(),PreferenceConnector.USER_NAME,name);
                        String email =arr.getJSONObject(i).getString(GlobalData.email);
                        PreferenceConnector.writeString(getActivity(),PreferenceConnector.USER_EMAIL,email);
                        String mobile=arr.getJSONObject(i).getString(GlobalData.username);
                        PreferenceConnector.writeString(getActivity(),PreferenceConnector.USER_PHONE,mobile);
                        String city=arr.getJSONObject(i).getString(GlobalData.city);
                            PreferenceConnector.writeString(getActivity(),PreferenceConnector.USER_CITY,city);
                    }

                    System.out.println("Results 2"+result2);
                    System.out.println("Array 2"+arr2);

                    for (int j=0;j<arr2.length();j++)
                    {
                        String id = arr2.getJSONObject(j).getString(GlobalData.Vehicle_id);
                        String user_id = arr2.getJSONObject(j).getString(GlobalData.user_id);
                        String brand = arr2.getJSONObject(j).getString(GlobalData.brand);
                        String model = arr2.getJSONObject(j).getString(GlobalData.model);
                        String type = arr2.getJSONObject(j).getString(GlobalData.type);
                        String fuel_type = arr2.getJSONObject(j).getString(GlobalData.fuel_type);
                        String reg_no = arr2.getJSONObject(j).getString(GlobalData.reg_no);
                        String year = arr2.getJSONObject(j).getString(GlobalData.year);
                        String km_driven = arr2.getJSONObject(j).getString(GlobalData.km_driven);
                        String variant = arr2.getJSONObject(j).getString(GlobalData.variant);
                        DBHandler db = new DBHandler(getActivity());


/*          "user_id": "20666",
        "vehicle_id": "170",
        "brand": "Hero MotoCorp",
        "model": "Xtreme (2014)",
        "type": "2w",
        "fuel_type": "PETROL",
        "year": "2014",
        "km_driven": "17240",
        "variant": ""*/
                        db.insert_all(Integer.parseInt(user_id),     Integer.parseInt(id),brand,model,type,fuel_type,reg_no,km_driven,year,variant);

                        ArrayList<GarageGetterSetter> lis = db.getAllVehicles();

                        System.out.println(lis);



                    }

                    for (int k=0;k<arr3.length();k++)
                    {
                        String otp_verify=arr3.getJSONObject(k).getString(GlobalData.verify_otp);
                        PreferenceConnector.writeString(getActivity(),PreferenceConnector.OTP_VERIFY,otp_verify);
                    }

                        LoginActivity.mPager.setCurrentItem(LoginActivity.mPager.getCurrentItem() + 1);
                }

                else if (UserDetails.equals(getResources().getString(R.string.response_new_user))){

                    String result1 = jsonobj.getString(getResources().getString(R.string.response_results));
                    JSONArray arr = new JSONArray(result1);
                    String result2 = jsonobj.getString(getResources().getString(R.string.response_results2));
                    JSONArray arr2 = new JSONArray(result2);
                    String result3 = jsonobj.getString(getResources().getString(R.string.response_results3));
                    JSONArray arr3 = new JSONArray(result3);

                    for (int k=0;k<arr3.length();k++)
                    {
                        String otp_verify=arr3.getJSONObject(k).getString(GlobalData.verify_otp);
                        PreferenceConnector.writeString(getActivity(),PreferenceConnector.OTP_VERIFY,otp_verify);
                    }
                    LoginActivity.mPager.setCurrentItem(LoginActivity.mPager.getCurrentItem() + 1);
                }

 //                    JSONArray arr2=new JSONArray(result2);







           //      else if     (UserDetails.equals(getResources().getString(R.string.response_register))){








           //     }

            } catch (Exception e) {
                if (e.getMessage() != null) {
                    Toast.makeText(getActivity(),     getResources().getString(R.string.AsyncException),
                            Toast.LENGTH_SHORT).show();
                }
                e.printStackTrace();
            }
        }
    }
}
}

Need help in passing data between fragments


回答1:


Create an interface

Implement that interface on the base activity where your fragment transaction

Call this interface from fragment1 while fragment transaction through a call back

Pass the value through this interface

For more details check this ans https://stackoverflow.com/a/32372333/5169060




回答2:


You can try passing data between Fragments by making a common singleton class. Depending on your requirements you can create a class to set and get data. Below is one example of a singleton class which can be used to pass data between fragments

public class DataClass {
    private static DataClass dataObject = null;

    private DataClass() {

    }

    public static DataClass getInstance() {
        if (dataObject == null)
            dataObject = new DataClass();
        return dataObject;
    }
    private String distributor_id;;

    public String getDistributor_id() {
        return distributor_id;
    }

    public void setDistributor_id(String distributor_id) {
        this.distributor_id = distributor_id;
    }
}

After this set your data before you move to the next screen.

DataHolderClass.getInstance().setDistributor_id("your data");

and to get data

String data = DataClass.getInstance().getDistributor_id();


来源:https://stackoverflow.com/questions/44043147/passing-data-between-fragments-in-view-pager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!