Android数据库制作错误

时间:2015-08-10 22:52:57

标签: java android sqlite

我创建了一个简单的Android应用程序,询问用户的详细信息,如姓名,血型和联系号码,并将其存储在数据库中。我使用以下代码删除了数据库:

package com.example.androidsimpledbapp1;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;

public class MyDBHandler extends SQLiteOpenHelper {

/*
 * Class for Working with DB 
 */

//Update each time DB structure changes e.g. adding new property
private static final int DATABASE_VERSION =1;
//DB Name
private static final String DATABASE_NAME = "deets.db";
//Table name
public static final String  TABLE_PRODUCTS = "products";
//DB Columns 
public static final String  COLUMN_ID = "_Id";
public static final String  COLUMN_PERSONNAME  = "firstName";
public static final String  COLUMN_PERSONBLOOD  = "bloodType";
public static final String  COLUMN_PERSONCONTACT  = "contactName";
public static final String  COLUMN_PERSONNUMBER  = "phoneNumber";
public static final String  COLUMN_PERSONRELATION = "relationship";

//Constructor
/*
 * Passing information to super class in SQL
 * Context is background information 
 * name of db 
 * Database version
 */
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

/*
 * What to do first time when you create DB
 * Creates the table the very first time
 * (non-Javadoc)
 * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
 * Remember to use Commas as shown below
 */
@Override
public void onCreate(SQLiteDatabase db){
    String query = "CREATE TABLE "+ TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
            COLUMN_PERSONNAME + " TEXT, "+
            COLUMN_PERSONBLOOD + " TEXT, "+
            COLUMN_PERSONCONTACT + " TEXT, "+
            COLUMN_PERSONNUMBER + " TEXT, " +
            COLUMN_PERSONRELATION + " TEXT " +
            ");";
    //Execute the query
    db.execSQL(query);
}

/*
 * If ever upgrading DB call this method
 * (non-Javadoc)
 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
 */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
    //Delete the current table
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
    //create new table 
    onCreate(db);
}

//Add new row to the database
public void addProduct(Details details){
    //Built in class - set values for different columns 
    //Makes inserting rows quick and easy
    ContentValues values = new ContentValues();
    values.put(COLUMN_PERSONNAME, details.get_firstName());
    values.put(COLUMN_PERSONBLOOD, details.get_bloodType());
    values.put(COLUMN_PERSONCONTACT, details.get_contactName());
    values.put(COLUMN_PERSONNUMBER, details.get_phoneNumber());
    values.put(COLUMN_PERSONRELATION, details.get_relationship());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_PRODUCTS, null, values);
    db.close();
}

/*Table was deleted*/
public void deleteProducts(){
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DROP TABLE "+TABLE_PRODUCTS);
}

//Take DB and Convert to String 
public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    //Every Column and row
    String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

    //Cursor points to a location in your results
    //First row point here, second row point here

    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();

    while(!c.isAfterLast()){
        //Extracts first name and adds to string
        if(c.getString(c.getColumnIndex("firstName"))!=null){
            dbString += c.getString(c.getColumnIndex("firstName"));
            c.moveToNext();
            /*
             * Displaying all other columns 
             */
        }
    }
    db.close();
    return dbString;
}
}

然而,当我现在尝试创建数据库时,我收到一个错误。

数据库类

package com.example.androidsimpledbapp1;

public class Details {

//primary key
private int _id;
//Properties 
private String _firstName;
private String _bloodType;
private String _contactName;
private String _phoneNumber;
private String _relationship;

//Dont Have to Enter Everything each time
public Details(){

}

public Details(String firstName){
    this.set_firstName(firstName);
}

//Passing in details 
//Setting values from the user 
public Details(String firstName, String bloodType,
        String contactName, String phoneNumber,
        String relationship){
    this.set_firstName(firstName);
    this.set_bloodType(bloodType);
    this.set_contactName(contactName);
    this.set_phoneNumber(phoneNumber);
    this.set_relationship(relationship);

}

//Retrieve the data 
public int get_id() {
    return _id;
}

//Setter allows to give property
public void set_id(int _id) {
    this._id = _id;
}

public String get_firstName() {
    return _firstName;
}

public void set_firstName(String _firstName) {
    this._firstName = _firstName;
}

public String get_bloodType() {
    return _bloodType;
}

public void set_bloodType(String _bloodType) {
    this._bloodType = _bloodType;
}

public String get_contactName() {
    return _contactName;
}

public void set_contactName(String _contactName) {
    this._contactName = _contactName;
}

public String get_phoneNumber() {
    return _phoneNumber;
}

public void set_phoneNumber(String _phoneNumber) {
    this._phoneNumber = _phoneNumber;
}

public String get_relationship() {
    return _relationship;
}

public void set_relationship(String _relationship) {
    this._relationship = _relationship;
}

   }

详细信息类

package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


public class EditScreen extends Activity {
EditText firstNameInput;
EditText bloodTypeInput;
EditText contacNameInput;
EditText phoneNumberInput;
EditText relationshipInput;

TextView displayName;
MyDBHandler dbHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_screen);
    //Setting EditTexts 
    firstNameInput = (EditText) findViewById(R.id.inputname);
    bloodTypeInput = (EditText) findViewById(R.id.inputblood);
    contacNameInput = (EditText) findViewById(R.id.inputcontact);
    phoneNumberInput = (EditText) findViewById(R.id.inputnum);
    relationshipInput = (EditText) findViewById(R.id.inputraltion);
    displayName = (TextView) findViewById(R.id.fullname);
    //Setting DbHandler object 
    dbHandler = new MyDBHandler(this, null, null, 1);
}

public void saveMe(View v){
    /*
     * Making a new object 
     * Object takes 5 parameters 
     */
    Details detail = new Details(firstNameInput.getText().toString(),
            bloodTypeInput.getText().toString(),
            contacNameInput.getText().toString(),
            phoneNumberInput.getText().toString(),
            relationshipInput.getText().toString());
    dbHandler.addProduct(detail);

    /*Sending Text To Main Activity*/
    String dbString = dbHandler.databaseToString();
    Intent myIntent = new Intent(v.getContext(),MainActivity.class);
    myIntent.putExtra("mytext",dbString);
    startActivity(myIntent);
    /*End of Sending to Main Activity*/
}

public void clearBtnPressed(View v){
    dbHandler.deleteProducts();
}
}

编辑屏幕 - 用户输入数据并点击调用saveMe方法的保存按钮

08-10 23:27:39.968: E/AndroidRuntime(356): FATAL EXCEPTION: main
08-10 23:27:39.968: E/AndroidRuntime(356): java.lang.IllegalStateException: Could not execute method of the activity
08-10 23:27:39.968: E/AndroidRuntime(356): at android.view.View$1.onClick(View.java:2144)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.view.View.performClick(View.java:2485)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.view.View$PerformClick.run(View.java:9080)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.os.Handler.handleCallback(Handler.java:587)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.os.Handler.dispatchMessage(Handler.java:92)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.os.Looper.loop(Looper.java:130)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-10 23:27:39.968: E/AndroidRuntime(356): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 23:27:39.968: E/AndroidRuntime(356): at java.lang.reflect.Method.invoke(Method.java:507)
08-10 23:27:39.968: E/AndroidRuntime(356): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-10 23:27:39.968: E/AndroidRuntime(356): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-10 23:27:39.968: E/AndroidRuntime(356): at dalvik.system.NativeStart.main(Native Method)
08-10 23:27:39.968: E/AndroidRuntime(356): Caused by: java.lang.reflect.InvocationTargetException
08-10 23:27:39.968: E/AndroidRuntime(356): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 23:27:39.968: E/AndroidRuntime(356): at java.lang.reflect.Method.invoke(Method.java:507)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.view.View$1.onClick(View.java:2139)
08-10 23:27:39.968: E/AndroidRuntime(356): ... 11 more
08-10 23:27:39.968: E/AndroidRuntime(356): Caused by: android.database.sqlite.SQLiteException: no such table: products: , while compiling: SELECT * FROM products WHERE 1
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:49)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1356)
08-10 23:27:39.968: E/AndroidRuntime(356): at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1324)
08-10 23:27:39.968: E/AndroidRuntime(356): at com.example.androidsimpledbapp1.MyDBHandler.databaseToString(MyDBHandler.java:107)
08-10 23:27:39.968: E/AndroidRuntime(356): at com.example.androidsimpledbapp1.EditScreen.saveMe(EditScreen.java:60)
08-10 23:27:39.968: E/AndroidRuntime(356): ... 14 more

Log Cat错误

{{1}}

1 个答案:

答案 0 :(得分:0)

正如你所说,你放弃了桌子,但从未再创造过它。由于数据库存在,除非您删除数据库文件,否则不会再次为您调用onCreate()。如果您不想这样做,只需在删除表后自己调用onCreate(),或在删除表后再次执行CREATE TABLE语句。

如果您只想清空表格中的数据,可以改为:

db.delete(TABLE, null, null);

如果你实际上 想删除数据库文件,你可以使用

SQLiteDatabase.deleteDatabase(filename);