Listview显示更新后的新旧内容

时间:2012-12-04 12:30:11

标签: android android-listview listactivity listadapter simpleadapter

在我的应用程序中,listview是从SQLite数据库加载的,它使用SimpleAdapter来设置ListView。当用户在listitem上执行longclick时,该项将从数据库中删除,并且应该更新listviw。但是当我从数据库中删除项目时,listview会显示旧数据和新数据。 请提出一些解决方案。 感谢名单。

以下是我的代码:

public class FavouriteListActivity extends ListActivity {       
    public final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    ListAdapter adapter;
    public ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>(); 
    ArrayList<String> titles = new ArrayList<String>();
    String title,artist;    
    SQLiteAdapter adp;
    SimpleCursorAdapter cursoradp;
    Cursor cursor,cursorDB; 

    @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.favouritelist);         

        // Adding menuItems to ListView
        final String[] from = {"songTitle", "artist","duration"};
        final int[] to={R.id.fav_songTitle,R.id.fav_songArtist,R.id.fav_duration};

        ListView lv = getListView();            
        songsListData = getFavourites();
        final ListAdapter adapter = new SimpleAdapter(this,songsListData,
                    R.layout.favouritelist_item, from, to);
        lv.setFastScrollEnabled(true);  
        setListAdapter(adapter);
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {
            public boolean onItemLongClick(AdapterView<?> av, View v,
                     final int pos,final long id) {
                final AlertDialog.Builder b = new AlertDialog.Builder(FavouriteListActivity.this);
                b.setTitle("Are you sure you want to delete?");
                b.setIcon(android.R.drawable.ic_delete);               
                b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String title = songsListData.get(pos).get("songTitle");
                        ListAdapter adapter = null;
                        adp.delete_byTitle(title);
                        songsListData.clear();
                        setListAdapter(null);
                        songsListData = getFavourites();                                                                                         
                        adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);

                        setListAdapter(adapter);
                        Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
                    }
                });
                b.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });
                b.show();
                return true;
            }           
        });        
    }
    public ArrayList<HashMap<String,String>> getFavourites()
    {
        ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
        ArrayList<String> titles = new ArrayList<String>();
        adp = new SQLiteAdapter(this);        
        adp.openToRead();
        cursorDB = adp.queueAll();
        if(cursorDB.moveToFirst())
        {
            for(int i=0;i<cursorDB.getCount();i++)
            {
                titles.add(cursorDB.getString(cursorDB.getColumnIndex("Title")));
                cursorDB.moveToNext();
            }
            String[] songTitles = new String[titles.size()];
            songTitles = titles.toArray(songTitles);
            if(songTitles == null)
            {
                songTitles =null;
            }
            String whereClause = MediaStore.Audio.Media.TITLE + " IN ( ?";
            if (songTitles.length>1) 
            {
                for (int j = 1 ; j < songTitles.length; ++j) 
                {
                    whereClause+=", ?";
                }
            }
            whereClause+=")";             
            Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null ,whereClause,songTitles,MediaStore.Audio.Media.TITLE);            
            if (cursor == null) 
            {
                  //Query Failed , Handle error.
            }
            else if (!cursor.moveToFirst()) 
            {
                 //No media on the device.
            }
            else
            {            
                int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);  
                int idColumn = cursor.getColumnIndexOrThrow(android.provider.MediaStore.Audio.Media.DATA);                
                int artistcolumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
                int durationcolumn =cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION);
                for(int i=0;i<cursor.getCount();i++)
                {
                    String thisTitle = cursor.getString(titleColumn);                   
                    String path = cursor.getString(idColumn);
                    String artist = cursor.getString(artistcolumn);
                    Long duration = cursor.getLong(durationcolumn);
                    Utilities objUtilities = new Utilities();
                    String timeDuration = objUtilities.milliSecondsToTimer(duration);   
                    HashMap<String, String> song = new HashMap<String, String>();
                    song.put("songTitle",thisTitle);
                    song.put("songPath", path);
                    song.put("artist", artist);
                    song.put("duration",timeDuration);
                    // Adding each song to SongList
                    songsList.add(song);
                    cursor.moveToNext();
                 }
            }
                // looping through playlist
            for (int i = 0; i < songsList.size(); i++) {
                    // creating new HashMap
                HashMap<String, String> song = songsList.get(i);
                    // adding HashList to ArrayList
                songsListData.add(song);
            }       
        }
        return songsListData;
    }
}

3 个答案:

答案 0 :(得分:2)

您永远不会清除songList,因此每次删除时都会添加所有项目。

反过来又全部复制到songsListData。

答案 1 :(得分:0)

从数据库中删除数据后,请调用

Listview.invalidateViews();

并将适配器重置为列表。

实际上它会从数据库中删除,但它会在ListView中显示旧列表,因此会使旧视图无效并重置适配器。

答案 2 :(得分:-2)

每次数据更改时调用adapter.notifyDataSetChanged()。

b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String title = songsListData.get(pos).get("songTitle");                        
                        adp.delete_byTitle(title);
                        songsListData.clear();
                        setListAdapter(null);
                        songsListData = getFavourites();                                                                                         
                        adapter = new SimpleAdapter(getApplicationContext(), songsListData,R.layout.favouritelist_item, from, to);

                        setListAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        Toast.makeText(FavouriteListActivity.this,"Song is removed from Favourites", Toast.LENGTH_SHORT).show();
                    }
                });