Updating Listview Without Duplication
I am writing a music player application with playlists, and I am trying to display the songs that have been chosen. All of the code for that works fine, but when a song is added, t
Solution 1:
Do this in your Activity Class.
publicclassMyActivityextendsActivity { privateSongListAdapter _songListAdapter; @OverridepublicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createLeftList(); } privatevoidcreateLeftList(){ DatabaseHandler db = newDatabaseHandler(this); ListView leftSongView = (ListView) findViewById(R.id.left_playlistView); _songListAdapter = newSongListAdapter(this, db.getAllsongs()); leftSongView.setAdapter(_songListAdapter); } //TODO use this whenever you wanna update your list.publicvoidupdateSongView(List<String> songsList){ if(_songListAdapter != null && songsList != null){ _songListAdapter.updateMusicList(songsList); } } }
Then create and Adapter class and follow the pattern.
publicclassSongListAdapterextendsBaseAdapter{ privateContext _context; privateList<String> musicList = newArrayList(); publicSongListAdapter(Context context, List<String> musicList){ _context = context; this.musicList.clear(); this.musicList.addAll(musicList); } publicvoidupdateMusicList(List<String> musicList){ this.musicList.clear(); this.musicList.addAll(musicList); notifyDataSetChanged(); } @Overridepublic int getCount() { return musicList.size(); } @OverridepublicObjectgetItem(int position) { return musicList.get(position); } @Overridepublic long getItemId(int position) { return position; } @OverridepublicViewgetView(int position, View convertView, ViewGroup parent) { if(convertView == null){ convertView = LayoutInflater.from(_context).inflate(R.layout.music_view, parent, false); // TODO folow view holder pattern. } String music = (String) getItem(position); if(music != null){ //TODO update your views Here } return convertView; } @OverridepublicvoidnotifyDataSetChanged() { super.notifyDataSetChanged(); //TODO peform any custon action when this is called if needed. } }
Post a Comment for "Updating Listview Without Duplication"