在Android中获取SQLite结果的正确方法

时间:2019-11-28 05:09:57

标签: sqlite

TextView cc = (TextView) popupWindow.getContentView().findViewById(R.id.course_code);
        TextView rr = (TextView) popupWindow.getContentView().findViewById(R.id.room_no);
        TextView tc = (TextView) popupWindow.getContentView().findViewById(R.id.instructor);

        DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getActivity());
        databaseAccess.Open();

        Cursor qr = databaseAccess.getFaculty(inst);

        //databaseAccess.Close();

       if(qr.getCount() > 0)
       {

           tc.setText("AAAAAAA");           
           //tc.setText(qr.getString(qr.getColumnIndex("fac_name")));
           Toast.makeText(getActivity(),"Fac_Code : "+qr.getCount(),Toast.LENGTH_LONG).show();
       }

如果我写tc.setText("AAAAAAA");行,那是工作,正在执行程序并以正确的值显示弹出窗口和Toast,但是当我想显示下一行以获取名称时,则是正在关闭程序

以下是数据库查询

 public Cursor getFaculty(String fc){
        Cursor c = database.rawQuery("Select * from faculties where fac_code = '"+fc+"'",new String[]{});
        return c;
    } 

请任何人,有什么问题及其解决方案。我为此花了很长时间,但无法解决

1 个答案:

答案 0 :(得分:0)

您没有定位游标,因此尝试从第一行之前的位置读取数据,这无法完成。

这样尝试:-

   Cursor qr = databaseAccess.getFaculty(inst);
   if(qr.moveToFirst()) {
       tc.setText("AAAAAAA");           
       tc.setText(qr.getString(qr.getColumnIndex("fac_name")));
       //Toast.makeText(getActivity(),"Fac_Code : "+qr.getCount(),Toast.LENGTH_LONG).show(); //Commented out as the issue could be a Null Pointer Exception
   }

P.S。

您可以使用

public Cursor getFaculty(String fc){
    return database.rawQuery("Select * from faculties where fac_code=?,new String[]{fc});
}
  • 此外,这可以防止SQL注入

而不是:-

public Cursor getFaculty(String fc){
    Cursor c = database.rawQuery("Select * from faculties where fac_code = '"+fc+"'",new String[]{});
    return c;
}