我如何创建一个方法,从sqlite数据库中获取数据,并使用该方法将其显示在片段中

时间:2013-10-15 10:25:27

标签: android sqlite cursor

这是一个片段。我想从数据库中获取特定数据并将其存储在字符串中,然后将其放在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;
}

2 个答案:

答案 0 :(得分: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));

希望这有帮助。

答案 1 :(得分: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 ;
}

然后在textview中将其设置如下:

tv.setText(DATABASECLASS.getDataFromDatabase(ID));