如何使用sharedPrefrence putString?

How to use sharedPrefrence putString?

我想使用另一个 activity 的 sharedprefrence 字符串,但是没有传递值,它总是传递默认值? 创建变量 toast 显示 inp 值但未传递值

                name_next = (Button) findViewById(R.id.name_next);
                sp= getSharedPreferences("name_pref",Context.MODE_PRIVATE);

                name_next.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        inp = nameInput.getText().toString();
                        SharedPreferences.Editor editor= sp.edit();
                        editor.putString(inp,nameInput);
                        editor.commit();
                        Toast.makeText(com.calmo.name.this,"welcome "+inp,Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(name.this,MainActivity.class);
                        startActivity(intent);
                    }
                });```    
**Calling **
**The Value is always returned as error that is default**

```            SharedPreferences sp=getApplicationContext().getSharedPreferences("name_pref",Context.MODE_PRIVATE);
        String name_in =sp.getString("inp","Error");
        name.setText(name_in);

移除 inp = nameInput.getText().toString(); 在点击下 并改变 editor.putString(inp,nameInput); editor.putString("inp",nameInput.getText().toString());

public class AppSharedPreferences {
public static final String TAG = "AppSharedPreferences";
private static SharedPreferences sharedPref;

private String demo_string = "demo string's key"

public AppSharedPreferences() {

}

public static void init(Context context)
{
    if(sharedPref == null)
        sharedPref = context.getSharedPreferences(
            context.getPackageName(), Activity.MODE_PRIVATE);
}

public static void setDemoString(String demoString) {
    Editor prefs = sharedPref.edit();
    prefs.putString(demo_string, demoString);
    prefs.apply();
}

public static String getDemoString() {
    return sharedPref.getString(demo_string, "");
}}

把这个放在你想使用共享首选项的地方:

AppSharedPreferences.init(this);

您可以将 this 换成 activitycontext,具体取决于您使用代码的位置。

要设置优先值,请使用此代码:

AppSharedPreferences.setDemoString("Some Text");

从首选项中获取值:

String text = AppSharedPreferences.getDemoString();