在View Pager中的片段之间传递数据

时间:2017-05-18 08:59:02

标签: android android-fragments android-fragmentactivity

在View Pager中的片段之间传递数据需要帮助!我们尝试在Fragments中将数据作为bundle传递。在Fragment.getInstance()方法内部并尝试从其他Fragment.getArguments()获取数据。

活动代码

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






}

片段代码:

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

需要帮助在片段之间传递数据

2 个答案:

答案 0 :(得分:0)

创建界面

在片段事务的基本活动上实现该接口

通过回调片段事务从fragment1调用此接口

通过此界面传递值

有关详细信息,请查看此https://stackoverflow.com/a/32372333/5169060

答案 1 :(得分:0)

您可以尝试通过创建一个常见的单例类来在片段之间传递数据。根据您的要求,您可以创建一个类来设置和获取数据。 下面是单例类的一个示例,可用于在片段之间传递数据

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

在您移动到下一个屏幕之前设置数据。

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

并获取数据

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