繁体   English   中英

使用共享首选项在Android Studio中存储文本?

[英]Storing text in android studio using shared preferences?

我正在尝试通过单击按钮来存储用户的提交名称,以便在另一个活动中进行检索和使用。 目前,我遇到一个无法解决的错误,我们将不胜感激。

错误是无法解析方法“ 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();


        }
        });


}

}

SharedPreferences shredpreferences=getApplicationContext().getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);

您需要在Context上调用getSharedPreferences()

所以,改变

sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

sharedpreferences = this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM