我试图存储用户提交的名称,并点击按钮进行检索并在另一项活动中使用。目前我收到了一个我无法解决的错误,我们将不胜感激任何帮助。
错误是无法解决方法' getSharedPreferences(java.lang.String,int)'
这是我的代码
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();
}
});
}
}
答案 0 :(得分:0)
SharedPreferences shredpreferences=getApplicationContext().getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
答案 1 :(得分:0)
您需要在getSharedPreferences()
上致电Context
。
所以,改变
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
要
sharedpreferences = this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);