android studio sqlite 异常

标签 android database sqlite

单击词典页面上的搜索按钮时出现错误。请帮助我。

我的数据库助手类是:

package com.example.pro.phord;

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 android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by me on 4/2/2015.
 */
public class wordshelper extends SQLiteOpenHelper{
    private static final int version = 1;
    private static final String DATABASE = "phords.db";
    private static final String TABLE= "words";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_WORD = "word";
    private static final String COLUMN_DESCRIPTION = "description";
    SQLiteDatabase db;


    private static final String TABLE_CREAT = "create table words(id integer not null , " +
            "word text primary key not null , description text not null);";

    public wordshelper(Context context) {
        super(context, DATABASE, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREAT);
        this.db = db;
    }

    public void insertContract(Contract c) {
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        String query = "select * from words";

        Cursor cursor = db.rawQuery(query , null);
        int count = cursor.getCount();

        values.put(COLUMN_ID , count);
        values.put(COLUMN_WORD, c.getWord());
        values.put(COLUMN_DESCRIPTION, c.getDescription());
        db.insert(TABLE, null, values);
        db.close();
    }
    public Cursor getMeaning(String search_word,SQLiteDatabase sqLiteDatabase){

        String[] projections = {COLUMN_WORD,COLUMN_DESCRIPTION};
        String selection = COLUMN_WORD + " LIKE ?";
        String[] selection_args = {search_word};
        Cursor cursor = sqLiteDatabase.query(TABLE,projections,selection,selection_args,null,null,null);
        return cursor;

    }


    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
        String query = "DROP TABLE IF EXISTS "+TABLE;
        db.execSQL(query);
        this.onCreate(db);

    }

}

我的字典类:

package com.example.pro.phord;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Locale;

/**
 * Created by Me on 27-Aug-15.
 */
public class Dictionary extends Activity {
    EditText searches;
    TextView words,descriptions;
    private EditText resultText;
    SQLiteDatabase sql;
    wordshelper wordhelp = new wordshelper(this);
    String search_word;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dictionary);
        searches = (EditText)findViewById(R.id.etsearch);
        words = (TextView)findViewById(R.id.tvword);
        descriptions = (TextView)findViewById(R.id.tvdescription);
        resultText=(EditText)findViewById(R.id.etsearch);
    }
    public void onSearch(View v)
    {
        search_word = searches.getText().toString();
        wordhelp = new wordshelper(getApplicationContext());
        sql = wordhelp.getReadableDatabase();
        Cursor cursor = wordhelp.getMeaning(search_word,sql);
        if (cursor.moveToFirst())
        {
            String WORD = getString(0);
            String DESCRIPTION = getString(1);
            words.setText(WORD);
            descriptions.setText(DESCRIPTION);
        }
    }
 public void onSpeech(View v)
 {
     if (v.getId()==R.id.imageButton)
     {
         EditText result=(EditText)findViewById(R.id.etsearch);
         promptSpeechInput();
     }
 }
    public void promptSpeechInput(){
        Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        i.putExtra(RecognizerIntent.EXTRA_PROMPT, "say something");
        try {
            startActivityForResult(i, 100);
        }
        catch (ActivityNotFoundException a)
        {
            Toast.makeText(Dictionary.this,"sorry! your device doesn't support speech",Toast.LENGTH_LONG).show();
        }
    }

    public void onActivityResult(int request_code,int result_code,Intent i )
    {
        super.onActivityResult(request_code,result_code,i);

        switch (request_code) {
            case 100:
                if (result_code == RESULT_OK && i !=null)
                {
                    ArrayList<String> result = i.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    resultText.setText(result.get(0));
                }
                break;
        }
    }
}

我的字典 xml 代码是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/relative"
    android:background="@drawable/marshmellows">



    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Word/phrase"
        android:id="@+id/textView9"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textSize="25dp"
        android:textStyle="bold"
        android:layout_marginTop="70dp"
        />

    <TextView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Meaning"
        android:id="@+id/textView10"
        android:textSize="25dp"
        android:textStyle="bold"
        android:layout_marginTop="86dp"

        android:layout_below="@+id/textView9"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ok"
        android:id="@+id/Bok"
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/textView9"
        android:layout_toEndOf="@+id/textView9" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etsearch"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/imageButton"
        android:layout_toStartOf="@+id/Bsearch"
        android:layout_marginTop="20dp"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="70dp"
        android:text="Search"
        android:id="@+id/Bsearch"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="onSearch"
        />

    <ImageButton
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/imageButton"
        android:src="@drawable/r"
        android:onClick="onSpeech"
        android:layout_toLeftOf="@+id/Bsearch"
        android:layout_toStartOf="@+id/Bsearch" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="70dp"
        android:id="@+id/tvword"
        android:layout_below="@+id/textView9"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="250dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/tvdescription"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/textView10"/>

</RelativeLayout>

我的合约类:

package com.example.pro.phord;

/**
 * Created by Me on 13-Sep-15.
 */
public class Contract {
    String word,description;
    public void setWord(String word) {this.word=word;}
    public String getWord() {return this.word;}
    public void setDescription(String description){this.description=description;}
    public String getDescription(){return this.description;}
}

我的 logcat 说:

09-19 07:53:46.549    2325-2325/com.example.pro.phord E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.pro.phord, PID: 2325
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:4012)
            at android.view.View.performClick(View.java:4761)
            at android.view.View$PerformClick.run(View.java:19767)
            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:5312)
            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:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
     Caused by: java.lang.reflect.InvocationTargetException
            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:4007)
            at android.view.View.performClick(View.java:4761)
            at android.view.View$PerformClick.run(View.java:19767)
            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:5312)
            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:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
     Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
            at android.content.res.Resources.getText(Resources.java:274)
            at android.content.res.Resources.getString(Resources.java:360)
            at android.content.Context.getString(Context.java:376)
            at com.example.pro.phord.Dictionary.onSearch(Dictionary.java:47)
            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:4007)
            at android.view.View.performClick(View.java:4761)
            at android.view.View$PerformClick.run(View.java:19767)
            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:5312)
            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:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

最佳答案

宁可发布这么多代码...首先解释您收到的错误是什么,然后发布 logcat 报告。在提出一些建议后,无论是在出现错误的地方发布示例还是代码部分......无论如何,在经历错误和代码之后,你在 Dictionary 类的 onSearch 方法中的 if 条件中犯了一个简单的错误

if (cursor.moveToFirst())
        {
            String WORD = getString(0);
            String DESCRIPTION = getString(1);
  //remaining code
 }

改成

if (cursor.moveToFirst())
        {
            String WORD = cursor.getString(0);
            String DESCRIPTION = cursor.getString(1);
  //remaining code
 }

由于直接使用 getString,它在资源文件中查找

另一个建议是使用列索引使用列名示例

if (cursor.moveToFirst()) {
    str = cursor.getString(cursor.getColumnIndex("content"));
}

关于android studio sqlite 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668227/

相关文章:

android - 在授予权限的 Android SD 卡上创建文件时出现 IO 异常

android - 为什么解绑服务onDestroy?

android - 当我使用 'poweroff' 重新启动时,如何在 HTC 中获取 Boot_Complete Intent ?

java - 通过点击 Android 中的 "Next"和 "Previous"按钮来更改阵列图像和音频

php - 使用 JS/PHP/MySQL 检查新内容?

sql - 无法在表中插入新列

mysql - 系统不喜欢使用索引

python - Django:使用sqlite3作为数据库在Heroku上部署应用程序

android - 从 SQLite 数据库制作 ListView

java - Android - 与 SQL 查询作斗争