1

我正在开发一个 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();
}
4

1 回答 1

1

从SQLiteDatabase的文档中可以看出,db.insert它将返回新创建对象的 id。只需addEvents返回它(而不是'void)。

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();
于 2013-10-13T08:20:45.830 回答