Android add string to shared preferences

杀马特。学长 韩版系。学妹 提交于 2021-02-20 04:17:41

问题


my task is to write simple application:

1. user writes a String in a Text field and save it to SharedPreferences (his note)

    saveButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            text = textEtxt.getText().toString();

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(textEtxt.getWindowToken(), 0);

            // save to ShPr
            sharedPreference.save(context, text);
            Toast.makeText(context,
                    getResources().getString(R.string.saved),
                    Toast.LENGTH_LONG).show();


        }
    });

2. saving an object in SharedPreferences class

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. getting an object in SharedPreference class

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. read all notes that user has been written before (in the other activity)

protected void onCreate (Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
    sharedPreference = new SharedPreference();
    findViewsById();
    text += sharedPreference.getValue(context);
    textTxt.append(text);

}

My problem's : my program always overrides older String so i can have only 1 (the latest note) in reading activity. Where am I wrong or what can I do to keep my Strings added to existings?


回答1:


Use HashSet to store notes into SharedPreferences.

#. Store notes into SharedPreferences:

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

#. Get notes from SharedPreferences:

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;
}

#. Read all notes from SharedPreferences and show on TextView:

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

Hope this will help~




回答2:


I created a class with some generic methods of code to use in my apps to save my time. So that I don't have to do the same thing again and again. Put this Helper class anywhere in your code, and access it's methods to use within your app. It has a-lot of helping methods that you can use in any application based on your requirements. After coping this class in your project, you can easily access it's methods by "Helper.anymethod()". For Shared Prefernces it has methods named "saveData()" and "getSavedData().

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentActivity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Helper {

private static ProgressDialog pd;

public static void saveData(String key, String value, Context context) {
    SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences("appData", 0);
    SharedPreferences.Editor editor;
    editor = sp.edit();
    editor.putString(key, value);
    editor.commit();
}

public static void deleteData(String key, Context context){
    SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences("appData", 0);
    SharedPreferences.Editor editor;
    editor = sp.edit();
    editor.remove(key);
    editor.commit();

}

public static String getSaveData(String key, Context context) {
    SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences("appData", 0);
    String data = sp.getString(key, "");
    return data;

}




public static long dateToUnix(String dt, String format) {
    SimpleDateFormat formatter;
    Date date = null;
    long unixtime;
    formatter = new SimpleDateFormat(format);
    try {
        date = formatter.parse(dt);
    } catch (Exception ex) {

        ex.printStackTrace();
    }
    unixtime = date.getTime();
    return unixtime;

}

public static String getData(long unixTime, String formate) {

    long unixSeconds = unixTime;
    Date date = new Date(unixSeconds); 
    SimpleDateFormat sdf = new SimpleDateFormat(formate);  
    String formattedDate = sdf.format(date);
    return formattedDate;
}

public static String getFormattedDate(String date, String currentFormat,
        String desiredFormat) {
    return getData(dateToUnix(date, currentFormat), desiredFormat);
}




public static double distance(double lat1, double lon1, double lat2,
        double lon2, char unit) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    if (unit == 'K') {
        dist = dist * 1.609344;
    } else if (unit == 'N') {
        dist = dist * 0.8684;
    }
    return (dist);
}

/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

public static int getRendNumber() {
    Random r = new Random();
    return r.nextInt(360);
}

public static void hideKeyboard(Context context, EditText editText) {
    InputMethodManager imm = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}

public static void showLoder(Context context, String message) {
    pd = new ProgressDialog(context);

    pd.setCancelable(false);
    pd.setMessage(message);
    pd.show();
}

public static void showLoderImage(Context context, String message) {
    pd = new ProgressDialog(context);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setCancelable(false);
    pd.setMessage(message);
    pd.show();
}

public static void dismissLoder() {
    pd.dismiss();
}

public static void toast(Context context, String text) {

    Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
/*
public static Boolean connection(Context context) {
    ConnectionDetector connection = new ConnectionDetector(context);
    if (!connection.isConnectingToInternet()) {

        Helper.showAlert(context, "No Internet access...!");
        //Helper.toast(context, "No internet access..!");
        return false;
    } else
        return true;
}*/

public static void removeMapFrgment(FragmentActivity fa, int id) {

    android.support.v4.app.Fragment fragment;
    android.support.v4.app.FragmentManager fm;
    android.support.v4.app.FragmentTransaction ft;
    fm = fa.getSupportFragmentManager();
    fragment = fm.findFragmentById(id);
    ft = fa.getSupportFragmentManager().beginTransaction();
    ft.remove(fragment);
    ft.commit();

}

public static AlertDialog showDialog(Context context, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message);

    builder.setPositiveButton("OK", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
            // TODO Auto-generated method stub

        }
    });

    return builder.create();
}

public static void showAlert(Context context, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Alert");
    builder.setMessage(message)
            .setPositiveButton("Ok", new OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            }).show();
}

public static boolean isURL(String url) {
    if (url == null)
        return false;

    boolean foundMatch = false;
    try {
        Pattern regex = Pattern
                .compile(
                        "\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]",
                        Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher regexMatcher = regex.matcher(url);
        foundMatch = regexMatcher.matches();
        return foundMatch;
    } catch (PatternSyntaxException ex) {
        // Syntax error in the regular expression
        return false;
    }
}

public static boolean atLeastOneChr(String string) {
    if (string == null)
        return false;

    boolean foundMatch = false;
    try {
        Pattern regex = Pattern.compile("[a-zA-Z0-9]",
                Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher regexMatcher = regex.matcher(string);
        foundMatch = regexMatcher.matches();
        return foundMatch;
    } catch (PatternSyntaxException ex) {
        // Syntax error in the regular expression
        return false;
    }
}

public static boolean isValidEmail(String email, Context context) {
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        return true;
    } else {
        // Helper.toast(context, "Email is not valid..!");

        return false;
    }
}

public static boolean isValidUserName(String email, Context context) {
    String expression = "^[0-9a-zA-Z]+$";
    CharSequence inputStr = email;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        return true;
    } else {
        Helper.toast(context, "Username is not valid..!");
        return false;
    }
}

}

One last thing make sure you have appropriate permissions in your "AndroidManifest" class.




回答3:


What is PREFS_KEY? Looks like its a constant Key.

So basically you are writing into the SharedPreference to the same key. SharedPreferences being a Hashmap has only one value for each key, and hence everytime you write it, only the last value remains.

To solve your problem, the best solution looks like to have distinct key-value pairs, or have an arraylist of strings as the value

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

Then use the below link to save an arraylist Save ArrayList to SharedPreferences

public ArrayList<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:


Add this depandence in your build.gradle

compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'

Creat myPraf.java class

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

and creat your Singlton or copy past this code mySinglton.java

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;
   }




}

then when you want to save the your java object jast call this mathod

myPraf.getAllPraf(context)) // this will creat the SharedPref if already not created
     myPraf.saveObjectToSharedPreference(Context context,  String serializedObjectKey, Object object)

to get your java object just call this mathod `

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

or get your All java objs keys

Set myPrafKeysSet =myPraf.getAllPraf(mySinglton.getInStance(context))



回答5:


I think you should get the preferences first and then save it. For example:

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

text = text + textinput;

sharedPreference.save(context, text);


来源:https://stackoverflow.com/questions/44035216/android-add-string-to-shared-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!