Android:如何存储生成的ID并在下一个应用程序运行时调用它?

时间:2014-08-20 12:13:21

标签: android

每次我的应用程序启动时,我的程序都会生成一个ID。因为每次它生成一个不同的ID,我想在退出程序之前将ID保存在某处,这样我可以在程序运行后再次使用它。

样品编号:125469

注意:我宁愿不将其保存在文件中,也不保存在其他文件中。

5 个答案:

答案 0 :(得分:1)

更好的解决方案是使用 GreenDAO 这里有一些例子

https://github.com/greenrobot/greenDAO

https://github.com/octa-george/Android-GreenDao-Sample

GreenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases. Being highly optimized for Android, greenDAO offers great performance and consumes minimal memory.

你只需要greendao jar

public class MyDaoGenerator {

      public static void main(String args[]) throws Exception {
      Schema schema = new Schema(1, "ro.octa.greendaosample.dao");
      createSchema(schema);
      new DaoGenerator().generateAll(schema, "C:/GreenDaoSchema");
}

private static void createSchema(Schema schema) {

     Entity user = schema.addEntity("DBUser");
     user.addIdProperty().primaryKey().autoincrement();
     user.addStringProperty("email").notNull().unique();
     user.addStringProperty("password").notNull();

}

在几行代码之后,您可以为自动增量ID,电子邮件和密码生成模型。

答案 1 :(得分:0)

您可以使用SharedPreferences,也可以使用SQLite数据库进行存储。

答案 2 :(得分:0)

你可以这样做:

private SharedPreferences prefs;

...
...
private void initializeFromPreference() {
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
myId = prefs.getInt("myId", myId );
}
...
...
public void onDestroy() {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("myId", myId );
editor.commit();
super.onDestroy();
}

我不会将数据库用于单个值,Sharedpreferences是一种很好的方法

答案 3 :(得分:0)

您可以使用SharedPreferences存储您的ID

 SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);

       Editor edit=prefs.edit();

       //to store value
       edit.putInt("Your Id Name", Id Value).commit();

       //to get value

       int id=prefs.getInt("Your Id Name", 0);

答案 4 :(得分:0)

这是一个简单的方法,我能想到:)

    public static SharedPreferences sharedpreferences;
    sharedpreferences = getSharedPreferences("MyIds", Context.MODE_PRIVATE);

    if (sharedpreferences.contains("id"))
    {
       String id = sharedpreferences.getString("id", "");
       // *Use existing id and enjoy* ;)
    }
    else{

            // *Generate New ID (yourID)*
            Editor editor = sharedpreferences.edit();
            editor.putString("id", yourID);
            editor.commit();
    }