SharedPreferences在安卓登录(SharedPreferences for login

2019-09-17 20:46发布

我的工作,需要登录的Android应用程序。 我要检查,当用户按下PostIdea活动按钮,然后选中登录或没有用户,如果没有的话重定向到登录页面,否则继续执行任务。

在这里我使用该SharedPreferences。 现在,当我按下登录按钮,然后用户名和密码添加到SharedPreferences,当按下PostIdea活动,然后我得到了用户名和密码。

但我的问题是,当我重新启动应用程序,并去PostIdea活动不登录则记得SharedPreferences data.How的上次登录(用户名/密码),我可以从SharedPreferences删除数据,让自己的应用程序正常工作。 让我知道我错或有我的问题没有其他解决办法。

谢谢。

LoginActivity.class

public class LoginActivity extends CheerfoolznativeActivity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_login);
    setHeader("Login");

    editUser = (EditText) findViewById(R.id.login_useredit);
    editPass = (EditText) findViewById(R.id.login_passedit);
    txterror = (TextView) findViewById(R.id.login_error);
    textlogin = (TextView) findViewById(R.id.login_postidea_textView);
    btngotoregister = (Button) findViewById(R.id.login_btnLinkToRegisterScreen);
    btnlogin = (Button) findViewById(R.id.login_button);
    pgb = (ProgressBar) findViewById(R.id.login_progressBar);

    btnlogin.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            new Login().execute();

        }
    });

}

public class Login extends AsyncTask<Void, Void, Void> {

    int i = 0;
    String uName ;
    String Password;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        uName = editUser.getText().toString().trim();
        Password = editPass.getText().toString().trim();

        if (uName.equals("") | Password.equals("")) {
            Toast.makeText(getApplicationContext(), "Enter the Data",
                    Toast.LENGTH_SHORT).show();

            if (editUser.length() == 0) {
                editUser.setError("Enter Username");
            }
            if (editPass.length() == 0) {
                editPass.setError("Enter Password");
            }
        } else {

            pgb.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub


            String loginURL = "http://www.cheerfoolz.com/rest/user/login";

            strResponse = util.makeWebCall(loginURL, uName, Password);

        return null;
    }

    @Override
    public void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

    txterror.setText("");

            try {
                if (strResponse.substring(KEY_SUCCESS) != null) {
                    txterror.setText("");

                    // SharedPreferences Logic
                    SharedPreferences userDetails =getSharedPreferences("userdetails", MODE_PRIVATE);
                    Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("username", uName);
                    edit.putString("password", Password);
                    edit.commit();


                    new FetchUserProfileTask().execute();

                } else {
                    txterror.setText("Username and Password Not valid !!!");
                }
            } catch (Exception e) {
                // TODO: handle exception
            }

    }

}

public class FetchUserProfileTask extends AsyncTask<Void, Void, Void> {

    int i = 0;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();


    }

    @Override
    protected Void doInBackground(Void... params) {

        //logic for the featch user profile data

    return null;
    }

    @Override
    public void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

         pgb.setVisibility(View.GONE);
        displayProfile();

    }
}

public void displayProfile() {

    Intent in1 = new Intent(LoginActivity.this, post_myprofile.class);
    in1.putExtra("loginObject", bean);
    startActivity(in1);
}

}

Post_idea_Activity.class

public class Post_idea_Activity extends CheerfoolznativeActivity {

TextView txtwelcome;
String Uname="";
String pass = ""; 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
    System.out.println("value of the userdertails ==========>"+ userDetails);
    //String Uname="";
    //String pass= ""; 

    Uname = userDetails.getString("username", "");
    pass = userDetails.getString("password", "");

    Toast.makeText(getApplicationContext(),"username : "+Uname +" \n password :"+pass, Toast.LENGTH_SHORT).show();

    if (Uname.equals(null)) 
    {
        Intent in1 = new Intent(this, LoginActivity.class);
        in1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(in1);

    }
    else {

        setContentView(R.layout.post_idea);
        setHeader("Post idea");

        txtwelcome =(TextView)findViewById(R.id.post_welcome_text);
             }


       }

   //  coding for the layout
}

Answer 1:

清除您的共享偏好您的应用程序启动时。

SharedPreferences userDetails =getSharedPreferences("userdetails", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.commit();

您可以在应用程序类应用程序的写。



Answer 2:

在闪屏清除共享prefernce使用闪屏下面的代码,这意味着你的应用程序的第一项活动

SharedPreferences userDetails =getSharedPreferences("userdetails", MODE_PRIVATE);
                    Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("username", "");
                    edit.putString("password", "");
                    edit.commit();


Answer 3:

    Write in login page.....
    //variables
    String PREFS_USER_ID = "USER_ID";
    String  PREF_NAME = "Pref";
    String  USER_ID;
    //write in where u want to store data....
    setPreferences(PREF_NAME, PREFS_USER_ID, USER_ID);
    // methods
    private void setPreferences(String preferenceName, String key, String value)
    {
            SharedPreferences settings = getSharedPreferences(preferenceName, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(key, value);
            editor.commit();
    }
    private String getSharedPreferences(String preferenceName, String key)
    {
            // Restore preferences
            SharedPreferences settings = getSharedPreferences(preferenceName, 0);
            String value = settings.getString(key, null);
            return value;
    }
    in the other activity u get user name and password.........
    String userid=getSharedPreferences(PREF_NAME, PREFS_USER_ID);
    //method
    private String getSharedPreferences(String preferenceName, String key)
    {
        // Restore preferences
            SharedPreferences settings = getSharedPreferences(preferenceName, 0);
            String value = settings.getString(key, null);
            return value;
    }
// for delete  or remove the data from sharepreferences
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = wmbPreference.edit();
    editor.clear();
    editor.commit();


文章来源: SharedPreferences for login in android