如何在Android中使用SharedPreferences来存储,获取和编辑值

大兔子大兔子 提交于 2020-01-06 15:35:50

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

已关闭 。 这个问题需要更加集中。 它当前不接受答案。 了解更多

想改善这个问题吗? 更新问题,使其仅通过编辑此帖子来关注一个问题。

去年关闭。

这篇文章是社区维基 。 编辑现有答案以改善此职位。 它当前不接受新的答案。 了解更多

我想存储一个时间值,需要检索和编辑它。 如何使用SharedPreferences做到这一点?


#1楼

要将值存储在共享首选项中:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();

要从共享的首选项中检索值:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}

#2楼

通过SharedPreferences如何存储登录值的简单解决方案。

您可以扩展MainActivity类或其他将存储“您想要保留的东西的值”的类。 将其放入作家和读者类中:

public static final String GAME_PREFERENCES_LOGIN = "Login";

在这里, InputClass是输入类,而OutputClass是输出类。

// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";

// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();

// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();

现在,您可以像其他类一样在其他地方使用它。 以下是OutputClass

SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");

// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);

#3楼

editor.putString("text", mSaved.getText().toString());

在这里, mSaved可以是我们可以从中提取字符串的任何TextViewEditText 。 您只需指定一个字符串即可。 此处的文本将是保存从mSavedTextViewEditText )获得的值的键。

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

同样,也不需要使用程序包名称“ com.example.app”保存首选项文件。 您可以提及自己的首选名称。 希望这可以帮助 !


#4楼

来写 :

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();

读书 :

SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");

#5楼

在任何应用程序中,都可以通过PreferenceManager实例及其相关方法getDefaultSharedPreferences(Context)来访问默认首PreferenceManager

使用SharedPreference实例,可以使用getInt(String key,int defVal)检索任何首选项的int值。 在这种情况下,我们感兴趣的偏好是对立的。

在我们的案例中,我们可以使用edit()修改我们的案例中的SharedPreference实例,并使用putInt(String key, int newVal)我们增加了存在于应用程序之外并因此显示的应用程序计数。

为了进一步演示,请重新启动并重新启动应用程序,您会注意到,每次重新启动应用程序时,计数都会增加。

PreferencesDemo.java

码:

package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class PreferencesDemo extends Activity {
   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);

        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);

        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");

        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important
    }
}

main.xml

码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/text"  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello" />
</LinearLayout>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!