2017-07-14 44 views
-2

我需要生成隨機int,以便在第一次運行我的應用程序時提供設備ID,然後將其保存到SharedPreffs,在TextView上顯示id以及何時再次打開show saved id來自TextView上的SharedPreffs。生成隨機int並將其保存到SharedPreferences

public class MainActivity extends AppCompatActivity { 

    public static final String MyPREFERENCES = "MyPrefs"; 
    public static final String KEY_DEVICE = "id"; 
    SharedPreferences sharedpreferences; 
    String id; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     deviceid = (TextView) findViewById(R.id.deviceid); 
     sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 

     if (!sharedpreferences.contains(id)) { 
      SharedPreferences.Editor editor = sharedpreferences.edit(); 
      id = String.valueOf(new Random().nextInt(900000) + 100000); 
      editor.putString(KEY_DEVICE, id); 
      editor.commit(); 
      deviceid.setText(id); 
     } 

     deviceid.setText(id); 
    } 
} 

上面的代碼生成隨機INT,並顯示在TexView,但我每次隱藏或關閉應用程序時,設備ID發生變化 你能解釋我什麼,我需要做的才達到我的目標。

+0

'contains'第一個參數是關鍵,而不是價值。你的鑰匙是'KEY_DEVICE',你爲什麼用'id'來檢查? –

+0

https://stackoverflow.com/questions/7496840/get-android-shared-preferences-value-in-activity-normal-class請轉到鏈接,瞭解如何獲得sharedpreferences的價值.. – wonderPub

回答

0

試試這個

String MyPREFERENCES = "MyPrefs"; 
     String KEY_DEVICE = "device_id"; 
     SharedPreferences sharedpreferences; 
     SharedPreferences.Editor editor; 

     sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 
     if (sharedpreferences.contains(KEY_DEVICE)) { 
      id = sharedpreferences.getString(KEY_DEVICE, "0"); 
      deviceid.setText(id); 
     } else { 
      id = String.valueOf(new Random().nextInt(900000) + 100000); 
      editor = sharedpreferences.edit(); 
      editor.putString(KEY_DEVICE, id); 
      editor.apply(); 
      deviceid.setText(id); 
     } 
+0

它的工作原理就像一個魅力! 非常感謝。 –

2

應該有"id"KEY_DEVICE

更換

!sharedpreferences.contains(id) 

!sharedpreferences.contains(KEY_DEVICE) 

而且

deviceid.setText(id); 

將顯示null在這種情況下

所以你的setText

之前添加
id = sharedpreferences.getString(KEY_DEVICE,"0"); 
0

這是因爲你只是檢查是否有那麼沒有共享優先值選擇一個隨機數,並把它添加到設備,但是你是不是在創建方法中獲得任何價值,即您沒有獲得您之前存儲的任何共享偏好值。只需獲取存儲的值,然後檢查值是否存在,如果存在,則在textview中設置,否則調用條件檢查。希望它幫助

0

在從sharedPreferences中獲取值之前檢查null。 如果它爲空:那麼保存ID
其他:只提取較舊的一個。

如果此檢查:如果(!sharedpreferences.contains(id))是必需的,則將其保留在空檢查下嵌套。