android – 注销清除SharedPreferences

前端之家收集整理的这篇文章主要介绍了android – 注销清除SharedPreferences前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有登录页面,将用户名和密码保存到共享首选项.我有另一个包含注销按钮的Activity类.我想在单击“注销”按钮时清除“共享首选项”.问题是我没有从这个类获得SharedPreferences.我怎样才能获得SharedPreferences?

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.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.commit();
             finish();
 });
原文链接:https://www.f2er.com/android/317421.html

猜你在找的Android相关文章