-1

这是一个片段。我想从数据库中获取特定数据并将其存储在字符串中,然后将其放入 textview 但我不知道如何构造该方法以及如何使用该方法来获取数据。(光标)请帮帮我。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View layoutView = inflater.inflate(R.layout.fragment_lyrics,
    container, false);
    int hymnNo = fragVal - 1;
        //Database
    DataBaseHelper myDbHelper = new DataBaseHelper(getActivity());
    String lyrics = myDbHelper.data(hymnNo);


    View tv = layoutView.findViewById(R.id.text);

    //((TextView) tv).setText("Hymn Nunmber " + hymnNo);
    return layoutView;
    }

这是数据库助手类 DataBaseHelper.java

public Cursor data(int x){
    SQLiteDatabase db =  SQLiteDatabase.openDatabase(DB_PATH,null,
    SQLiteDatabase.OPEN_READONLY);
    Cursor c = db.rawQuery("Select Lyrics from Hymns where id = " + x , null);
    db.close();
return c;
}
4

2 回答 2

0

尝试,在您的 DataBaseHelper.java 类上创建此方法

public String getData(int x) {
    String dataReturn = null;

    SQLiteDatabase db =  SQLiteDatabase.openDatabase(DB_PATH,null,
    SQLiteDatabase.OPEN_READONLY);
    Cursor c = db.rawQuery("Select Lyrics from Hymns where id = " + x , null);

    try {
        if (cursor.moveToFirst()) {
            dataReturn = cursor.getString(0);
            /** 0 is column position in database that you want to retrieve, it depend on your database settings */
        }
    } catch (Exception ex) {
        idReturn = "empty";
    } finally {
        db.close();
        return dataReturn ;
    }
}

使用以下代码设置 TextView 文本:

View tv = layoutView.findViewById(R.id.text);
tv.setText(myDbHelper.getData(hymnNo));

希望这可以帮助。

于 2013-10-15T10:33:50.807 回答
0

要从数据库创建方法中获取数据,如下所示:

public String getDataFromDatabase(int id) {
    String dataReturn = null;

    SQLiteDatabase db =  SQLiteDatabase.openDatabase(DB_PATH,null,
    SQLiteDatabase.OPEN_READONLY);
    Cursor c = db.rawQuery("Select Lyrics from Hymns where id = " + x , null);
    if(c!= null){
    try {
         if (cursor.moveToFirst()) {
             dataReturn = cursor.getString(1);
         }
     }  catch (Exception ex) {
         idReturn = "empty";
     }  finally {
         db.close();
         return dataReturn ;
     }
  }
  return dataReturn ;
}

然后将其设置在您的文本视图中,如下所示:

tv.setText(DATABASECLASS.getDataFromDatabase(ID));
于 2013-10-15T10:40:59.563 回答