2015-04-05 47 views
0

我想創建一些需要在第一次獲取信息並保存它。該應用程序從MainActivity開始,如果它沒有所需的信息,應用程序會將您發送到MotoActivity。一旦應用程序有了這些信息,你就不需要再去MotoActivity了。我知道我錯了,但我不知道該怎麼做。SharedPreferences登錄

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sp.edit(); 

    editor.putInt("valid", 0); 
    editor.commit(); 
    int n = sp.getInt("valid", -1); 
    if(n == 0){ 
     editor.putInt("valid", 1); 
     editor.commit(); 
     startActivity(new Intent(MainActivity.this, MotoActivity.class)); 
     MainActivity.this.finish(); 
    } 

回答

0

首先檢查的第一次,如果「userLoggedBefore」是從SharedPreferences真的還是假的,如果用戶曾使用過的應用程序,並已進入我們將認證保存爲true,如果他沒有,我們將默認值設置爲false。

 SharedPreferences sharedPref = getSharedPreferences("Save", 0); 
     boolean authenticated = sharedPref.getBoolean("userLoggedBefore", false); 

再檢查 -

if (authenticated){ 
//show your MainActivity 
} else { 
// show your MotoActivity 
} 
在MotoActivity

//如果證書匹配,

if(credentialMatches) 
          SharedPreferences sharedPref = getSharedPreferences(
            "Save", 0); 
          SharedPreferences.Editor prefEditor = sharedPref 
            .edit(); 
          prefEditor.putBoolean("userLoggedBefore", true); 
          prefEditor.commit(); 
else{ // if credentials doesn't match 
          SharedPreferences sharedPref = getSharedPreferences("Save", 0); 
          SharedPreferences.Editor prefEditor = sharedPref 
            .edit(); 
          prefEditor.putBoolean("userLoggedBefore", false); 
          prefEditor.commit(); 
} 
+0

謝謝!有效! – 2015-04-05 13:44:17

+0

如果有幫助,您可以將我的答案設置爲正確答案;) – 2015-04-05 13:49:12

0

試試這個:

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sp.edit(); 
    // app already has the needed info. 
    if(sp.getInt("valid", -1) == 1){ 
     // do something 
    } 
    // app needs info. first, when you have got the info. in MotoActivity then set preferences key 'valid' to 1 
    else{ 
     startActivity(new Intent(MainActivity.this, MotoActivity.class)); 
     finish(); 
    }