在共享首选项Android中保存用户ID

时间:2012-02-07 13:27:41

标签: java android unique-id

我刚问了一个关于此的问题,但我想以不同的方式去做。当用户编辑他/她的个人资料并点击保存按钮时,我希望能够使用UUID生成随机数。我希望这个ID保持不变,如果用户返回并再次编辑他们的个人资料(如果他们再次按'保存'我想保留他们第一次按'保存'时生成的ID)。我有以下代码用于保存其他数据,但我不知道如何包含一个检查,可以找出是否已生成一个ID。这是我的代码:

public void save(View view) {
    String firstnameText = firstname.getText().toString();
    String lastnameText = lastname.getText().toString();
    String phoneText = phone.getText().toString();
    String cityText = city.getText().toString();
    String zipText = zip.getText().toString();
    String uuid = UUID.randomUUID().toString(); //Generate random ID but I 
                                                 think this would generate a 
                                                 new ID each time the data is     
                                                 saved

    if (firstnameText != null)
        PreferenceConnector.writeString(this, PreferenceConnector.FIRSTNAME,
                firstnameText);
    if (lastnameText != null)
        PreferenceConnector.writeString(this, PreferenceConnector.LASTNAME,
                lastnameText);

    if (phoneText != null && !phoneText.equals(""))
        PreferenceConnector.writeLong(this, PreferenceConnector.PHONE,
                Long.parseLong(phoneText));

    if (cityText != null)
        PreferenceConnector.writeString(this, PreferenceConnector.CITY,
                cityText);

    if (zipText != null && !zipText.equals(""))
        PreferenceConnector.writeInteger(this, PreferenceConnector.ZIP,
                Integer.parseInt(zipText));

    if (uuid != null) //what next?

    startActivity(new Intent(PreferencesActivity.this, Main.class));                        
}

1 个答案:

答案 0 :(得分:2)

你可以设置一个初始设置为false的布尔型SharedPreference,然后设置为生成ID的第一个时间为true,然后在生成和ID之前检查这个布尔值,如果它是基本错误则只生成

//get idHasBeenGenerated from prefs with default false
if(!idHasBeenGenerated)
{
//generate ID
//change value of idHasBeenGenerated to true and save in shared prefs.
}

编辑:

SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean idHasBeenGenerated = prefs.getBoolean("idgenerated", false);

if(!idHasBeenGenerated){
    String uuid = UUID.randomUUID().toString();

//do your thing with PreferenceConnector
    Editor editor=prefs.edit();
    editor.putBoolean("idgenerated", true);
    editor.commit();
}else{          
    //Do nothing ID has already been generated
}