|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
activity_main.xml修改为:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <Button
- android:id="@+id/create_database"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="create database"/>
- <Button
- android:id="@+id/add_data"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Add data"/>
- </LinearLayout>
复制代码
MainActivy.java修改为:
- package com.example.xinwei.databasetest;
- import android.content.ContentValues;
- import android.database.sqlite.SQLiteDatabase;
- import android.support.v7.app.AlertDialog;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- public class MainActivity extends AppCompatActivity {
- private MyDatabaseHelper dbHelper;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);
- Button createDatabase = (Button)findViewById(R.id.create_database);
- createDatabase.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- dbHelper.getWritableDatabase();
- }
- });
- addData();
- }
- private void addData() {
- Button addData = (Button)findViewById(R.id.add_data);
- addData.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- SQLiteDatabase db = dbHelper.getWritableDatabase();
- ContentValues values=new ContentValues();
- values.put("name","The Da Vinci Code");
- values.put("author","Dan Brown");
- values.put("pages",454);
- values.put("price",16.96);
- db.insert("book",null,values);
- values.clear();
- values.put("name","The Lost Temple");
- values.put("author","Dan Brown");
- values.put("pages",510);
- values.put("price",19.95);
- db.insert("book",null,values);
- values.clear();
- }
- });
- }
- }
复制代码
addData()这个函数里就是添加数据的方法。 |
|