SharedPreference并不能保存在Android上

时间:2015-07-27 13:16:54

标签: android sharedpreferences

我正在使用SharedPreference,但我无法保存信息。

这些是我的代码:

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SharedPrefApp extends Activity implements View.OnClickListener {

    Button buton1 , buton2 ;
    EditText etv1 , etv2 ;
    TextView tv1;
    private static SharedPreferences sharedPref;
    protected void onCreate(Bundle bambam){
        super.onCreate(bambam);
        setContentView(R.layout.sharedpref_xml);
        buton1 = ( Button) findViewById(R.id.button12);
        buton2 = ( Button) findViewById(R.id.button13);
        etv1= (EditText) findViewById(R.id.editText4);
        etv2= (EditText) findViewById(R.id.editText5);
        tv1 = (TextView) findViewById(R.id.textView12);
        buton1.setOnClickListener(this);
        buton2.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button12:
                sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("isim" , etv1.getText().toString());
                editor.putString("sifre" , etv2.getText().toString());
                editor.apply();
                Toast.makeText(this , "Kaydedildi" , Toast.LENGTH_SHORT).show();
                break;
            case R.id.button13:
                sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE);
                String a = sharedPref.getString("isim", "olmadı");
                String b = sharedPref.getString("sifre" , "olmadı");
                tv1.setText(a + " " + b);
                Toast.makeText(this, "Gosterildi" , Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

它在应用程序中返回olmadı olmadı。为什么它不起作用?

3 个答案:

答案 0 :(得分:0)

为什么使用editor.apply()方法 尝试使用commit()方法

例如

editor.commit()

答案 1 :(得分:0)

尝试以下代码

   sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
   sharedprefs.edit.putString("isim" , etv1.getText().toString()).commit();

哦男孩......你的getString应该如下所示..

String a = sharedPref.getString("isim", null);
String b = sharedPref.getString("sifre" , null);

答案 2 :(得分:0)

您的代码中有拼写错误。您将name拼写为nama,导致您尝试存储并从两个不同的偏好设置中获取值。

您获得共享偏好设置的第一个按钮(R.id.button12)调用是:

sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );

将其更改为:

sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE );