[英]How to save the intent Extras in Shared prefrences
這是我的代碼,要求用戶提供用戶名:
private void request_user_name() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
final String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
else
{
dialogInterface.cancel();
request_user_name();
}
}
});
builder.show();
}
這就是我將他的用戶名傳遞給下一個活動的方式:
intent.putExtra("room_name",((TextView)view).getText().toString() );
intent.putExtra("user_name",name);
intent.putExtra("default_name","anyonymous");
startActivity(intent);
這是我在下一個活動中收到額外Intent的方式:
if (getIntent().getExtras() != null
&& getIntent().getExtras().get("user_name")!=null) {
user_name = getIntent().getExtras().get("user_name").toString();
}else{
user_name = getIntent().getExtras().get("default_name").toString();
}
我的問題是,當用戶不輸入他的名字並且返回null時,它將返回anyonymous
但是當用戶輸入他的名字時,它將用戶名傳遞給下一個活動。 但是,當我重新啟動應用程序時,它anyonymous
傳遞給下一個活動,而不是已經輸入用戶名的用戶
因此,我需要有關如何將輸入的用戶名保存在共享首選項中並在以后的應用程序啟動中使用該建議的建議,除非未輸入新名稱而不是anyonymous
提前致謝。
如果您已經在使用SharedPreferences
來存儲user_name,則無需通過Intent
傳遞user_name
。 SharedPreferences
是全局的,可以在整個應用程序中進行訪問。 做就是了:
sharedpreferences.getString("username","anonymous")
在您的目標活動中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.