来自一个片段的SharedPreferences未在另一个片段上注册登录活动的数据

时间:2016-04-19 02:29:57

标签: android fragment sharedpreferences

我有一个名为LoginFragment的片段,用户可以通过单击“注册”按钮第一次注册。单击此按钮后,将打开一个名为RegisterFragment的新片段,用户可以选择并输入要注册的新用户名和密码。当我运行应用程序并输入注册下的字段并选择确定时,它会在吐司中显示“保存的信息”,就像它应该的那样。但是当我尝试使用我注册的用户名和密码登录时,应用程序无法识别信息并显示吐司“请检查条目并再试一次”,只有在用户名已存在或密码不正确时才会显示,在我的情况下并非如此。

SharedPreferences不保存用户名和密码值,因为我正在使用两个不同的片段吗?任何帮助将不胜感激!

RegisterFragment.java

   public class RegisterFragment extends Fragment {

    Button register_btn;
    EditText username_signup_ET, password_signup_ET;

    private  String KEY_UID = "uid";
    private  String KEY_PASSWORD = "pwd";
    private  final String PREFER_NAME = "Registry";
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    String username;

    //LoginDataBaseAdapter loginDataBaseAdapter;
    Context context;
    public void myAlertDialog(){
    context = getActivity();
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState){

        View v = inflater.inflate(R.layout.register_fragment_layout, container, false);

        sharedPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);;
        editor = sharedPreferences.edit();


        username_signup_ET = (EditText)v.findViewById(R.id.username_signup_ET);
        password_signup_ET = (EditText)v.findViewById(R.id.password_signup_ET);

        register_btn = (Button)v.findViewById(R.id.register_btn);
        register_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {

            String userName = username_signup_ET.getText().toString();
            String password = password_signup_ET.getText().toString();

            if(userName.equals("")||password.equals(""))
            {
                Toast.makeText(getActivity(), "Please Enter Values in all Fields!", Toast.LENGTH_SHORT).show();
            }
            else{
            register();
            launchLogin();
            }   
            }
        });
        return v;   
    }

    //launch login activity
    public void launchLogin(){
        FragmentManager FM = getFragmentManager();
        FragmentTransaction FT = FM.beginTransaction();
        LoginFragment LG = new LoginFragment();
        FT.addToBackStack("LG");
        FT.replace(R.id.fragment_one_id, LG);
        FT.commit();
    }

    // register your account
            private void register() {
                // prefix the keys with the user name
                editor.putString("userName" + "_" + KEY_UID, username_signup_ET.getText()
                        .toString());
                editor.putString("password" + "_" + KEY_PASSWORD, password_signup_ET.getText()
                        .toString());
                //editor.commit(); // commit the values
                editor.apply();

                Toast.makeText(getActivity(), "Saved Info!", Toast.LENGTH_SHORT).show();

            }// end of register

}

LoginFragment.java

    public class LoginFragment extends Fragment {


    Button login_btn, register_btn;
    EditText username_ET, password_ET;

    private  String KEY_UID = "uid";
    private  String KEY_PASSWORD = "pwd";
    private  final String PREFER_NAME = "Registry";
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
     String username;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState){
        super.onCreateView(inflater, container, savedInstanceState);

        View v = inflater.inflate(R.layout.login_fragment_layout, container, false);

        sharedPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        username_ET = (EditText)v.findViewById(R.id.username_ET);
        password_ET = (EditText)v.findViewById(R.id.password_ET);
        login_btn = (Button)v.findViewById(R.id.login_btn);
        register_btn = (Button)v.findViewById(R.id.register_btn);


        login_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // initialize username
                username = username_ET.getText().toString();

                boolean valid = isValid();
                if (valid) {
                    String text = getResources().getString(R.string.logging_in_str);
                    Toast.makeText(getActivity().getApplicationContext(), text,
                            Toast.LENGTH_SHORT).show();
                    if (!userExists() | !(passwordCorrect())) {
                        text = getResources().getString(
                                R.string.error_username_str);
                        Toast.makeText(getActivity().getApplicationContext(), text,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Intent i = new Intent(getActivity(), DiaryActivity.class);
                        startActivity(i);
                    }
                }


                //sharedPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);

                //get username and password from EditText
                String userName = username_ET.getText().toString();
                String password = password_ET.getText().toString();


                if(username_ET.length() > 0 && password_ET.length() > 0) {
                    String uName = null;
                    String uPassword = null;



                    if (sharedPreferences.contains(userName)) {
                        uName = sharedPreferences.getString("userName", "");

                    }

                    if (sharedPreferences.contains(password)) {
                        uPassword = sharedPreferences.getString("password", "");

                    }

                    //start new activity
                    if (userName.equals(uName) && password.equals(uPassword)) {


                        Toast.makeText(getActivity(), "You entered: " + uName, Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(getActivity(), DiaryActivity.class);
                        startActivity(i);
                    }
                }
                //String userName = sharedPreferences.getString("userName", "");
                //String pw = sharedPreferences.getString("password", "");

                //sharedPreferences.getString("uid", "");
                //sharedPreferences.getString("pwd", "");
            }   
        });

        register_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                FragmentManager FM = getFragmentManager();
                FragmentTransaction FT = FM.beginTransaction();
                RegisterFragment RG = new RegisterFragment();
                FT.replace(R.id.register_fragment_id, RG);
                FT.commit();
            }   
        });
        return v;
    }

    // getter for the user name
    public  String getUsername() {
        String str = username_ET.getText().toString();
        return str;// returns the user name
    }// end of getUsername()

    private boolean passwordCorrect() {

        // prefix the key with the user name
        if (sharedPreferences.contains(username + "_" + KEY_UID)) {
            String pwd = sharedPreferences.getString(username + "_"
                    + KEY_PASSWORD, "");
            if (pwd.equals(password_ET.getText().toString()))
                return true;
        }
            return false;

    }
    // getter for the user name

    private boolean userExists() {

        // prefix the key with the user name
        if (sharedPreferences.contains(username + "_" + KEY_UID)) {
            String uID = sharedPreferences.getString(username + "_" + KEY_UID,
                    "");
            if (uID.equals(username_ET.getText().toString()))
                return true;
        }

            return false;

    }// end of userExists()

    private boolean isValid() {
        boolean idEmpty = false;
        boolean passEmpty = false;
        if ((username_ET.getText().toString().isEmpty())) {
            idEmpty = true;
            String text = getResources()
                    .getString(R.string.error_emptyUsername);
            Toast.makeText(getActivity().getApplicationContext(), text, Toast.LENGTH_SHORT)
                    .show();
        }
        if ((password_ET.getText().toString().isEmpty())) {
            passEmpty = true;
            String text = getResources()
                    .getString(R.string.error_emptyPassword);
            Toast.makeText(getActivity().getApplicationContext(), text, Toast.LENGTH_SHORT)
                    .show();
        }
        return !(idEmpty | passEmpty);
    }// end of isValid()

}

1 个答案:

答案 0 :(得分:1)

您正在使用其他密钥在LoginFragment中获取数据。即 您正在尝试访问不存在的首选项。更改您的代码,如下所示

LoginFragment:

private boolean userExists() {

    String uID = sharedPreferences.getString("userName" + "_" + KEY_UID, "");

    return (uID.equals(username_ET.getText().toString()))

}

也可以将其更改为密码。