尝试在Android中创建数据库并添加数据

时间:2022-04-14 07:10:36

I'm starting to learn Android programming and developing.

我开始学习Android编程和开发。

I'm trying to create a very simple SQLite contacts database (basically, storing names, numbers and an ID).

我正在尝试创建一个非常简单的SQLite联系人数据库(基本上,存储名称,数字和ID)。

In my application, there's a "Add contact" button; it's supposed to add a specific contact.

在我的应用程序中,有一个“添加联系人”按钮;它应该添加一个特定的联系人。

Here's the code of the contract class:

这是合同类的代码:

package com.example.marcos.myapplication;

import android.provider.BaseColumns;

/**
* Created by marcos on 22/09/15.
*/
public final class Contract {
public Contract(){}

public static abstract class Entry implements BaseColumns{
    public static final String TABLE_NAME = "contacts";

    public static final String NAME = "name";
    public static final String NUMBER = "number";
    public static final String ID = "id";
}
}

The code of the SQL helper:

SQL助手的代码:

package com.example.marcos.myapplication;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
* Created by marcos on 22/09/15.
*/
public class ContactsOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "contactsDatabase.db";
private static final String TABLE_CREATE = "CREATE TABLE " + Contract.Entry.TABLE_NAME + " (" +
                                            Contract.Entry.NAME + " TEXT," + Contract.Entry.NUMBER + " TEXT," +
                                            Contract.Entry.ID + " TEXT);";

public ContactsOpenHelper(Context context){
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
    db.execSQL(TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
    onCreate(db);
}
}

The code of the main class/activity:

主类/活动的代码:

package com.example.marcos.myapplication;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.v7.widget.SearchView;

public class ExampleActivity extends AppCompatActivity {

ContactsOpenHelper dbHelper;
SearchView searchView;
SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_example);
    dbHelper = new ContactsOpenHelper(this);;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_example, menu);

    searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

    return super.onCreateOptionsMenu(menu);
}

@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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        showSettings();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void showMessage(View view){
    MyDialogFragment mdf = new MyDialogFragment(getApplicationContext());
    mdf.show(getFragmentManager(), "TAG");
}

public void addContact(View view){
    db = dbHelper.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(Contract.Entry.NAME, "Mr Green");
    values.put(Contract.Entry.NUMBER, "07456456156");
    values.put(Contract.Entry.ID, 1);

    db.insert(Contract.Entry.TABLE_NAME,"null",values);
}

public void viewContacts(View view){
    db = dbHelper.getReadableDatabase();

    String[] projection = {Contract.Entry.NAME,Contract.Entry.NUMBER,Contract.Entry.ID};

    Cursor c = db.query(Contract.Entry.TABLE_NAME, projection, null, null, null, null, null);
}

public void showSettings(){
    Intent intent = new Intent(this, Settings.class);
    startActivity(intent);
}
}

The layout XML file:

布局XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".ExampleActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    android:onClick="showMessage"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add contact"
    android:onClick="addContact"
    android:id="@+id/addButton"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="View contacts"
    android:onClick="viewContacts"
    android:layout_below="@id/addButton"
    />
</RelativeLayout>

The error lines that I get when pressing the "Add button":

按下“添加按钮”时出现的错误行:

09-22 17:44:38.672  12294-12294/com.example.marcos.myapplication E/SQLiteLog﹕ (1) table contacts has no column named number
09-22 17:44:38.672  12294-12294/com.example.marcos.myapplication E/SQLiteDatabase﹕ Error inserting number=07456456156 name=Mr Green id=1
android.database.sqlite.SQLiteException: table contacts has no column named number (code 1): , while compiling: INSERT INTO contacts(number,name,id) VALUES (?,?,?)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
        at com.example.marcos.myapplication.ExampleActivity.addContact(ExampleActivity.java:67)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at android.view.View$1.onClick(View.java:4015)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I'm getting crazy trying to figure out the cause of the error: the database is not created, the data can't be inserted into the table... I think it's beyond my knowledge.

我正在疯狂地试图弄清楚错误的原因:数据库没有创建,数据无法插入表中......我认为这超出了我的知识。

I'd really appreciate some help.

我真的很感激一些帮助。

Cheers!

干杯!

1 个解决方案

#1


0  

Iterate the database version to 3 and add a DROP statement in the onUpgrade function of ContactsOpenHelper:

将数据库版本迭代为3并在ContactsOpenHelper的onUpgrade函数中添加DROP语句:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
}   

I also reccomend adding a log statement to the onCreate function of ContactsOpenHelper to ensure the onCreate function is actually being run. It seems like it should be, but you never know.

我还建议在ContactsOpenHelper的onCreate函数中添加一个日志语句,以确保实际运行onCreate函数。它似乎应该是,但你永远不会知道。

#1


0  

Iterate the database version to 3 and add a DROP statement in the onUpgrade function of ContactsOpenHelper:

将数据库版本迭代为3并在ContactsOpenHelper的onUpgrade函数中添加DROP语句:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
}   

I also reccomend adding a log statement to the onCreate function of ContactsOpenHelper to ensure the onCreate function is actually being run. It seems like it should be, but you never know.

我还建议在ContactsOpenHelper的onCreate函数中添加一个日志语句,以确保实际运行onCreate函数。它似乎应该是,但你永远不会知道。