chow_stephen
chow_stephen
2016-03-31 13:23

一个Activity创建数据库,另一个Activity中调用数据库并用TextView显示

  • android
  • 数据库
  • textview

第一个Activity(创建数据库):

Db db = new Db(this);
    SQLiteDatabase dbWrite = db.getReadableDatabase();

    ContentValues cv = new ContentValues();
    cv.put("name", "小张");
    cv.put("sex", "男");
    dbWrite.insert("user", null, cv);

    cv = new ContentValues();
    cv.put("name", "小李");
    cv.put("sex", "女");
    dbWrite.insert("user", null, cv);
    dbWrite.close();

第二个Activity(查看数据库内容):

public class TryAnotherAty extends AppCompatActivity {

private TextView tv = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_try_another_aty);

    tv = (TextView) findViewById(R.id.tv);
    tv.setMovementMethod(ScrollingMovementMethod.getInstance());

    SQLiteDatabase dbRead = openOrCreateDatabase("mytable", Context.MODE_PRIVATE,null);
    Cursor  c = dbRead.query("user", null, null, null, null, null, null);

    while(c.moveToNext()){
        tv.append(getString(c.getColumnIndex("name")));
        tv.append(getString(c.getColumnIndex("sex")));
        tv.append("\n");
    }
}

Db.class:

public class Db extends SQLiteOpenHelper {

//必须要有构造函数
public Db(Context context) {
    super(context, "db", null, 1);
}

public void onCreate(SQLiteDatabase db) {
db.execSQL("create table user( name TEXT,sex TEXT )");
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

PS:真机测试时跳到第二个Acitvity直接退出程序。

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

5条回答