我第一次在android中测试SQLite数据库。 当我打开它时我的程序停止了,我无法检查它,我想知道我的代码或数据库连接是否有错误,
任何帮助将不胜感激:)
这是我的Main.java文件:
package de.blattsoft.SQLite;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT * FROM MyTable", null);
c.moveToFirst();
Log.d("Ali", c.getString(c.getColumnIndex("FirstName")));
db.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
注意:我之前已经多次提出这个问题了,我已经在下面的答案中写了完整的答案,说明如何在Android中实现数据库。
答案 0 :(得分:2)
首先,您需要创建一个数据库,然后在其中插入一些数据,然后尝试显示。
您正在做的是,如果数据库不在那里,则创建并选择列和显示。它显然会失败,你的应用程序崩溃。 做点什么
public void onCreate(SQLiteDatabase db) {
/*CREATE LOGIN TABLE*/
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT," + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
然后这样做,
public void addMessage(String id, String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, id); //
values.put(KEY_NAME, name);
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
然后你可以显示,
答案 1 :(得分:2)
您尚未创建数据库。从结构中插入或获取不存在的值将导致应用程序崩溃。这就像攀爬一座不存在的建筑物。
因此,首先创建数据库然后再做其他事情。
为了更好地理解,请按照Slidenerd的管视频教程进行操作。他们依次为初学者here解释了所有内容。
希望它会有所帮助。
答案 2 :(得分:2)
很多次,当我是Android菜鸟时,我已经问过这个问题了! :d
现在这是我建议你使用辅助类使用android sqlite数据库的方式。
作为概述,我们需要创建两个类
DatabaseHelper
类 和DataSource
上课。
我们需要创建的内容:
DatabaseHelper
类必须从SQLiteOpenHelper
包扩展android.database.sqlite
这是一个内置的Android类,其目的是管理数据库创建和版本管理。 DataSource
类使用我们的帮助程序类来实现应用程序所需的方法。 例如,我们将创建一个数据库,其中有一个名为users
的表,该表有两列:id
和name
;
id
将用作主键。
所以,让我们创建一个助手类:
DatabaseHelper.java:
package com.mpandg.android.dbtest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
// this tag is used for logging purposes.
public static final String TAG = "database";
// database version.
public static final int DATABASE_VERSION = 1;
// database file name.
public static final String DATABASE_NAME = "database.db";
// table details:
public static final String TABLE_USERS = "users";
public static final String USERS_COLUMN_ID = "id";
public static final String USERS_COLUMN_NAME = "name";
// query of creating users table.
public static final String CREATE_USERS_TABLE =
"CREATE TABLE " + TABLE_USERS + " (" +
USERS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
USERS_COLUMN_NAME + " TEXT" + ")";
// query string of deleting users table.
public static final String DELETE_TABLES =
"DROP TABLE IF EXISTS " + TABLE_USERS + ";";
// constructor method which takes the context and passes it
// to appropriate super method with other database details
// which creates the database.
public DatabaseHelper(Context context) {
// creates the database using given information.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// this line executes the query we made earlier
// to create the users table.
db.execSQL(CREATE_USERS_TABLE);
// log the table creation for debugging.
Log.i(TAG, TABLE_USERS + " has been created.");
}
// whenever you give a new update for your application,
// if you change the version of the database, this method
// will be called, you can do your own complicated operations
// on your tables if you need, but right now, I just delete
// the old table and I make an explicit call to onCreate
// method to create the tables again.
// but never forget that you should never make explicit
// calls to onCreate method, but this is an exception here.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// execute the delete query we made earlier.
db.execSQL(DELETE_TABLES);
// explicit call to onCreate. (read the comment above method)
onCreate(db);
}
}
如您所见,我们实际上创建了SQLiteOpenHelper
的子类,并且我们已经实现了onCreate(SQLiteDatabase)
和onUpgrade(SQLiteDatabase, int, int)
方法,并且我们创建的帮助程序类负责打开数据库它存在,创建它,如果它不存在,并在必要时升级它。
现在是时候使用我们创建的辅助类并编写我们的方法来使用DataSource
类中的数据库。
我们将创建一个数据库对象,我们将使用helper类中的方法对其进行实例化,并创建插入,选择和删除的方法。
所以,让我们创建DataSource.java
:
package com.mpandg.android.dbtest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DataSource {
// create an instance of SQLiteOpenHelper
// but we're going to instantiate it using
// the helper class we created earlier.
SQLiteOpenHelper dbHelper;
// the main database object which will be
// instantiated using the helper class methods.
SQLiteDatabase dataBase;
private final String TAG = "dataSource";
// an string array holding our table's column names
// which is going to be used by database methods.
public static final String[] usersTableColumns = {
DatabaseHelper.USERS_COLUMN_ID,
DatabaseHelper.USERS_COLUMN_NAME
};
// constructor which receives the activity context.
public DataSource(Context context){
// instantiate the dbHelper object using our DatabaseHelper class.
dbHelper = new DatabaseHelper(context);
}
public void open(){
// opening the database or
// creating the table structures for the first time.
// the helper class knows when to open or create the database.
dataBase = dbHelper.getWritableDatabase();
// log the event for debugging purposes.
Log.i(TAG, "database opened");
}
public boolean isOpen () {
// check if the database is already open.
return dataBase.isOpen();
}
public void close(){
// close the database.
dataBase.close();
// log the event for debugging purposes.
Log.i(TAG, "database closed");
}
// insert a name record into database .
public void insertName (String name) {
// ContentValues implements a map interface.
ContentValues values = new ContentValues();
// put the data you want to insert into database.
values.put(DatabaseHelper.USERS_COLUMN_NAME, name);
// passing the string array which we created earlier
// and the contentValues which includes the values
// into the insert method, inserts the values corresponding
// to column names and returns the id of the inserted row.
long insertId = dataBase.insert(DatabaseHelper.TABLE_USERS , null, values);
// log the insert id for debugging purposes.
Log.i(TAG, "added name id:" + insertId);
}
// returns a list of string
// containing the names saved in the database.
public List<String> getNames (){
List<String> names;
// creating the cursor to retrieve data.
// cursor will contain the data when the
// query is executed.
Cursor cursor = dataBase.query(DatabaseHelper.TABLE_USERS, usersTableColumns,
null, null, null, null, null);
// log the number of returned rows for debug.
Log.i(TAG, "returned: " + cursor.getCount() + " name rows .");
// check if the cursor is not null.
if(cursor.getCount()>0){
// instantiate the list.
names = new ArrayList<>();
// cursor starts from -1 index, so we should call
// moveToNext method to iterate over the data it contains.
while (cursor.moveToNext()) {
// read the string in the cursor row using the index which is the column name.
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.USERS_COLUMN_NAME));
// log the retrieved name.
Log.i(TAG, "name retrieved:" + name);
// now add the retrieved name into the list.
names.add(name);
}
// now we have the names in our string list
return names;
} else {
// if the cursor was empty, it means that
// there was no name found in the table,
// so return null.
return null;
}
}
// returns a name corresponding to given id.
public String findNameById (long id){
String name;
// the where clause which is our condition.
String whereClause = DatabaseHelper.USERS_COLUMN_ID + " = ?";
// the arguments passed to
// the where clause. (here is only one argument)
String[] whereArgs = {id+""};
// creating the cursor to retrieve data.
// cursor will contain the data when the
// query is executed.
Cursor cursor = dataBase.query(DatabaseHelper.TABLE_USERS, usersTableColumns,
whereClause, whereArgs, null, null, null);
// log the number of returned rows for debug.
// (logically it should return one row here)
Log.i(TAG, "returned: " + cursor.getCount() + " name rows .");
// check if the cursor is not null.
if(cursor.getCount()>0){
// cursor starts from -1 index, so we should call
// moveToNext method to iterate over the data it contains.
cursor.moveToNext();
// read the string in the cursor row using the index which is the column name.
name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.USERS_COLUMN_NAME));
// log the retrieved name.
Log.i(TAG, "name retrieved:" + name);
return name;
} else {
// if the cursor was empty, it means that
// there was no name found with given id,
// so return null.
return null;
}
}
// delete a name from the table.
public void deleteName (String name) {
// where statement of our delete method.
String whereClause = DatabaseHelper.USERS_COLUMN_NAME + "=" + "?";
// the arguments passed to
// the where clause. (here is only one argument)
String[] whereArgs = {name};
// execute the delete query with delete method.
int deleteId = dataBase.delete(DatabaseHelper.TABLE_USERS , whereClause, whereArgs);
// log the id of the deleted row.
Log.i(TAG, "deleted name id:" + deleteId);
}
}
现在我们已经编写了必要的类来以适当的方式创建和使用我们的数据库,现在是时候使用我们在DataSource
类中编写的方法了。
您需要做的就是在您的活动中创建DataSource
类的对象并使用其中的方法。
当你打算使用数据库时,你应该打开它,你可以通过我们在open()
类中编写的DataSource
方法来完成它,完成后你必须关闭它以避免它泄漏;您可以使用'DataSource`类中的close()
方法关闭它。
例如,您有一些用户,并且您希望将它们添加到数据库中:
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// insert the names.
dataSource.insertName("Amy");
dataSource.insertName("Johnny");
dataSource.insertName("Abbey");
dataSource.insertName("Miley");
// close the database.
dataSource.close();
或者您想要记录数据库中的所有用户:
//TAG for debug logs.
String TAG = "db log";
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// get the names.
List<String> names = dataSource.getNames();
// log all the names in the list.
for (String name: names) {
Log.i(TAG, "retrieved name:" + name);
}
// close the database.
dataSource.close();
或者您想通过其ID找到名称:
//TAG for debug logs.
String TAG = "db log";
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// find the name by id.
String name = dataSource.findNameById(1);
// log the retrieved name wit id:1.
Log.i(TAG, "retrieved name:" + name);
// close the database.
dataSource.close();
最后,如果你想删除一个名字:
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// delete the given name
dataSource.deleteName("Amy");
// close the database.
dataSource.close();
就是这样。 这是在Android中创建数据库的基本结构,如您所见,您可以通过将自己的代码添加到帮助程序类以及您自己的方法来轻松添加其他表和列,以便在DataSource类中使用它们。
答案 3 :(得分:1)
试试这个
package ir.itstuff.SQLite;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
(EditText) fName = (EditText)findViewById(R.id.editText1);
(EditText) sName = (EditText)findViewById(R.id.editText2);
(Button) save = (Button)findViewById(R.id.button1);
SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS MyTable(id INTEGER PRIMARY KEY AUTOINCREMENT, FirstName varchar,SecondName varchar);")
//Inserting data from inputs
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String first_name = fName.getText().toString();
String second_name = sName.getText().toString();
String insert_data="INSERT INTO MyTable (FirstName,SecondName) VALUES " + "('" + first_name + "'," + "'" + second_name + "'" + ")";
shoppingListDB.execSQL(insert_data);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
Cursor cr=shoppingListDB.rawQuery("SELECT * FROM MyTable;", null);
if (cr.moveToFirst()){
do{
String name = cr.getString(cr.getColumnIndex("FirstName"));
}
while (cr.moveToNext());
Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show;
}
cr.close();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}