2016-02-13 75 views
0

即時通訊使用listview來顯示一個數據庫數據(3個字段,但只顯示名稱),當我點擊1項目,AlertDialog出現,我可以看到該行的其他字段,我使用遊標選擇數據然後傳遞我想要的字符串,但是每當我按下一個時,我就會得到一個預期的不同元素,我知道我可以對我想獲得的行進行查詢,但是在SQLite中我很糟糕所以我寧願做這種方式,這裏是代碼:奇怪的光標行爲

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
            long id) { 
       Cursor crs = db.rawQuery("SELECT * FROM Usuarios", null); 

       crs.moveToPosition(position); 

       // get prompts.xml view 
       LayoutInflater li = LayoutInflater.from(context); 

       View promptsView1 = li.inflate(R.layout.dialog1, null); 

       AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
         context); 

       // set prompts.xml to alertdialog builder 
       alertDialogBuilder.setView(promptsView1); 

       final TextView nam = (TextView) promptsView1 
         .findViewById(R.id.name1); 
       nam.setText(crs.getString(0)); 

       final TextView ape = (TextView) promptsView1 
         .findViewById(R.id.apellido2); 
       ape.setText(crs.getString(1)); 

       final TextView loc = (TextView) promptsView1 
         .findViewById(R.id.loc1); 
       loc.setText(crs.getString(2)); 

       // set dialog message 
       alertDialogBuilder 
         .setCancelable(true); 

       // create alert dialog 
       AlertDialog alertDialog = alertDialogBuilder.create(); 

       // show it 
       alertDialog.show(); 
       //cursor = null; 

      } 
     }); 

使用這種方法或一個(查詢語句)任何幫助,將不勝感激

+0

不要使用'rawQuery',不使用'position'但使用'id'。這一定會打破 –

+0

我應該用什麼來代替rawQuery?我已經嘗試使用ID,儘管它的長型,反正有什麼意義?在調試器中,Im爲id和位置獲取相同的值 – Aleeeeeeeeeeeeex

+0

項目的位置可以在query1和query2之間變化,其'id'不會。 –

回答

0

我不知道你想做什麼。但我希望我能幫上忙。

首先,當您只需要一行時,請不要使用select *,而應使用ID等密鑰列。

cursor = db.rawQuery("Select * from " + TABLE + " where " + where, null); 

那麼,如果查詢返回一行,將光標移動到第一位置和讀取數據

if (cursor != null) 
    if (cursor.getCount() != 0) 
     cursor.moveToFirst(); 
     item.setText(cursor.getString(cursor 
         .getColumnIndex(ClassesConst.COLUMN_TEXT)));