2015-10-25 34 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