0

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, the listView won't update. I have searched extensively online, but cannot figure out how to fix it. I ended up trying to call leftAdapter.notifyDataSetChanged(); to update the list, but it throws the error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference

I have also tried calling the initializing method (createLeftList()) but it duplicates all of the items in the list.

Method called to initialize listview:

public void createLeftList() {
            DatabaseHandler db = new DatabaseHandler(this);
            leftSongView = (ListView) findViewById(R.id.left_playlistView);
            db.getAllsongs();
            ArrayAdapter<String> leftAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ArrayofName);
            leftSongView.setAdapter(leftAdapter);
            leftSongView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    Toast.makeText(getApplicationContext(), ((TextView) v).getText(), Toast.LENGTH_SHORT).show();


                }
            });

        }

Method to fetch list and send to listview

public List<LeftPlaylist> getAllsongs() {
        List<LeftPlaylist> leftPlaylistList = new ArrayList<LeftPlaylist>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_PLAYLIST;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                LeftPlaylist leftPlaylist = new LeftPlaylist();
                leftPlaylist.setID(Integer.parseInt(cursor.getString(0)));
                leftPlaylist.setName(cursor.getString(1));
                leftPlaylist.setPath(cursor.getString(2));

                String name = cursor.getString(1) +"\n"+ cursor.getString(2);
                ListenPage.ArrayofName.add(name);
                // Adding song to list
                leftPlaylistList.add(leftPlaylist);
            } while (cursor.moveToNext());
        }

Method called to update the listview after modifying it:

public void updateLeftList(){

        leftAdapter.notifyDataSetChanged();

    }

Any help would be greatly appreciated!

Here is my SongAdapter code:

public class SongAdapter extends BaseAdapter {

        private ArrayList<Song> songs;
        private LayoutInflater songInf;

        public SongAdapter(Context c, ArrayList<Song>theSongs){
            songs=theSongs;
            songInf=LayoutInflater.from(c);
        }

        @Override
        public int getCount() {
            return songs.size();
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //map to song layout
            LinearLayout songLay = (LinearLayout)songInf.inflate
                    (R.layout.song, parent, false);
            //get title and artist views
            TextView songView = (TextView)songLay.findViewById(R.id.song_title);
            TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
            //get song using position
            Song currSong = songs.get(position);
            //get title and artist strings
            songView.setText(currSong.getTitle());
            artistView.setText(currSong.getArtist());
            //set position as tag
            songLay.setTag(position);
            return songLay;
        }


    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Alex Collette
  • 1,664
  • 13
  • 26
  • @AlexCollete. Let me see your adapter code. There is nothing wrong with the Db Helper code. But i wanna see how your updating your adapter and your constructors. – CodeDaily Dec 07 '16 at 20:26
  • where are you passing db.getAllsongs() to your adapter.? you just called the function but haven't done anything with List returned by the method. – Nitesh Dec 07 '16 at 20:29
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – dsh Dec 07 '16 at 21:28
  • `leftAdapter` is a local variable in your `createLeftList()` method; it can not be accessed from `updateLeftList()`. The error tells you that `leftAdapter` is `null` when `updateLeftList()` is called. You need to arrange for the variable to have a reference to the list adapter before you can call `updateLeftList()` – dsh Dec 07 '16 at 21:30

1 Answers1

0
  1. Do this in your Activity Class.

    public class MyActivity extends Activity {
    
    private SongListAdapter _songListAdapter;
       @Override
       public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          createLeftList();
       }
    
       private void createLeftList(){
         DatabaseHandler db = new DatabaseHandler(this);
         ListView leftSongView = (ListView) findViewById(R.id.left_playlistView);
         _songListAdapter = new SongListAdapter(this, db.getAllsongs());
          leftSongView.setAdapter(_songListAdapter);
       }
    
      //TODO use this whenever you wanna update your list.
      public void updateSongView(List<String> songsList){
        if(_songListAdapter != null && songsList != null){
            _songListAdapter.updateMusicList(songsList);
        }
      }
    }
    
  2. Then create and Adapter class and follow the pattern.

    public class SongListAdapter extends BaseAdapter{
    private Context _context;
    private List<String> musicList = new ArrayList();
    
    public SongListAdapter(Context context, List<String> musicList){
        _context = context;
        this.musicList.clear();
        this.musicList.addAll(musicList);
    }
    
    public void updateMusicList(List<String> musicList){
        this.musicList.clear();
        this.musicList.addAll(musicList);
        notifyDataSetChanged();
    }
    
    @Override
    public int getCount() {
        return musicList.size();
    }
    
    @Override
    public Object getItem(int position) {
        return musicList.get(position);
    }
    
    @Override
    public long getItemId(int position) {
        return position;
    }
    
    @Override
    public View getView(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;
    }
    
    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    
        //TODO peform any custon action when this is called if needed.
    }
    }
    
CodeDaily
  • 756
  • 4
  • 17
  • I currently have an adapter named SongAdapter here is the code for that: – Alex Collette Dec 08 '16 at 17:21
  • @AlexCollette. if you look at the example code i've written above for you. It looks almost exactly with what you have have in your adapter. So just copy and paste my code above for both activity and adapter and everything should work well. – CodeDaily Dec 08 '16 at 17:47
  • How should i call the updateSongView() method? what should be passed with it? thanks! – Alex Collette Dec 12 '16 at 17:23
  • @AlexCollette In your activity, when ever u get the list of songs from your Db to update the songs list. use updateSongView(List songsList). Pass in a list of Type string. – CodeDaily Dec 12 '16 at 17:58
  • This line is also throwing an error: _listenPageSongAdapter = new ListenPageSongAdapter(this, db.getAllsongs()); error: Error:(121, 80) error: incompatible types: List cannot be converted to List – Alex Collette Dec 13 '16 at 17:21
  • it looks like you changed the object contained in the list view from a String to LeftPlaylist. Just make sure your list contains same objects. for your Case replace List with List. – CodeDaily Dec 13 '16 at 18:51
  • How should i call updateSongView() from another activity? List songsList is all throwing errors: expression expected. Any idea why this is? – Alex Collette Jan 04 '17 at 17:25