在SQLiteDatabase

时间:2015-09-29 10:54:42

标签: java android sqlite

我正面临这个奇怪的问题,我搜索了很多,但到目前为止没有用。

以下代码用于使用从openhelper类扩展的DBHelper检索SQLite数据库。

public class DBHelper extends SQLiteOpenHelper {

public static final int DB_VERSION = 1;
public static final String DB_NAME = "cp.db";
public static final String DB_PATH = "/data/data/abdulla.com.test/databases/";
public static final String ID = "no";
public static final String NAME = "name";
public static final String FORMULA = "formula";
public static final String MW = "mw";
public static final String OMEGA = "omega";
public static final String TC = "tc";
public static final String PC = "pc";
SQLiteDatabase db;
Cursor cursor;
ArrayList<String> elementName;

public DBHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists elements");
    this.onCreate(db);

}


public List<Element> getAllElements() {
    List<Element> elementList = new ArrayList<Element>();
    // Select All Query
    Cursor cursor = null;
        String selectQuery = "SELECT  * FROM elements";
        SQLiteDatabase db = this.getReadableDatabase();
        cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Element element = new Element();
            element.setNo(Integer.parseInt(cursor.getString(0)));
            element.setFormula(cursor.getString(1));
            element.setName(cursor.getString(2));

            // Adding contact to list
            elementList.add(element);
        } while (cursor.moveToNext());
    }

    // return contact list
    return elementList;
}
}

这是从MainActivity类

捕获的
public class MainActivity extends AppCompatActivity {


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

    DBHelper helper = new DBHelper(this);

    List<Element> elementList = helper.getAllElements();

    for(Element element : elementList){
        String log = "no: "+element.getNo();

        Log.d("No: ", log);
    }

 }
}

我收到此错误:

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{abdulla.com.test/abdulla.com.test.MainActivity}: 
android.database.sqlite.SQLiteException: no such table: elements (code 1):  
, while compiling: SELECT  * FROM elements

我知道元素表就在那里

任何帮助?

1 个答案:

答案 0 :(得分:0)

可能问题出在您的onUpgrade()方法中。如果您的数据库没有版本,应用程序会尝试升级它,并删除您的表(db.execSQL("drop table if exists elements");)。

解决方案:set version to DB或更改onUpgrade()方法(删除DROP语句)。