我在理解sqlite数据库在android中的工作原理时遇到了一些困难.我创建了一个DatabaseHelper.java类,如下所示:
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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。