1

2 つのアクティビティがあり、一方は意図的に他方にデータを送信します。

ユーザーが保存後に値を入力するための2つのeditTextがあり、editTextボックスに表示されます

savePreferences = getSharedPreferences("filename", Context.MODE_PRIVATE);
first = savePreferences.getString("first", "1st");
second = savePreferences.getString("second", "2nd");

editf1.setText(first);
editf2.setText(second);

アクティビティ 1 で

public static String filename = "myfile";
SharedPreferences savePreferences;
savePreferences = getSharedPreferences("filename", Context.MODE_PRIVATE);

SharedPreferences.Editor saveEditor = savePreferences.edit();            
saveEditor.putString("first", edit1.getText().toString());
saveEditor.putString("second", edit2.getText().toString());              
saveEditor.commit();

Intent myIntent = new Intent(this, Activity2.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

//put the retrieved data in extras      
Bundle extras = new Bundle();
extras.putString("firststr", first);
extras.putString("secondstr", second);
myIntent.putExtras(extras);

startActivity(myIntent);

アクティビティ 2 で

Intent intent = getIntent();
Bundle extras = intent.getExtras();         

if (extras != null) {
     firstval = extras.getString("firststr");
     secondval = extras.getString("secondstr");
}

アクティビティ1から渡されたデータを表示する2つのTextViewがあります

if (firstval == null || firstval == "")
     textView1.setText("empty");
else
     textView1.setText(firstval);

if (secondval == null || secondval == "")
     textView2.setText("empty");
else
     textView2.setText(secondval);

保存ボタンをクリックすると、値が共有設定に保存され、インテントが開始され、Activity2 に移動します。この段階で、Activity1 から保存および渡された値を TextViews に表示できます。

しかし、ページを更新すると、代わりに TextView が空で表示されます。

アプリケーションが起動すると、Activity2 が最初に起動し、TextView も空で表示されます。アプリを開いたとき、またはアプリを更新したときに、インテント エクストラの値が常にそこにあるようにするにはどうすればよいですか? Activity1 に移動して再度保存する代わりに。

4

1 に答える 1

0

Intent に保存する値を渡す必要はありません。SharedPreferences の使用方法は非推奨です。

prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

設定の適切な場所で文字列値を保存および取得するには、次を使用できます。

// Retrieve the saved values in Activity2
    private String getCurrentDefaultHomeApp(){
            return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());.getString("Key", "DefaultValue");
    }

// Put this in Activity1
    private void setCurrentDefaultHomeApp(String appId){
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());.edit();
            editor.putString("Key", "value");
            editor.commit();
    }
于 2013-09-28T15:17:00.047 に答える