0

Hi I know there are answers of this question. I have tried all of them but it is not working in my app. I have two fragments(Login and Password), I want to pass email and mobile number from Login fragment to Password fragment. I tried alot but i cant get solution.

Please anyone help to me.

LoginFragment:

public class LoginFragment extends Fragment {
    private SlidingTabLayout mSlidingTabLayout;
    private ViewPager mViewPager;
    SharedPreferences pref = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_login, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // BEGIN_INCLUDE (setup_viewpager)
        // Get the ViewPager and set it's PagerAdapter so that it can display items
        mViewPager = (ViewPager) view.findViewById(R.id.loginpager);
        mViewPager.setAdapter(new TabsAdapter());
        // END_INCLUDE (setup_viewpager)

        // BEGIN_INCLUDE (setup_slidingtablayout)
        // Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
        // it's PagerAdapter set.
        mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setViewPager(mViewPager);
        // END_INCLUDE (setup_slidingtablayout)
    }

    public class TabsAdapter extends PagerAdapter {
        @Override
        public boolean isViewFromObject(View view, Object o) {
            return o == view;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0: return "SIGN IN";
                case 1: return "SIGN UP";
            }
            return "";
        }
        // END_INCLUDE (pageradapter_getpagetitle)

        @Override
        public int getCount() {
            // get item count - equal to number of tabs
            return 2;
        }

        /**
         * Instantiate the {@link View} which should be displayed at {@code position}. Here we
         * inflate a layout from the apps resources and then change the text view to signify the position.
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // Inflate a new layout from our resources
            View view = null;
            switch (position) {
                case 0: view = getActivity().getLayoutInflater().inflate(R.layout.fragment_signin,
                        container, false);
                        signinListener(view);
                        break;
                case 1: view = getActivity().getLayoutInflater().inflate(R.layout.fragment_signup,
                        container, false);
                        signupListener(view);
                       break;

            }
            container.addView(view);
            return view;
        }

        EditText Name;
        EditText EmailId;
        EditText Phone;
        Button Signup;
        // Progress Dialog Object
        ProgressDialog prgDialog;
        // Error Msg TextView Object
        TextView errorMsg;
        TextView signUperrorMsg;
        EditText username;
        EditText password;
        Button Signin;


        public void signinListener(View signinView) {
            username = (EditText) signinView.findViewById(R.id.signin_mobile);
            password = (EditText) signinView.findViewById(R.id.signin_password);
            Signin = (Button) signinView.findViewById(R.id.signButton);
            // Find Error Msg Text View control by ID
            errorMsg = (TextView)signinView.findViewById(R.id.login_error);
            prgDialog = new ProgressDialog(getActivity());
            // Set Progress Dialog Text
            prgDialog.setMessage("Please wait...");
            // Set Cancelable as False
            prgDialog.setCancelable(false);

            //Validation for signin field while clicking signin button
            Signin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String usrname = username.getText().toString();
                    String usrpassword = password.getText().toString();
                    // Instantiate Http Request Param Object
                    RequestParams params = new RequestParams();
                    if (Utility.isNotNull(usrname) && Utility.isNotNull(usrpassword)) {
                        // When Email entered is Valid
                        if (Utility.validate(usrname)) {
                            // Put Http parameter username with value of Email Edit View control
                            params.put("mobile", usrname);
                            // Put Http parameter password with value of Password Edit Value control
                            params.put("pwd",usrpassword);
                            // Invoke RESTful Web Service with Http parameters
                            signinWS(params);
                        }
                        // When Email is invalid
                        else {
                            Toast.makeText(getActivity().getApplicationContext(), "Please enter valid mobile", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show();
                    }
                                }
            });
        }

        /*
        Function to set the onclick listener for signup tab
         */
        public void signupListener(View signUpView) {
            Name = (EditText) signUpView.findViewById(R.id.signup_name);
            EmailId= (EditText) signUpView.findViewById(R.id.signup_email);
            Phone= (EditText) signUpView.findViewById(R.id.signup_phone);
            Signup = (Button) signUpView.findViewById(R.id.signupButton);
            // Find Error Msg Text View control by ID
            signUperrorMsg = (TextView)signUpView.findViewById(R.id.signup_error);
            prgDialog = new ProgressDialog(getActivity());
            // Set Progress Dialog Text
            prgDialog.setMessage("Please wait...");
            // Set Cancelable as False
            prgDialog.setCancelable(false);


            //Allow only characters and space in name field
            Name.setFilters(new InputFilter[]{
                    new InputFilter() {
                        @Override
                        public CharSequence filter(CharSequence cs, int start,
                                                   int end, Spanned spanned, int dStart, int dEnd) {
                            // TODO Auto-generated method stub
                            if (cs.equals("")) { // for backspace
                                return cs;
                            }
                            if (cs.toString().matches("[a-zA-Z ]+")) {
                                return cs;
                            }
                            return "";
                        }
                    }
            });

            //Validation for signup field while clicking signup button
            Signup.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String sName = Name.getText().toString();
                    String sPhoneNo = Phone.getText().toString();
                    String sEmailId = EmailId.getText().toString();


                    // Instantiate Http Request Param Object
                    RequestParams params = new RequestParams();
                    if (Utility.isNotNull(sName) && Utility.isNotNull(sPhoneNo) && Utility.isNotNull(sEmailId) ) {
                        if (Utility.line2_validate(sName)) {
                            if (Utility.validate(sPhoneNo)) {
                                if (Utility.email_validate(sEmailId)) {

                                   // Put Http parameter username with value of Name Edit View control
                                    params.put("name", sName);
                                    // Put Http parameter email with value of Email Edit Value control
                                    params.put("email", sEmailId);
                                    // Put Http parameter mobile with value of Mobile Edit Value control
                                    params.put("mobile", sPhoneNo);
                                    // Invoke Signup RESTful Web Service with Http parameters
                                    signUpWS(params);

                                }
                                else {
                                    EmailId.setError("Enter valid Email");
                                }
                            }
                            else {
                                Phone.setError("Enter valid Mobile");
                            }
                        }
                        else {
                            Name.setError("Enter valid Name");
                        }
                    }
                    else {
                        Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        /*
        Function to invoke the WS for signin activity
         */
        public void signinWS(RequestParams params){
            // Show Progress Dialog
            prgDialog.show();
            // Make RESTful webservice call using AsyncHttpClient object
            AsyncHttpClient client = new AsyncHttpClient();
            client.get("http://example.com/signin", params, new AsyncHttpResponseHandler() {
                // When the response returned by REST has Http response code '200'
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {

                    // Hide Progress Dialog
                    prgDialog.hide();
                    try {
                        // JSON Object
                        JSONObject obj = new JSONObject(new String(response));
                        // When the JSON response has status boolean value assigned with true
                        if (obj.getBoolean("status")) {
                            Toast.makeText(getActivity().getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show();
                            // Navigate to Home screen
                            pref = getActivity().getPreferences(Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = pref.edit();
                            editor.putInt(getString(R.string.signedupflag), 1);
                            editor.putString("name", username.getText().toString());
                            editor.commit();
                            ((MainActivity) getActivity()).navigatetoSearchActivity();
                        }
                        // Else display error message
                        else {
                            errorMsg.setText(obj.getString("error_msg"));
                            Toast.makeText(getActivity().getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }


                // When the response returned by REST has Http response code other than '200'
                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responsebody, Throwable error) {
                    // Hide Progress Dialog
                    prgDialog.hide();
                    // When Http response code is '404'
                    if (statusCode == 404) {
                        Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code is '500'
                    else if (statusCode == 500) {
                        Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code other than 404, 500
                    else {
                        Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
                    }

                }
            });
        }


        /**
         * Destroy the item from the {@link ViewPager}. In our case this is simply removing the
         * {@link View}.
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        /*
       Function to invoke the WS for signin activity
        */
        public void signUpWS(RequestParams params){
            // Show Progress Dialog
            prgDialog.show();
            // Make RESTful webservice call using AsyncHttpClient object
            AsyncHttpClient client = new AsyncHttpClient();
            client.get("http://example.com/signup", params, new AsyncHttpResponseHandler() {
                // When the response returned by REST has Http response code '200'
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {

                    // Hide Progress Dialog
                    prgDialog.hide();
                    try {
                        // JSON Object
                        JSONObject obj = new JSONObject(new String(response));
                        // When the JSON response has status boolean value assigned with true
                        if (obj.getBoolean("status")) {
                            Toast.makeText(getActivity().getApplicationContext(), "You are successfully Signed Up!", Toast.LENGTH_LONG).show();


                      //Pass value from this fragment
                            PasswordFragment pf = new PasswordFragment();
                            Bundle args = new Bundle();
                            args.putString("email",EmailId.getText().toString());
                            pf.setArguments(args);
                            getFragmentManager().beginTransaction().add(R.id.content_frame,pf).commit();



                            ((MainActivity) getActivity()).navigatetoPasswordActivity();
                        }
                        // Else display error message
                        else {
                            signUperrorMsg.setText(obj.getString("msg"));
                            Toast.makeText(getActivity().getApplicationContext(), obj.getString("msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }


                // When the response returned by REST has Http response code other than '200'
                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responsebody, Throwable error) {
                    // Hide Progress Dialog
                    prgDialog.hide();
                    // When Http response code is '404'
                    if (statusCode == 404) {
                        Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code is '500'
                    else if (statusCode == 500) {
                        Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code other than 404, 500
                    else {
                        Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
                    }

                }
            });
        }
    }
}

PasswordFragament:

public class PasswordFragment extends Fragment  {
    EditText verifyCode;
    EditText new_pwd;
    EditText confirm_pwd;
    TextView pwd_error_msg;
    Button pwd_ok;
    // Progress Dialog Object
    ProgressDialog prgDialog;

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

            View view = inflater.inflate(R.layout.password, container,false);
           //Retrive value from login fragment
           final String email = getArguments().getString("email");

            verifyCode = (EditText)view.findViewById(R.id.mobie_verification);
            new_pwd = (EditText)view.findViewById(R.id.new_password);
            confirm_pwd = (EditText)view.findViewById(R.id.confirm_password);
            pwd_error_msg = (TextView)view.findViewById(R.id.pwd_error_msg);
            pwd_ok = (Button)view.findViewById(R.id.password_button);

        prgDialog = new ProgressDialog(getActivity());
            // Set Progress Dialog Text
            prgDialog.setMessage("Please wait...");
            // Set Cancelable as False
            prgDialog.setCancelable(false);

            pwd_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strPwd = new_pwd.getText().toString();
                String strConfPwd = confirm_pwd.getText().toString();
                String strVerifyCode = verifyCode.getText().toString();


                // Instantiate Http Request Param Object
                RequestParams params = new RequestParams();

                if (Utility.isNotNull(strPwd)) {
                    if (Utility.isNotNull(strConfPwd)) {
                        if ((strPwd.length() > 3 ) && (strPwd.length() < 8 ) )  {
                            pwd_error_msg.setText(null);
                            if (strPwd.equals(strConfPwd)) {
                                //password and confirm passwords equal.go to next step
                                pwd_error_msg.setText(null);
                                //Toast.makeText(getActivity().getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
                                params.put("email", email);
                                // Put Http parameter verificationCode with value of Verificationcode Edit View control
                                params.put("key", strVerifyCode);
                                // Put Http parameter password with value of Password Edit Value control
                                params.put("code", strPwd);

                                params.put("mobile", "9966338856");
                                pwdWS(params);

                            } else {
                                //passwords not matching.please try again
                                pwd_error_msg.setText("Password does not Match!");
                            }
                        }
                        else {
                            pwd_error_msg.setText("Password should be from 4 to 8 characters.");
                        }

                    }
                    else {
                        confirm_pwd.setError("Confirm Password must be filled out");
                    }

                }
                else {
                    new_pwd.setError("New Password must be filled out");
                }
            }
        });
        return view;
    }

    /*
      Function to invoke the WS for signin activity
       */
    public void pwdWS(RequestParams params){
        // Show Progress Dialog
        prgDialog.show();
        // Make RESTful webservice call using AsyncHttpClient object
        AsyncHttpClient client = new AsyncHttpClient();
        client.get("http://www.example.com/mverify", params, new AsyncHttpResponseHandler() {
            // When the response returned by REST has Http response code '200'
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {

                // Hide Progress Dialog
                prgDialog.hide();
                try {
                    // JSON Object
                    JSONObject obj = new JSONObject(new String(response));
                    // When the JSON response has status boolean value assigned with true
                    if (obj.getBoolean("status")) {
                        Toast.makeText(getActivity().getApplicationContext(), "Password Successfully Created!", Toast.LENGTH_LONG).show();
                        // Navigate to Home screen
                            /*pref = getActivity().getPreferences(Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = pref.edit();
                            editor.putInt(getString(R.string.signedupflag), 1);
                            editor.putString("name", username.getText().toString());
                            editor.commit();*/
                        ((MainActivity) getActivity()).navigatetoSearchActivity();
                    }
                    // Else display error message
                    else {
                        pwd_error_msg.setText(obj.getString("msg"));
                        Toast.makeText(getActivity().getApplicationContext(), obj.getString("msg"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }


            // When the response returned by REST has Http response code other than '200'
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responsebody, Throwable error) {
                // Hide Progress Dialog
                prgDialog.hide();
                // When Http response code is '404'
                if (statusCode == 404) {
                    Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                }
                // When Http response code is '500'
                else if (statusCode == 500) {
                    Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                }
                // When Http response code other than 404, 500
                else {
                    Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
                }

            }
        });
    }
}
Rohit5k2
  • 17,529
  • 8
  • 42
  • 56
Razul
  • 107
  • 12
  • possible duplicate of [How can I transfer data from one fragment to another fragment android](http://stackoverflow.com/questions/19333178/how-can-i-transfer-data-from-one-fragment-to-another-fragment-android) – RobinHood Aug 14 '15 at 06:22
  • You already asked it here. http://stackoverflow.com/questions/31986005/how-to-get-value-from-one-fragment-and-pass-to-another-fragment – Emil Aug 17 '15 at 08:34

2 Answers2

2

Use Bundle to send String:

 //Put the value
   YourNewFragment ldf = new YourNewFragment ();
   Bundle args = new Bundle();
   args.putString("YourKey", "YourValue");
   ldf.setArguments(args);

    //Inflate the fragment
   getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

In onCreateView of the new Fragment(onCreateView):

 //Retrieve the value
 String value = getArguments().getString("YourKey");
sasikumar
  • 11,797
  • 2
  • 26
  • 44
2

1) Create an interface in fragment 2.
2) Implement this interface in your activity.
3) Cast activity's object to interface in fragment and call it's method with the data you want to pass.
4) In Interface's method from activity use "getFragmentManager().findFragmentbyId(...)" to get the object of second fragment and pass the data to fragment2 using this object.

Refer this link :http://developer.android.com/training/basics/fragments/communicating.html

Example : http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/

Nitesh
  • 3,760
  • 1
  • 19
  • 25