初学者 - 将sqlite数据作为全局变量加载

时间:2013-04-13 13:59:15

标签: android eclipse sqlite

Database.java

public class Data extends SQLiteOpenHelper {
public static String week, classes, title, mat, it, comp, que;

///更常见的代码,如create,drop database

 public String[] getAllIAI(){

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_IAI + "WHERE KEY_week =" +LessonPlanner.itemWeek+ "AND KEY_class=" +LessonPlanner.itemClass ;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor3 = db.rawQuery(selectQuery, null);
    String[] data = null;
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {

            title=cursor.getString(3);
            mat=cursor.getString(4);
            it=cursor.getString(5);
       } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning lables
    return data;
}   

Recomend.Java

声明

TextView  title, mat, IT;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recomend);

    title = (TextView) findViewById(R.id.titleText);
    mat = (TextView) findViewById(R.id.materialText);
    IT = (TextView) findViewById(R.id.instTText);

    title.setText(Data.title);
    mat.setText(Data.mat);
    IT.setText(Data.it);

我认为代码在某处是错误的,因为Textview(多行文本)没有显示任何内容。 任何人都可以指出我的错误?我完全不熟悉Eclipse。

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误,首先,您返回的数组“数据”始终为null,因此您无法从中获取任何内容。

其次,如果你计划从数据库中获得几个结果,你应该声明一个列表并添加你从数据库中获取的objets,目前你的循环完全无用,你实例化你从未使用过的变量......

这是一个示例,说明如何从数据库中获取List,但您也可以获得Cursor,Array或任何您需要的内容:

// Getting All Categories By ID
    public List<Category> getCategoriesList() {
        String selectQuery = "SELECT " + CATEGORY_ID + ", " + CATEGORY_NAME + " FROM " + CATEGORY_TABLE + " ORDER BY " + CATEGORY_ID + " ASC";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null); 

        List<Category> categoriesList = new ArrayList<Category>();

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Category category = new Category(cursor.getInt(0), cursor.getString(1), false);
                categoriesList.add(category);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return categoriesList;
    }

注意:在这个例子中,我从DB中获取了几行,如果你只想获得一行,只需删除循环do-while并直接返回对象。