共享首选项Android Studio [英] Shared Preferences Android Studio

查看:96
本文介绍了共享首选项Android Studio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的代码,我试图检索共享的首选项,我认为它已正确保存,但是当我返回登录屏幕时,所有数据都消失了.回到该屏幕时,我需要保留它. 因此,我在个人资料页面的三行中分别输入了姓名,年龄和ID. 然后我按保存按钮 然后,通过在操作栏上按回去,转到上一页. 当我返回个人资料页面时,我的信息仍应存在,但不存在 有帮助吗?

For the code below I am trying to retrieve the shared preference, I think it saved correctly but when I go back to the login screen all the data is gone. I need it to remain when I go back to this screen. So i enter name, age and id into three separate lines on the profile page. Then i press the save button Then go to the page before by pressing back on the action bar. And when i go back to the profile page my info should still be there but its not Any help?

 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;

    }
}

推荐答案

要保存数据,请使用以下代码示例

To save data use the following code sample

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();

要获取数据,请使用以下代码示例

To retrieve the data use the following code sample

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()中进行检索,因此将它们全局声明是有用的,以避免编写额外的代码行.
  • The first parameter of getSharedPreferences is your package name, basically the first line in your code.
  • You don't need to create multiple SharedPreferences instances, one is enough
  • You don't need to create multiple SharedPreferences.Editor instances, one is also enough.
  • You might not want to use a random key, such as the user's username for saving data, since you would then need to pass the key to other activities through intents, and if you are going to do that, why not send the username instead of the key?
  • Use editor.apply() instead of editor.commit()
  • It is common to save data in onPause() and retrieve it in onResume(), so it can be useful to declare them global, to avoid writing extra lines of code.

这篇关于共享首选项Android Studio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆