[英]Storing text in android studio using shared preferences?
I'm trying to store a user's submitted name with a button click to be retrieved and used in another activity. 我正在尝试通过单击按钮来存储用户的提交名称,以便在另一个活动中进行检索和使用。 Currently I'm getting an error that I haven't been able to resolve and any help would be appreciated. 目前,我遇到一个无法解决的错误,我们将不胜感激。
The error is Cannot resolve method 'getSharedPreferences(java.lang.String, int)' 错误是无法解析方法“ getSharedPreferences(java.lang.String,int)”
Here's my code 这是我的代码
package net.androidbootcamp.gamecompanion;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.text.DecimalFormat;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.MODE_PRIVATE;
public class SettingsActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
final EditText enterName1 = (EditText) findViewById(R.id.enterName1);
final EditText enterName2 = (EditText) findViewById(R.id.enterName2);
Button btnOK = (Button) findViewById(R.id.btnOK);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
btnOK.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String n = enterName1.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
// Toast.makeText(SettingsActivity.this, "Player name set!", Toast.LENGTH_LONG).show();
}
});
}
} }
SharedPreferences shredpreferences=getApplicationContext().getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
You need to call getSharedPreferences()
on a Context
. 您需要在Context
上调用getSharedPreferences()
。
So, change 所以,改变
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
To 至
sharedpreferences = this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.