sqlite AutoComplete TextView from a Local Database File,Android Studio,Java

fv2wmkja  于 2023-10-23  发布在  SQLite
关注(0)|答案(1)|浏览(126)

请帮助我,我试图用本地数据库文件预填充我的自动完成文本视图,我一直得到这个错误

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.saud.app.autocompletesample/com.saud.app.autocompletesample.MainActivity}: android.database.sqlite.SQLiteException: near "drugstable": syntax error (code 1 SQLITE_ERROR): , while compiling: drugstable

低于我的代码
DatabaseHelper.java

package com.saud.app.autocompletesample;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.material.shape.CutCornerTreatment;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;

public class DrugsDataBase extends SQLiteOpenHelper {

    private static String DB_PATH = "";
    private final Context myContext;

    private static final String database_name = "aaa.db";
    private static final int version = 1;
    public static final String table_name = "drugstable";
    public static final String column_id = "id";
    public static final String column_name = "drug";

    private SQLiteDatabase db;

    public DrugsDataBase(Context context) {

        super(context, database_name, null, version);
        this.myContext = context;
        DB_PATH = myContext.getDatabasePath(database_name)
                .toString();
    }

    public void createDataBase()
            throws IOException {

        boolean dbExist = checkDataBase();

        if (dbExist) {
            // do nothing - database already exist
        } else {
            // By calling this method and
            // the empty database will be
            // created into the default system
            // path of your application
            // so we are gonna be able
            // to overwrite that database
            // with our database.
            this.getWritableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error(
                        "Error copying database");
            }
        }
    }

    // Check if the database already exist
    // to avoid re-copying the file each
    // time you open the application
    // return true if it exists
    // false if it doesn't.
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH;
            checkDB
                    = SQLiteDatabase
                    .openDatabase(
                            myPath, null,
                            SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {

            // database doesn't exist yet.
            Log.e("message", "" + e);
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null;
    }

    /**
     * Copies your database from your
     * local assets-folder to the just
     * created empty database in the
     * system folder, from where it
     * can be accessed and handled.
     * This is done by transferring bytestream.
     */
    private void copyDataBase()
            throws IOException {
        // Open your local db as the input stream
        InputStream myInput
                = myContext.getAssets()
                .open(database_name);

        // Path to the just created empty db
        String outFileName = DB_PATH;

        // Open the empty db as the output stream
        OutputStream myOutput
                = new FileOutputStream(outFileName);

        // transfer bytes from the
        // inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase()
            throws SQLException {
        // Open the database
        String myPath = DB_PATH;
        db = SQLiteDatabase
                .openDatabase(
                        myPath, null,
                        SQLiteDatabase.OPEN_READONLY);
    }

    @Override
    public synchronized void close() {
        // close the database.
        if (db != null)
            db.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        SQLiteDatabase db = this.getReadableDatabase();

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase,

        int oldVersion,
        int newVersion) {
            // It is an abstract method which is
            // used to perform different task
            // based on the version of database.
        }


    public ArrayList<String> getNames() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<String> names = new ArrayList<>();
        Cursor cursor = db.rawQuery(table_name, null);
        cursor.moveToNext();

        while (!cursor.isAfterLast()) {

            names.add(cursor.getString(1));
            cursor.moveToNext();
        }

        cursor.close();
        return names;
    }
}

MainActivity.java

package com.saud.app.autocompletesample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private AutoCompleteTextView autoCompleteTextView;
    private ArrayList<String> names;
    private DrugsDataBase dataBase;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
        dataBase = new DrugsDataBase(this);
        names = dataBase.getNames();

        ArrayAdapter<String> autoCompleteAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, names);
        autoCompleteTextView.setAdapter(autoCompleteAdapter);

    }
}
icnyk63a

icnyk63a1#

在DrugsDataBase类的getNames方法中,您应该使用query方法构造一个适当的SQL查询。查询应该从drugstable表中检索特定的列。下面是查询的样子:

public ArrayList<String> getNames() {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<String> names = new ArrayList<>();
    
    // Define the columns you want to retrieve
    String[] columns = { column_name }; // Only retrieve the "drug" column
    
    // Query the table to retrieve the names
    Cursor cursor = db.query(table_name, columns, null, null, null, null, null);
    
    if (cursor != null && cursor.moveToFirst()) {
        do {
            names.add(cursor.getString(cursor.getColumnIndex(column_name)));
        } while (cursor.moveToNext());
        
        cursor.close();
    }
    
    return names;
}

该查询使用query方法从drugstable表的“drug”列中检索值。产生的Cursor将只包含“drug”列值,您可以遍历Cursor以使用药物名称填充ArrayList。
确保正确声明了column_name常量,并且它与数据库表定义中的实际列名匹配。

相关问题