本文介绍了注销清除SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个登录页面,该页面将usernamepassword保存到SharedPreferences.我还有另一个Activity类,其中包括注销按钮.单击注销按钮时,我想清除SharedPreferences.问题是我没有从此类获得SharedPreferences.如何获得SharedPreferences?

I have a login page that saves username and password to SharedPreferences. I have another Activity class that includes a logout button. I want to clear SharedPreferences when I click the logout button. The problem is that I don't get the SharedPreferences from this class. How can I get the SharedPreferences?

LoginPage

LoginPage

public class MainActivity extends Activity {
public SharedPreferences.Editor loginPrefsEditor;
    public  SharedPreferences loginPreferences;
    private Boolean saveLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    name = (EditText) findViewById(R.id.et_Username);
        pass = (EditText) findViewById(R.id.et_Password);
        login = (Button) findViewById(R.id.bt_Login);

         loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
         loginPrefsEditor = loginPreferences.edit();

         saveLogin = loginPreferences.getBoolean("saveLogin", false);

         if (saveLogin == true) {
                name.setText(loginPreferences.getString("username", ""));
                pass.setText(loginPreferences.getString("password", ""));
            }

        login.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                 name1 = name.getText().toString();
                 pass1 = pass.getText().toString();
               //new Thread (new Task()).start();
                    loginPrefsEditor.putBoolean("saveLogin", true);
                    loginPrefsEditor.putString("username", name1);
                    loginPrefsEditor.putString("password", pass1);
                    loginPrefsEditor.commit();
                 new myAsyncTask().execute();
            }
        });
}

AnotherActivity中的退出按钮

Logout Button in AnotherActivity

 logout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching News Feed Screen

                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);
            }
        });

推荐答案

尝试一下!

logout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching News Feed Screen

             SharedPreferences preferences =getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
             SharedPreferences.Editor editor = preferences.edit();
             editor.clear();
             editor.apply();
             finish();
 });

这篇关于注销清除SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 20:13