【#第一文档网# 导语】以下是®第一文档网的小编为您整理的《安卓手机数据库连接代码》,欢迎阅读!
package com.fenghuo.firstproject; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class DataBaseActivity extends Activity { public static SQLiteDatabase db = null; private ListView listView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_data_base); SQLiteOpenHelper helper = new SQLiteOpenHelper(this,"mydb",null,1) { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table users"); onCreate(db); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE 'users' ( '_id' INTEGER NOT NULL, 'username' TEXT NOT NULL, 'password' TEXT NOT NULL, 'email' TEXT NOT NULL, PRIMARY KEY ('_id') ) "); db.execSQL("insert into users values(1,'admin','admin','admin@admin.com')"); db.execSQL("insert into users values(2,'admin1','admin','admin1@gmail.com')"); db.execSQL("insert into users values(3,'admin2','admin','admin2@gmail.com')"); db.execSQL("insert into users values(4,'admin3','admin','admin3@gmail.com')"); } }; } } db = helper.getWritableDatabase(); Cursor cursor = db.rawQuery("select * from users",new String[]{}; CursorAdapter ca = new SimpleCursorAdapter( this, R.layout.listviewitem, cursor, new String[] { "username", "email" }, new int[] {R.id.newsTitle, R.id.newsMessage }; listView = (ListView) findViewById(R.id.listview); listView.setAdapter(ca); @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.data_base, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } 本文来源:https://www.dywdw.cn/022bf17e915f804d2a16c145.html