我的任务是编写简单的应用程序:
1。用户在文本字段中写入字符串并将其保存到SharedPreferences(他的注释)
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。在SharedPreferences类中保存对象
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。在SharedPreference类中获取对象
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. 阅读用户之前已写过的所有笔记(在其他活动中)
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
sharedPreference = new SharedPreference();
findViewsById();
text += sharedPreference.getValue(context);
textTxt.append(text);
}
我的问题:我的程序总是覆盖旧的字符串,所以我在阅读活动中只能有1个(最新的注释)。我错在哪里或者我能做些什么来保持我的字符串被添加到存在中?
答案 0 :(得分:0)
使用HashSet
将notes
存储到SharedPreferences
。
#。将notes
存储到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();
}
#。从notes
获取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;
}
#。阅读notes
中的所有SharedPreferences
并在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());
}
希望这会有所帮助〜
答案 1 :(得分:0)
我创建了一个类,其中包含一些通用的代码方法,可以在我的应用程序中使用,以节省我的时间。所以我不必一次又一次地做同样的事情。将此Helper类放在代码中的任何位置,并访问它在您的应用程序中使用的方法。它有许多帮助方法,您可以根据您的要求在任何应用程序中使用它们。在项目中处理此类之后,您可以通过“Helper.anymethod()”轻松访问它的方法。对于共享首选项,它具有名为“saveData()”和“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;
}
}
}
最后一件事是确保您在“AndroidManifest”课程中拥有适当的权限。
答案 2 :(得分:0)
什么是PREFS_KEY?看起来像是一个不变的密钥。
所以基本上你要将SharedPreference写入相同的密钥。作为Hashmap的SharedPreferences每个键只有一个值,因此每次编写它时,只剩下最后一个值。
要解决您的问题,最佳解决方案似乎具有不同的键值对,或者具有字符串的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);
}
然后使用以下链接保存一个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;
}
答案 3 :(得分:0)
在 build.gradle
中添加此depandencecompile 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();
}
}
并创建您的Singlton或复制此代码 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;
}
}
然后当你想保存你的java对象jast 调用这个mathod
myPraf.getAllPraf(context)) // this will creat the SharedPref if already not created
myPraf.saveObjectToSharedPreference(Context context, String serializedObjectKey, Object object)
获取 您的java对象只需调用此mathod`
myPraf.getSavedObjectFromPreference(Context context, String preferenceKey, Class<GenericClass> classType)`
或获取所有 java objs键
Set myPrafKeysSet =myPraf.getAllPraf(mySinglton.getInStance(context))
答案 4 :(得分:-1)
我认为您应首先获取首选项然后保存。例如:
String textinput = textEtxt.getText().toString();
String text = settings.getString(PREFS_KEY, "");
text = text + textinput;
sharedPreference.save(context, text);