Shared Preferences Android Studio

4

对于下面的代码,我正在尝试检索共享首选项,我认为它已经保存正确了,但是当我返回到登录屏幕时,所有数据都消失了。我需要在返回到此屏幕时保留它。 所以我在个人资料页面上单独输入姓名、年龄和ID。 然后我按保存按钮 然后通过操作栏上的“返回”按钮返回上一页。 当我回到个人资料页面时,我的信息应该仍然存在,但实际上并没有。 有什么帮助吗?

 package com.example.myprofile;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.Savepoint;

public class Profile extends AppCompatActivity {

             protected EditText NameEditText;
             protected EditText AgeEditText;
             protected EditText IDEditText;
             protected Button saveButton;
             protected Button settings_id;
             String name;
             String age;
             String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        EditText mEdit = (EditText) findViewById(R.id.NameEditText);
        mEdit.setEnabled(false);
        EditText mEdit1 = (EditText) findViewById(R.id.AgeEditText);
        mEdit1.setEnabled(false);
        EditText mEdit2 = (EditText) findViewById(R.id.IDEditText);
        mEdit2.setEnabled(false);

        NameEditText = (EditText) findViewById(R.id.NameEditText);
        AgeEditText = (EditText) findViewById(R.id.AgeEditText);
        IDEditText = (EditText) findViewById(R.id.IDEditText);
        settings_id = (Button) findViewById(R.id.settings_id);
        saveButton = (Button) findViewById(R.id.SaveButton);



         SharedPreferences prefs = getSharedPreferences(getString(R.string.ProfileName), Context.MODE_PRIVATE);
         name = prefs.getString("userName", "");
         age = prefs.getString("userAge", "");
         id = prefs.getString("userID", "");


        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                String name = NameEditText.getText().toString();
                String age = AgeEditText.getText().toString();
                String id = IDEditText.getText().toString();
                SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.ProfileName), Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(getString(R.string.ProfileName), name);
                editor.putString(getString(R.string.ProfileAge), age);
                editor.putString(getString(R.string.ProfileID), id);
                editor.apply();


                  if (Integer.parseInt(age) < 18)
                {
                    Toast toast1 = Toast.makeText(getApplicationContext(), "Invalid Age", Toast.LENGTH_LONG);
                    toast1.show();
                }
                  else if (!name.isEmpty() && !age.isEmpty() && !id.isEmpty())
                  {
                      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                      Toast toast = Toast.makeText(getApplicationContext(), "Name Saved!", Toast.LENGTH_LONG);
                      toast.show();
                  }
                  else
                {
                    Toast toast2 = Toast.makeText(getApplicationContext(), "Incomplete Info", Toast.LENGTH_LONG);
                    toast2.show();
                }


            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings_id:
            {
                EditText mEdit = (EditText) findViewById(R.id.NameEditText);
                mEdit.setEnabled(true);
                EditText mEdit1 = (EditText) findViewById(R.id.AgeEditText);
                mEdit1.setEnabled(true);
                EditText mEdit2 = (EditText) findViewById(R.id.IDEditText);
                mEdit2.setEnabled(true);
                saveButton.setEnabled(Boolean.parseBoolean("True"));
            }
            default:
                return super.onOptionsItemSelected(item);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;

    }
}

你在检索数据时是否传递了正确的密钥?更多信息请参考 https://developer.android.com/training/data-storage/shared-preferences#java 和 https://dev59.com/OGAg5IYBdhLWcg3w7enx。 - user3678528
我认为没有必要使用多个SharedPreferences和SharedPreferences.Editor对象,一个对象就可以完成任务,只需使用不同的键来区分。我认为你应该从相同的SharedPreferences对象中使用相同的键进行读取(*在初始化时读取共享时传递与保存时使用的相同键),我相信这将解决你的问题。 - Ashutosh Sagar
在2020年,Google发布了一种新的数据存储方式来替代Shared Preference... 它是用Kotlin开发的。https://stackoverflow.com/questions/48001014/how-to-get-value-of-sharedpreferences-android/64301737#64301737 - Ucdemir
5个回答

3

保存

SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyname",true);
editor.putString("keyname","string value");
editor.putInt("keyname","int value");
editor.putFloat("keyname","float value");
editor.putLong("keyname","long value");
editor.commit();

获取

SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
pref.getString("keyname",null);
pref.getInt("keyname",0);
pref.getFloat("keyname",0);
pref.getBoolean("keyname",true);
pref.getLong("keyname",0);
对于单个删除
SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("keyname");
editor.commit();

对于所有删除操作

SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();

1
使用以下代码示例来保存数据。
name = NameEditText.getText().toString();
age = AgeEditText.getText().toString();
id = IDEditText.getText().toString();

SharedPreferences prefs = getSharedPreferences(
      "com.example.myprofile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("userName", name);
editor.putString("userAge", age);
editor.putString("userID", id);
editor.apply();

使用以下代码示例检索数据

SharedPreferences prefs = getSharedPreferences(
    "com.example.myprofile", Context.MODE_PRIVATE);
name = prefs.getString("userName", "");
age = prefs.getString("userAge", "");
id = prefs.getString("userID", "");

onCreate 方法之前
String name;
String age;
String id;

解释:

  • getSharedPreferences的第一个参数是您的包名称,基本上是代码中的第一行。
  • 您不需要创建多个SharedPreferences实例,一个就足够了。
  • 您也不需要创建多个SharedPreferences.Editor实例,一个就足够了。
  • 您可能不想使用随机的key,例如用户的用户名来保存数据,因为您将需要通过意图将键传递给其他活动,如果您要这样做,为什么不发送用户名而不是键呢?
  • 使用editor.apply()而不是editor.commit()
  • 通常在onPause()中保存数据并在onResume()中检索它,因此将它们声明为全局变量可能很有用,以避免编写额外的代码行。

0

您可以像这样使用共享首选项

要在首选项中保存数据

SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = share.edit();
edit.putLong("user_id", 1);
edit.putString("token","1243434sfdfsf");
edit.commit();

从偏好设置中获取数据

SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);
share.getLong("user_id", 0);
share.getString("token", "");

您可以尝试使用此链接获取更多详细信息:Android中的共享首选项

0

尝试(在行末使用apply()):

editor.putString(getString(R.string.ProfileName), name).apply();
editor1.putString(getString(R.string.ProfileAge), age).apply();
editor2.putString(getString(R.string.ProfileID), id).apply();

尝试了,不幸的是没有成功。 - user10976749

0

您正在使用特定的字符串(getString(R.string.ProfileAge) ....)通过使用commit()或apply()在私有模式下将数据保存到共享首选项中:

SharedPreferences sharedPreferences1 = getSharedPreferences(getString(R.string.ProfileAge), Context.MODE_PRIVATE);
                SharedPreferences sharedPreferences2 = getSharedPreferences(getString(R.string.ProfileID), Context.MODE_PRIVATE);

但是在私人模式下,您不应该使用这些字符串来获取数据,而应该使用:

-

SharedPreferences sharedPref = getSharedPreferences(getString(R.string.ProfileAge), Context.MODE_PRIVATE);
String name = sharedPref.getString("key", "defaultValue");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接