2012-04-18 5 views
0
String[] temp = new String[adapter.getCount()]; 

     for(int i = 0; i < adapter.getCount(); i++) 
      temp[i] = adapter.getItem(i).toString(); 


     List<String> list = Arrays.asList(temp); 

     Collections.sort(list); 

     adapter.clear(); 

     comment = new Comment(); 

     for(int i = 0; i < temp.length; i++) 
     { 
      comment.setComment(temp[i]); 
      System.out.println("comment is: " + comment.getComment()); 
      adapter.insert(comment, i); 
      System.out.println("adapter is: " + adapter.getItem(i)); 

     } 

     for(int i = 0; i < adapter.getCount(); i++) 
      System.out.println(adapter.getItem(i)); 

上記のコードは、入力されたArrayAdapterのソートを実行します。私はSQLiteHelperとSQLデータベースを使用しているヘルパークラスです。Android:ArrayAdapter;コピーされたデータ。それをソートしました。 ArrayAdapterに書き戻します。表示が適切に更新されない

これで、ArrayAdapter内のすべてのデータを消去した後、データが辞書順並べ替え順に追加されることを確認します。

しかし、これを確認するための最後のforループに到達するまでに、ArrayAdapterはすべてのインデックスでリストの最後の項目を複製しました。これは奇妙で、私には意味をなさない。もちろんこれも画面に反映されます。

あなたは何が起こっているのかを理解するための支援を提供できますか?すべての変更が行われ

答えて

1

。したがって、ArrayAdapterのすべての位置は、全く同じ「コメント」オブジェクト参照を持ちます。この単一のインスタンスは、元のリストから最後の文字列に設定されているので、すべてのListViewアイテムは同じように見えます。これを解決するには、 'comment'のインスタンス化をforループに移して、各アダプターの位置ごとに一意の「コメント」インスタンスを作成します。私はあなたのコードを若干最適化しました。

// -- Count used repeatedly, particularly in for loop - execute once here. 
int orgCount = adapter.getCount(); 

String[] temp = new String[orgCount]; 

for(int i = 0; i < orgCount; i++) 
    temp[i] = adapter.getItem(i).toString(); 


List<String> list = Arrays.asList(temp); 

Collections.sort(list); 

// -- Prevent ListView refresh until all modifications are completed. 
adapter.setNotifyOnChange(false); 
adapter.clear(); 


for(int i = 0; i < temp.length; i++) 
{ 
    // -- Instantiation moved here - every adapter position needs a unique instance. 
    comment = new Comment(); 
    comment.setComment(temp[i]); 
    System.out.println("comment is: " + comment.getComment()); 
    // -- Changed from insert to add. 
    adapter.add(comment); 
    System.out.println("adapter is: " + adapter.getItem(i)); 
} 

for(int i = 0; i < adapter.getCount(); i++) 
    System.out.println(adapter.getItem(i)); 

// -- Auto notification is disabled - must be done manually. 
adapter.notifyDataSetChanged(true); 
// -- All modifications completed - change notfication setting if desired. 
adapter.setNotifyOnChange(true); 

EDIT あなたが一度に一つの追加/挿入しているので、また、あなたはすべての修正が完了した後まで実行からnotifyDataSetChangedを遅らせることもできます。これにより、すべての変更時にListViewが更新されなくなります。私は上記のコードにそれを含めました。

1

コールadapter.notifyDataSetChanged() ..あなたはArrayAdapterを通じて「コメント」の同じインスタンスを使用している

+0

ありがとうございます。私はadapter.notifyDataSetChanged()を呼び出しましたが、それと同じ結果です:ArrayAdapterの最後の要素でListViewのビューを生成します。何が起きているのか分かりません。 ArrayAdapterの変更と同様に、データベースへの挿入とdeltionは完全に機能します。しかし、これを整理し、それを見通し内に表示しようとすることは困難であることが判明しています。 – user633658

関連する問題