<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>
public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK="create table Book(" +"id integer primary key autoincrement," + "author text," + "price real" + "pages integer" + "name text )"; public static final String CREATE_CATEGORY="create table Category(" + "id integer primary key autoincrement," + "category_name text," + "category_code integer)"; private Context mContext; public MyDatabaseHelper(Context context,String name,SQLiteDatabase.CursorFactory factory, int version){ super(context,name,factory,version); mContext=context; } @Override public void onCreate(SQLiteDatabase db){ db.execSQL(CREATE_CATEGORY); db.execSQL(CREATE_BOOK); Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_LONG).show(); } @Override public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){ } }
public class MainActivity extends Activity { private MyDatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper=new MyDatabaseHelper(this,"BookStore.db",null,1); Button createDatabase=(Button)findViewById(R.id.create_database); Button addData=(Button)findViewById(R.id.add_data); createDatabase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dbHelper.getWritableDatabase(); } }); addData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { 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(); } }); } }
一个数据都没有
解决方案