在rawQuery()中执行Cursor查询时发出问题

时间:2018-01-19 09:49:27

标签: android sqlite android-sqlite sqliteopenhelper

无法从外部数据库data.db中检索数据,它已存储在其中的值。因为已经存在数据库中填充数据的表,所以它会因表格而抛出错误。

我在清单中给出了READ和WRITE持久性。

DataBaseHelper.java

 public class DataBaseHelper extends SQLiteOpenHelper {

@SuppressLint("SdCardPath")
private static String DB_PATH = "/data/data/com.example.databaseDemo/";

private static String DB_NAME = "data.db";

private SQLiteDatabase myDataBase;

private final Context myContext;
Cursor cursor;


public DataBaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
}


public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
        //do nothing - database already exist
    } else {


        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {

        //database does't exist yet.

    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}


@Override
public synchronized SQLiteDatabase getReadableDatabase() {
    return super.getReadableDatabase();
}


private void copyDataBase() throws IOException {

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

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

    //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_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);

}

@Override
public synchronized void close() {

    if (myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}
public List<Album> getDataFromDB() {
    List<Album> modelList = new ArrayList<Album>();
    int i = 1;
    String query = "select * from Calls where call_key = " + i;

    SQLiteDatabase db = this.getReadableDatabase();
    cursor = db.rawQuery(query, null);

    if (cursor.moveToFirst()) {
        do {
            Album model = new Album();
            model.setName(cursor.getString(2));
            model.setNumOfSongs(cursor.getString(3));

            modelList.add(model);
        } while (cursor.moveToNext());
    }
    Log.d("student data", modelList.toString());
    return modelList;
  }
}

我的Logcat:

   01-19 15:05:09.903 E/SQLiteLog: (1) no such table: Calls
   01-19 15:05:09.911 D/AndroidRuntime: Shutting down VM
   01-19 15:05:09.911 W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4191c2a0)
   01-19 15:05:09.919 E/AndroidRuntime: FATAL EXCEPTION: main
                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.databaseDemo.databasedemo/com.example.databaseDemo.databasedemo.MainActivity}: android.database.sqlite.SQLiteException: no such table: Calls (code 1): , while compiling: select * from Calls where call_key = 1
                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2122)
                                     at android.app.ActivityThread.access$600(ActivityThread.java:140)
                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                     at android.os.Looper.loop(Looper.java:137)
                                     at android.app.ActivityThread.main(ActivityThread.java:4895)
                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                     at 

注意:我已经确认很多时候查询中提到的表名确实存在。在DBite浏览器中测试SQLite时,相同的查询返回数据。

我在MainActivity.java中的实现

public class MainActivity extends AppCompatActivity {


RecyclerView recyclerView;
private MainAdapter adapter;
private List<Album> albumList;
DataBaseHelper helper;


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

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    albumList = new ArrayList<>();


    LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    helper = new DataBaseHelper(this);
    albumList = helper.getDataFromDB();
    adapter = new MainAdapter(this, albumList);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}
} 

1 个答案:

答案 0 :(得分:0)

您从表格中获取数据&#34;来电&#34;但是没有创建表格,您的 @Override public void onCreate(SQLiteDatabase db) { String CREATE_CALLS_TABLE = "CREATE TABLE " + "Calls "+ "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")"; db.execSQL(CREATE_CALLS_TABLE ); } 实现应该是这样的,根据您的需要更改字段。

foreach