使用rawquery对单词进行排序

时间:2018-02-02 06:45:13

标签: android sqlite sorting

我希望能够使用原始查询按升序对单词进行排序(因为我将使用游标)。但是,当我尝试按字母顺序对单词进行排序时,我的应用程序崩溃了,给了我这个错误:

android.database.sqlite.SQLiteException: near "SELECTWORDFROM": syntax error (code 1): , while compiling: SELECTWORDFROM WORDSORDER BYWORD

以下显示发生错误的代码。

WordsDataSource.java

public Cursor sortWords (){
        String[] wordname = new String[]{ WordsHelper.COLUMN_WORD };
        Cursor cursor = mDatabase.rawQuery
            ("SELECT"+ TextUtils.join(", ", wordname)+"FROM " +
                    WordsHelper.TABLE_WORDS +
                    "ORDER BY"+ TextUtils.join(", ", wordname),null);
        //Cursor cursor= mDatabase.query(WordsHelper.TABLE_WORDS,wordname , null, null, null, null, WordsHelper.COLUMN_WORD+" ASC");

return cursor;
    }

WordsHelper.java(我的实际数据库)

package mapp.com.sg.pocketdictionary.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class WordsHelper extends SQLiteOpenHelper {
    public static final String TABLE_WORDS ="WORDS";
    public static final String COLUMN_ID = "_ID";
    public static final String COLUMN_WORD = "WORD";
    public static final String COLUMN_MEANING = "MEANING";
    public static final String COLUMN_TYPE = "TYPE";
    public static final String COLUMN_FAVOURITE = "FAVOURITE";

    private static final String DB_NAME = "words.db";
    private static final int DB_VER = 1;
    private static final String DB_CREATE = "CREATE TABLE "+TABLE_WORDS+
            " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT" +
            ", " + COLUMN_WORD + " TEXT, "  +
            COLUMN_MEANING + " TEXT,"+
            COLUMN_TYPE + " TEXT,"+ COLUMN_FAVOURITE +" INTEGER)";


    public WordsHelper(Context context){
        super(context, DB_NAME, null, DB_VER);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(DB_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

我哪里出错了?

1 个答案:

答案 0 :(得分:1)

您正在使用导致错误的Arrays.ToString()方法。 尝试使用TextUtils.join(", ", wordname)

将数组转换为字符串

Arrays.toString()返回" debug-style" 字符串,即。" [WORD]"。而不是" [WORD]"你需要WORD

<强>更新

查看当前错误

android.database.sqlite.SQLiteException: near "SELECTWORDFROM": syntax error (code 1): , while compiling: SELECTWORDFROM WORDSORDER BYWORD

您需要在SELECT之后和ORDER之后添加空格

尝试以下

mDatabase.rawQuery
            ("SELECT "+ TextUtils.join(", ", wordname)+" FROM " +
                    WordsHelper.TABLE_WORDS +
                    " ORDER BY "+ TextUtils.join(", ", wordname),null);