2016-09-19 78 views
0

Fragment類..我有這行代碼的傳遞數據從一個片段到另一個 - SharedPreferences

SharedPreferences pref = getActivity().getSharedPreferences("destination", MODE_PRIVATE); 
Editor editor = pref.edit(); 

在此以下代碼,字符串DEST已經有了一個值。

public void onPlaceSelected(Place place) { 
Log.i(LOG_TAG, "Place Selected: " + place.getName()); 
String dest = getString(R.string.place_data, place.getAddress()); 

edtDestination.setText(dest); 

editor.putString("destination", dest); 

但是當在其他活動上獲取。 DEST將返回null ... String destination = pref.getString("destination", "");

兩個類擴展片段

+1

edit.commit()或editor.apply()編輯共享偏好後。 –

+2

editor.commit()花費時間來在首選項中應用數據,所以只需使用editor.apply() –

+1

「這兩個活動都會擴展Fragment」 - 我相信你的意思是這兩個類。活動不能擴展片段 –

回答

0

要提交在SharedPreferences

editor.putString("destination", dest); editor.apply();

0

你的問題的標題說,你想從一個片段的數據傳遞到另一個變化。如果你想這樣做,使用SharedPreferences是沒有必要的。 SharedPreferences應該用於保存數據,而不是傳遞它們。

相關問題