Saving User ID in Shared Preferences Android

2019-09-05 23:59发布

I just asked a question about this but I want to go at it a different way. When a user edits his/her profile and hits the save button, I want to be able to generate a random number using UUID. I want this ID to stay the same if the user goes back and edits their profile a second time (if they press 'save' again I want to retain the ID that was generated the first time they pressed 'save'). I have the following code working to save other data, but I'm not sure how to include a check that can find out if an ID has already been generated. Here is my code:

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条回答
淡お忘
2楼-- · 2019-09-06 00:19

You can set a Boolean SharedPreference that is initialy set to false and then set to true the foirst time an ID is generated, then you check this boolean before generating and ID and only generate if it is false so basicly

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

Edit:

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
}
查看更多
登录 后发表回答