2015-10-25 33 views
0

在第一次活動我有3個按鈕冷杉按鈕去主題列表,第二個按鈕顯示上次看到的活動 Im使用此爲上次看到的活動: 在主題列表中的每個項目保存數量在共享偏好,當用戶點擊主題列表中的最後一次看到的號碼呼叫並顯示上次活動 此代碼運行良好,但是當我打開手機或應用程序未打開時,最後一次看到顯示沒有顯示爲什麼? 請幫我上次看到活動不保存在共享偏好

在主題列表中類

shared = getSharedPreferences("count", MODE_PRIVATE); 
    SharedPreferences.Editor editor = shared.edit(); 
public static int counter; 
@Override 
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 






    if (i == 0) { 
     Intent intent0 = new Intent(getApplicationContext(),Study.class); 
     startActivity(intent0); 
     counter=1; 
     SharedPreferences.Editor edit = shared.edit(); 
     edit.putInt("count", counter); 
     edit.commit(); 



    } 
    if (i == 1) { 
     counter=2; 
     SharedPreferences.Editor edit = shared.edit(); 
     edit.putInt("count", counter); 
     edit.commit(); 


        Intent intent1 = new Intent(getApplicationContext(),Mo.class); 
     startActivity(intent1); 


    } 

    if (i == 2) { 
     counter=3; 
     SharedPreferences.Editor edit = shared.edit(); 
     edit.putInt("count", counter); 
     edit.commit(); 




     Intent intent2 = new Intent(getApplicationContext(),Sa.class); 
     startActivity(intent2); 



    } 
的拳頭活動

包含最後一次露面按鈕:

case R.id.last_seen_btn: 

      if (SubjectActivity.counter==0){ 
       Toast.makeText(getApplicationContext(), " nothing", 
         Toast.LENGTH_LONG).show(); 

      } 
      if (SubjectActivity.counter==1){ 
       Intent intent = new Intent(getApplicationContext(),Study.class); 
       startActivity(intent); 

      } 
      if (SubjectActivity.counter==2){ 
       Intent intent = new Intent(getApplicationContext(),Mo.class); 
       startActivity(intent); 

      } 
      if (SubjectActivity.counter==3){ 
       Intent intent = new Intent(getApplicationContext(),Sa.class); 
       startActivity(intent); 

      } 

回答

0

您應始終使用「應用程序設置」,然後最好是訪問它們通過應用程序對象。 SharedPreferences上存在緩存,它在某些時候會創建一些問題。 也打開活動前的SharedPreferences隨時更新(如果我== 0)

public class MyApp extends Application { 
private SharedPreferences mMyPref; 

@Override 
public void onCreate() { 
    super.onCreate(); 
    mMyPref = getSharedPreferences("my_pref_name", MODE_PRIVATE); 
} 

public SharedPreferences getMySharedPreferences(){ 
    return mMyPref; 
} 
} 

在你要讀/寫只使用

((MyApp)getApplicationContext()).getMySharedPreferences() .... 

當然創建的代碼部分一局部變量,使您可以使用它。

+0

取悅更多的解釋 – chy

+0

是否有可能顯示在我的代碼 – chy

+0

公共類MyApp的擴展應用{ – chy