插入数据库后显示主键

时间:2013-10-13 07:45:06

标签: android sqlite

我正在开发一个Android应用程序,我想在textview中显示主键,以便每次我编辑一个文本字段,我将使用主键更新。任何人都可以帮我这个吗?下面是在sqlite中插入数据。我的问题是如何获得主键......

public class UsedataActivity extends Activity {
    DatabaseHandler db = new DatabaseHandler(this);
    ImageButton evsave;
    EditText evname;
    EditText evtime;
    EditText evdate;
    EditText evcode;
    TextView evadmin;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_onetoone);

        evsave = (ImageButton)findViewById(R.id.event_save);
        evname = (EditText)findViewById(R.id.eventname);
        evtime = (EditText)findViewById(R.id.time1);
        evdate = (EditText)findViewById(R.id.eventdate);
        evcode = (EditText)findViewById(R.id.eventcode);
        evadmin = (TextView)findViewById(R.id.adminname_1to1);

        evsave.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Events addev =
                    new Events(evname.getText().toString(),evcode.getText().toString(),evdate.getText().toString(),Integer.parseInt(evtime.getText().toString()),evadmin.getText().toString());

                db.addEvents(addev);
                Toast.makeText(getApplicationContext(), "Event:  "+ evname.getText()+" successfully save",
                               Toast.LENGTH_SHORT).show();
            }
        });
    }

数据库处理程序类:

public void addEvents(Events event) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_EV_NAME, event.get_name());
    values.put(KEY_EV_PASS, event.get_pass());
    values.put(KEY_EV_DATE, event.get_date());
    values.put(KEY_EV_TIME, event.get_time());
    values.put(KEY_EV_ADMIN, event.get_admin());
    // Inserting Row
    db.insert(TABLE_EVENTS, null, values);
    db.close();
}

1 个答案:

答案 0 :(得分:1)

docs for the SQLiteDatabase可以看出,db.insert将返回新创建的对象的id。只需让addEvents返回它(而不是“无效”。

PS:请在问题的编辑中粘贴代码,而不是在评论中。在评论中他们真的很糟糕!

修改

public long addEvents(Events event) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_EV_NAME, event.get_name());
    values.put(KEY_EV_PASS, event.get_pass());
    values.put(KEY_EV_DATE, event.get_date());
    values.put(KEY_EV_TIME, event.get_time());
    values.put(KEY_EV_ADMIN, event.get_admin());
    // Inserting Row
    long id = db.insert(TABLE_EVENTS, null, values);
    db.close();
    return id;
}

然后:

long id = db.addEvents(addev);
Toast.makeText(getApplicationContext(),
               "Event with id:  "+ id + " successfully saved",
               Toast.LENGTH_SHORT).show();