Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android向共享首选项添加字符串_Android_String_Sharedpreferences - Fatal编程技术网

Android向共享首选项添加字符串

Android向共享首选项添加字符串,android,string,sharedpreferences,Android,String,Sharedpreferences,我的任务是编写简单的应用程序: 1。用户在文本字段中写入一个字符串,并将其保存到SharedReferences(他的笔记) 2.在SharedReferences类中保存对象 public void save (Context context, String text) { SharedPreferences settings; Editor editor; settings = PreferenceManager.getDefaultSharedPreference

我的任务是编写简单的应用程序:

1。用户在文本字段中写入一个字符串,并将其保存到SharedReferences(他的笔记)

2.在SharedReferences类中保存对象

public void save (Context context, String text) {

    SharedPreferences settings;
    Editor editor;
    settings = PreferenceManager.getDefaultSharedPreferences(context);
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();

    editor.putString(PREFS_KEY, text);

    editor.commit();

}
3.获取SharedReference类中的对象

public String getValue(Context context) {

    SharedPreferences settings;
    String text;
    settings = PreferenceManager.getDefaultSharedPreferences(context);
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    text = settings.getString(PREFS_KEY, null);
    return text;
}
4.阅读用户以前写过的所有笔记(在其他活动中)


我的问题是:我的程序总是覆盖旧的字符串,所以我在阅读活动中只能有1个(最新的注释)。我哪里错了?我该怎么做才能将我的字符串添加到现有字符串中?

我认为您应该先获取首选项,然后保存它。例如:

String textinput = textEtxt.getText().toString();
String text = settings.getString(PREFS_KEY, "");

text = text + textinput;

sharedPreference.save(context, text);

使用
HashSet
notes
存储到
SharedReferences

#.
注释
存储到
共享参考中

public static final String PREFS_KEY = "notes";

............
.................
public void saveNote(Context context, String text) {

    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    // Get existing notes
    Set<String> notes = getNotes();

    // Add new note to existing notes
    notes.add(text);

    // Store notes to SharedPreferences
    editor.putStringSet(PREFS_KEY, notes);
    editor.apply();
}
public Set<String> getNotes(Context context) {

    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

    // Get notes
    Set<String> notes = settings.getStringSet(PREFS_KEY, new HashSet<String>());

    return notes;
}
#.阅读
共享参考资料中的所有
注释
,并在
文本视图
上显示:

protected void onCreate (Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);

    sharedPreference = new SharedPreference();
    findViewsById();

    // Get notes
    ArrayList<String> noteList = new ArrayList<String>(sharedPreference.getNotes(context));

    StringBuilder stringBuilder = new StringBuilder();

    // Looping through all notes and append to StringBuilder
    for(int i = 0; i < noteList.size(); i++)
        stringBuilder.append("\n" + noteList.get(i));

    // Set note text to your TextView   
    textView.setText(stringBuilder.toString());
}
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
SharedReference=新的SharedReference();
findViewsById();
//记笔记
ArrayList noteList=新的ArrayList(SharedReference.getNotes(context));
StringBuilder StringBuilder=新的StringBuilder();
//循环浏览所有注释并附加到StringBuilder
对于(int i=0;i

希望这会有所帮助~

我创建了一个类,其中包含一些通用的代码方法,可以在我的应用程序中使用,以节省时间。这样我就不用一次又一次地做同样的事情了。将此帮助器类放在代码中的任意位置,并访问其在应用程序中使用的方法。它有很多帮助方法,您可以根据自己的需求在任何应用程序中使用。在项目中处理完这个类之后,您可以通过“Helper.anymethod()”轻松访问它的方法。对于共享首选项,它具有名为“saveData()”和“getSavedData()的方法”


最后一件事是确保您在“AndroidManifest”类中拥有适当的权限。

什么是PREFS_键?看起来它是一个常量键

因此,基本上您是在向SharedReference中写入同一个键。SharedReference作为哈希映射,每个键只有一个值,因此每次写入时,只保留最后一个值

为了解决您的问题,最好的解决方案是使用不同的键值对,或者使用字符串的arraylist作为值

public void save (Context context, String text) {

    SharedPreferences settings;
    Editor editor;
    settings = PreferenceManager.getDefaultSharedPreferences(context);
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();
    ArrayList<String> notes = getValue(context);
    notes.add(text);
}
public void保存(上下文、字符串文本){
共享引用设置;
编辑;
设置=PreferenceManager.GetDefaultSharedReferences(上下文);
设置=context.getSharedReferences(PREFS\u NAME,context.MODE\u PRIVATE);
editor=settings.edit();
ArrayList notes=getValue(上下文);
注:增加(文本);
}
然后使用下面的链接保存arraylist

public ArrayList getValue(上下文){
共享引用设置;
字符串文本;
设置=PreferenceManager.GetDefaultSharedReferences(上下文);
设置=context.getSharedReferences(PREFS\u NAME,context.MODE\u PRIVATE);
text=settings.getString(PREFS_键,null);
返回文本;
}

在您的build.gradle中添加此depandence

compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'
创建myPraf.java类

public class myPraf {

    public static void saveObjectToSharedPreference(Context context,  String serializedObjectKey, Object object) {
        SharedPreferences sharedPreferences = mySinglton.getInStance(context);
        SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
        final Gson gson = new Gson();
        String serializedObject = gson.toJson(object);
        sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
        sharedPreferencesEditor.apply();

    }
    public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceKey, Class<GenericClass> classType) {
        SharedPreferences sharedPreferences = mySinglton.getInStance(context);
        if (sharedPreferences.contains(preferenceKey)) {
            final Gson gson = new Gson();
            return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
        }
        return null;
    }
    public static Set getAllPraf(SharedPreferences prefs)
    {
        Map<String,?> entries = prefs.getAll();
        Set<String> keys = entries.keySet();
        for (String key : keys) {

            Log.d("CustomAdapter",key);

        }
        Log.d("CustomAdapter",""+keys.size());
        return keys;
    }

    public static void deletePraf(Context context  , String mPrafKey)
    {
        SharedPreferences settings = mySinglton.getInStance(context);
        settings.edit().remove(mPrafKey).apply();
    }
    public static int getPrafSize(Context context)
    {
        Map<String,?> entries = mySinglton.getInStance(context).getAll();
        Set<String> keys = entries.keySet();
        return keys.size();
    }
}
然后,当您想保存java对象时,请调用此方法

myPraf.getAllPraf(context)) // this will creat the SharedPref if already not created
     myPraf.saveObjectToSharedPreference(Context context,  String serializedObjectKey, Object object)
要获取java对象,只需调用此方法`

myPraf.getSavedObjectFromPreference(Context context, String preferenceKey, Class<GenericClass> classType)`

如果我错了,请纠正我,您想在sharedPref中保存多个java对象,但当前它只存储一个?旧java对象替换为新java对象?正是…….thx,这是我一直在寻找的-解决问题的最简单方法:)如果我的答案看起来很完美,请将此标记为正确答案。
compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'
public class myPraf {

    public static void saveObjectToSharedPreference(Context context,  String serializedObjectKey, Object object) {
        SharedPreferences sharedPreferences = mySinglton.getInStance(context);
        SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
        final Gson gson = new Gson();
        String serializedObject = gson.toJson(object);
        sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
        sharedPreferencesEditor.apply();

    }
    public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceKey, Class<GenericClass> classType) {
        SharedPreferences sharedPreferences = mySinglton.getInStance(context);
        if (sharedPreferences.contains(preferenceKey)) {
            final Gson gson = new Gson();
            return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
        }
        return null;
    }
    public static Set getAllPraf(SharedPreferences prefs)
    {
        Map<String,?> entries = prefs.getAll();
        Set<String> keys = entries.keySet();
        for (String key : keys) {

            Log.d("CustomAdapter",key);

        }
        Log.d("CustomAdapter",""+keys.size());
        return keys;
    }

    public static void deletePraf(Context context  , String mPrafKey)
    {
        SharedPreferences settings = mySinglton.getInStance(context);
        settings.edit().remove(mPrafKey).apply();
    }
    public static int getPrafSize(Context context)
    {
        Map<String,?> entries = mySinglton.getInStance(context).getAll();
        Set<String> keys = entries.keySet();
        return keys.size();
    }
}
public class mySinglton
{
    private static SharedPreferences mySingltonSharePraf;


    private mySinglton() {
    }

    public static SharedPreferences getInStance(Context context)

   {
       if(mySingltonSharePraf==null)
       {

           mySingltonSharePraf = context.getSharedPreferences("mPreference1",0);

       }
       return mySingltonSharePraf;
   }




}
myPraf.getAllPraf(context)) // this will creat the SharedPref if already not created
     myPraf.saveObjectToSharedPreference(Context context,  String serializedObjectKey, Object object)
myPraf.getSavedObjectFromPreference(Context context, String preferenceKey, Class<GenericClass> classType)`
Set myPrafKeysSet =myPraf.getAllPraf(mySinglton.getInStance(context))