我在理解SQLite数据库在 android中的工作原理时遇到了一些困难.我创建了一个 DatabaseHelper.java类,如下所示: import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "library.db"; public static final String TITLE = "title"; public static final String MUSICTITLE = "musictitle"; public static final String AUTHOR = "author"; public static final String ARTIST = "artist"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "CREATE TABLE music (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, artist TEXT);"); db.execSQL( "CREATE TABLE books (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT);"); db.execSQL( "CREATE TABLE movies (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { android.util.Log.v("Constants", "Upgrading database which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS books"); db.execSQL("DROP TABLE IF EXISTS music"); db.execSQL("DROP TABLE IF EXISTS movies"); onCreate(db); } }
据我所知,这确实有用,并已使用adb控制台进行检查.
我的问题是如何从不同的活动中查询应用程序中的这个数据库,例如我想在我的应用程序中查询数据库:SELECT title FROM books;这将返回书表中的标题,如何连接到数据库,运行此查询然后将所有结果存储到数组中?
– – – – – – – – – – – – – – – – – 编辑 – – – – – – – – ————————-
是的,所以在我要查询的部分中,我已经放置了这段代码:
if (category.equals("Books")){ img.setImageResource(R.drawable.book); ArrayList<String> list = new ArrayList<String>(); dh = new DatabaseHelper(this); SQLiteDatabase db = dh.getReadableDatabase(); Cursor cursor = db.query("books", new String[] { "title" }, null, null, null, null, "title desc"); if (cursor.moveToFirst()) { do { list.add(cursor.getString(1)); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } list.add("Test"); cont_array = (String[]) list.toArray(); db.close(); }
通过类别向下传递前一个活动.来自奥利维尔的回答.这段代码崩溃了应用程序,我不明白为什么.在此if语句之后使用变量cont_array来填充ListView.任何人都有任何想法我错了,LogCat中没有任何东西可以告诉我哪里失败了?
在您的活动内部执行以下操作:public class DBAct extends Activity { private DataHelper dh; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //init your activity here //e.g. setContentView(R.layout.main); dh = new DataHelper(this); SQLiteDatabase db = dh.getReadableDatabase(); Cursor cursor = db.query("books", new String[] { "title" }, null, null, null, null, "title desc"); if (cursor.moveToFirst()) { do { list.add(cursor.getString(0)); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } db.close(); } }