我想在应用程序中检索用户输入以供以后使用.
例如,系统会提示用户输入一周中的所有7天,并在editText框中键入"星期一","星期二"等.然后在应用程序中稍后会出现一个问题,询问您最喜欢的一天是什么时候?微调器将显示他们输入的日期的下拉列表供用户选择.
我想共享偏好对此有用,但我找不到一个很好的例子来给我一个起点.任何帮助,将不胜感激.
SharedPreferences用于在Android中保存应用程序数据.
commit()和apply()两者都用来保存在共享偏好的变化.
如Android库中所述:
public abstarct void apply():
Run Code Online (Sandbox Code Playgroud)
与commit()同步地将其首选项写入持久存储,apply()会立即将其更改提交到内存中的SharedPreferences,但会启动异步提交到磁盘,并且不会通知您任何失败.如果此SharedPreferences上的另一个编辑器在apply()尚未完成时执行常规commit(),则commit()将阻塞,直到完成所有异步提交以及提交本身.
public abstract boolean commit ():
Run Code Online (Sandbox Code Playgroud)
将您的首选项更改从此编辑器返回到它正在编辑的SharedPreferences对象.这以原子方式执行请求的修改,替换SharedPreferences中当前的任何内容.
这是否意味着所做的更改commit()是即时的apply()?哪一个更好?
如果我需要在下一个立即活动中使用相同的共享首选项值,我应该使用哪一个?正如我所看到的,如果更新了Preference的值,则在重新启动应用程序之前不会反映它.
美好的一天,我正在构建一个Android应用程序.我想在首选项中存储一组字符串,以便根据其登录信息跟踪谁使用了该应用程序.
我不想使用数据库,因此我知道我应该使用SharedPreferences来存储登录的人员列表.我希望能够重置此列表,以便将单独的数据记录为字符串而不是StringSets不是一种选择.使用单独的字符串意味着我必须保留这些字符串的另一个列表,以便我可以在需要时清理它们.StringSet更易于维护.
这是我到目前为止所做的:
//this is my preferences variable
SharedPreferences prefs = getSharedPreferences("packageName", MODE_PRIVATE);
//I create a StringSet then add elements to it
Set<String> set = new HashSet<String>();
set.add("test 1");
set.add("test 2");
set.add("test 3");
//I edit the prefs and add my string set and label it as "List"
prefs.edit().putStringSet("List", set);
//I commit the edit I made
prefs.edit().commit();
//I create another Set, then I fetch List from my prefs file
Set<String> fetch = prefs.getStringSet("List", null);
//I then convert it to an Array …Run Code Online (Sandbox Code Playgroud) 我已经设置了一个Checkbox,现在如果未经检查,mediaplayers应该立即取消静音,当检查立即静音时,现在问题是当我选中/取消选中复选框时,声音不会立即静音,但是最近我重新开始活动.. . 我怎么解决这个问题?
该计划的主要代码:
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;
SharedPreferences mypref;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); …Run Code Online (Sandbox Code Playgroud) 所以,我现在正面临这个奇怪的问题。我HAVE使用SharedPreferences.Editor()。提交()在我的Android应用程序,但是,因为文档在这里指出,
由于SharedPreferences实例是流程中的单例,因此如果您已经忽略了返回值,则可以安全地用apply()替换任何commit()实例。
您无需担心Android组件的生命周期及其与apply()写入磁盘的交互。该框架确保在切换状态之前完成对apply()的运行中磁盘写入。
基本上commit(),apply()如果您不使用返回值BUT,则可以安全地替换为BUT,这是这里提到的两者之间的区别,并且在Android Studio中警告说,这是commit()立即写入数据,而BUT apply()异步执行。
所以我的问题是,我正在更改应用程序中的语言,并且要在用户选择语言后重新启动应用程序。但是,当用户选择语言时,将输入当前选择的语言SharedPreferences。
现在,问题是:
每当我使用代码apply()代替此处commit()的代码并重新启动应用程序以在此处重新启动应用程序时,所做的更改都不会写入磁盘,因为当应用程序重新启动时,它不会更改当前语言,因为from的值SharedPreference不会更改,因为它不会立即写入磁盘。但是,无论何时使用commit(),更改都会立即写入,并且在重新启动应用程序后会成功更改语言。
因此,问题是:
如果有很大的不同,编写代码commit()并apply()声明使用apply()而不是完全安全的人会立即写出数据,但是会在后台执行呢?commit()commit()apply()
如果我构建了apk,如果我不使用返回值,它将在代码优化中commit()被替换apply()(我知道我可以通过构建应用程序的发行版来知道这一点,但是我仍然不确定,因为当我使用apply()veerery 时,它通常会更改1/10次,但确实会从SharedPreference更改值
一张纸条:
我有一个具有登录,注销功能的Android应用程序.登录表单包含用户名和密码以及登录按钮.我想在用户选中"记住我"复选框时保存用户名和密码.
我的project.java文件如下所示:
public class project extends Activity {
private static final int IO_BUFFER_SIZE = 4 * 1024;
/** Called when the activity is first created. */
public int user_id,current_user_id;
public String access_token,username,current_username;
public boolean user_logged_in=false;
public ProgressDialog progdialog;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progdialog = new ProgressDialog(this);
progdialog.setMessage("loading...");
initLogin();
}
public void initLogin(){
setContentView(R.layout.login);
Button button = (Button) findViewById(R.id.login_login);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
login();
}
});
}
public void login(){
try{
String login_username=(((EditText) findViewById(R.id.login_username)).getText()).toString(); …Run Code Online (Sandbox Code Playgroud) 我有存储字符串集首选项的问题.我有这些实用方法用于存储:
public static void putStringSet(SharedPreferences pref, Editor e, String key, Set<String> set)
{
if (Utils.isApiLevelGreaterThanGingerbread())
{
// e.remove(key); // I tried to remove it here
e.putStringSet(key, set);
}
else
{
// removes old occurences of key
for (String k : pref.getAll().keySet())
{
if (k.startsWith(key))
{
e.remove(k);
}
}
int i = 0;
for (String value : set)
{
e.putString(key + i++, value);
}
}
}
public static Set<String> getStringSet(SharedPreferences pref, String key, Set<String> defaultValue)
{
if (Utils.isApiLevelGreaterThanGingerbread())
{
return pref.getStringSet(key, …Run Code Online (Sandbox Code Playgroud) 在活动被杀之前(OnDestroy被叫时),我保存了一些int值SharedPreferences.
但我注意到的是,要保存的值需要大约一秒钟,但应用程序在销毁之前不会等待Activity.
Wait它可以在被杀之前做些什么吗?
这是我的例子:
@Override
public void onDestroy(){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("finalXPos", finalX);
editor.putInt("finalYPos", finalY);
editor.commit();
super.onDestroy();
removeView();
}
Run Code Online (Sandbox Code Playgroud)
====================== >>编辑<< ======================
我犯了一个错误,并说这是为了一个,Activity但事实并非如此.我正在调用onDestroy一个服务,不幸的是没有onPause办法覆盖那里......
android android-service android-studio android-sharedpreferences android-ondestroy
我是android的新手.我正在使用SessionHandler类,我在共享首选项中保存LoginActivity中的用户名.我想从一类广播接收器中的共享首选项访问此用户名
这是SessionHandler类的代码.
public SharedPreferences getLoginPreferences() {
// This sample app persists the registration ID in shared preferences,
// but
// how you store the regID in your app is up to you.
return context.getSharedPreferences(
LoginActivity.class.getSimpleName(), Context.MODE_PRIVATE);
}
public void storeLoginSession(String str_Name) {
final SharedPreferences prefs = getLoginPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", str_Name);
editor.commit();
}
Run Code Online (Sandbox Code Playgroud)
我想在startService()中访问此名称.
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
startService();
}
}
private void startService() {
Calendar c = …Run Code Online (Sandbox Code Playgroud) 我正在尝试将三个字符串永久存储为我的 Android 应用程序的用户首选项。这三个字符串是 url、用户名和密码。我不太了解 SharedPreferences,所以我尝试使用内部文件存储。我无法从文件中检索三个字符串,并且出现运行时错误。我知道我可能编码有误,但我对 Android 不够精通,无法理解数据存储。有人可以帮我吗?
偏好活动:
package com.amritayalur.mypowerschool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
FileOutputStream fos;
String url = "";
String FILENAME = "InternalStrings";
String str;
String username;
String password;
/** Called when the activity is first created. */
@Override …Run Code Online (Sandbox Code Playgroud) 我知道apply和commit之间的区别.在我的情况下,我想使用commit(),但Android建议我使用,apply()因为它在后台运行,并没有阻止主线程.
如果我使用apply这样的东西是否有用,或者是否可能在调用之前没有更新它?
editor.putBoolean("TEST", true)
editor.apply()
if (preferences.getBoolean("TEST")) {
//do something
}
Run Code Online (Sandbox Code Playgroud) android ×11
java ×4
preferences ×2
audio ×1
checkbox ×1
internal ×1
remember-me ×1
storage ×1
string ×1