2015-10-18 68 views
1

這個程序的主要動機是在Android ListView中顯示一些來自SQLite的數據。HashMap只給我最後一個數據

protected String doInBackground(String... args) { 

      SQLiteOpenHelper helper = new Dictionary(contex); 
      SQLiteDatabase db = helper.getReadableDatabase(); 

      EditText et = (EditText) findViewById(R.id.search); 
      String word = et.getText().toString(); 
      wordlist = new ArrayList<>(); 

      String query = "SELECT ID, WORD" + 
        " FROM E_DICT WHERE WORD LIKE '"+word+"%' ORDER BY WORD ASC LIMIT 100 "; 
       Cursor cursor = db.rawQuery(query, null); 
       if(cursor!=null){ 
        if(cursor.moveToFirst()){ 
         do{ 

          long a = cursor.getLong(0); 
          String b = cursor.getString(1); 

          HashMap<String, String> map = new HashMap<String, String>(); 
          map.put(EDICT_WORD, b); 
          map.put(EDICT_ID, ""+a); 
          Log.d("RESULT", a +" " + b); //Till this this like everything seems to be ok. 
          wordlist.add(map); 
         } 
         while(cursor.moveToNext()); 

        }} 
      return null; 
     } 

現在我加載我的數據在某些AsyncTask<String, String, String>這樣的:

 protected void onPostExecute(String file_url) { 
      pDialog.dismiss(); 
      runOnUiThread(new Runnable() { 
       public void run() { 
        ListAdapter adapter = new SimpleAdapter(
          Main.this, wordlist, R.layout.word_list, 
          new String[] {EDICT_WORD, EDICT_ID}, 
          new int[] {R.id.eDict_Word, R.id.eDict_Id}); 
        setListAdapter(adapter); 
       } 
      }); 
     } 

這給了我最後EDICT_ID只列表視圖輸出。我在哪裏做錯了?

+0

您的數據庫中有多少數據?而且,wordlist有多少項? –

回答

0

看來你總是在創建新的HashMap,並且只返回一個值。

所以,從

if(cursor!=null){ 
    if(cursor.moveToFirst()){ 
    .... 
    HashMap<String, String> map = new HashMap<String, String>(); 
    while(cursor.moveToNext()); 
}} 

移動你的HashMap來循環之外。

HashMap<String, String> map = new HashMap<String, String>(); 
if(cursor!=null){ 
    .... 
} 
+0

但是,HashMap正被添加到'wordList',它是一張地圖列表。 – Cinnam

+0

哦,沒錯。 –

相關問題