【问题标题】:Updating listView without duplication更新 listView 不重复
【发布时间】:2017-04-22 22:35:37
【问题描述】:

我正在编写一个带有播放列表的音乐播放器应用程序,并且我正在尝试显示已选择的歌曲。所有代码都可以正常工作,但是当添加歌曲时,listView 不会更新。我已经在网上广泛搜索,但无法弄清楚如何解决它。我最终尝试调用leftAdapter.notifyDataSetChanged(); 来更新列表,但它抛出了错误:

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

我也尝试过调用初始化方法 (createLeftList()),但它复制了列表中的所有项目。

调用初始化列表视图的方法:

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();


                }
            });

        }

获取列表并发送到列表视图的方法

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());
        }

修改后调用的方法更新列表视图:

public void updateLeftList(){

        leftAdapter.notifyDataSetChanged();

    }

任何帮助将不胜感激!

这是我的 SongAdapter 代码:

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;
        }


    }

【问题讨论】:

  • @AlexCollete。让我看看你的适配器代码。 Db Helper 代码没有任何问题。但我想看看你如何更新你的适配器和你的构造函数。
  • 你在哪里将 db.getAllsongs() 传递给你的适配器。?您刚刚调用了该函数,但没有对该方法返回的 List 执行任何操作。
  • leftAdapter 是您的 createLeftList() 方法中的局部变量;无法从updateLeftList() 访问它。当调用updateLeftList() 时,错误告诉您leftAdapternull。您需要安排变量引用列表适配器,然后才能调用updateLeftList()

标签: java android listview android-arrayadapter


【解决方案1】:
  1. 在您的 Activity 类中执行此操作。

    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. 然后创建适配器类并遵循模式。

    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.
    }
    }
    

【讨论】:

  • 我目前有一个名为 SongAdapter 的适配器,代码如下:
  • @AlexCollette。如果您查看我上面为您编写的示例代码。它看起来几乎与您在适配器中所拥有的完全一样。因此,只需复制并粘贴我上面的活动和适配器代码,一切都会正常运行。
  • 我应该如何调用 updateSongView() 方法?应该通过什么?谢谢!
  • @AlexCollette 在您的活动中,当您从数据库中获取歌曲列表以更新歌曲列表时。使用 updateSongView(List songList)。传入类型字符串列表。
  • 这一行也报错:_listenPageSongAdapter = new ListenPageSongAdapter(this, db.getAllsongs());错误:错误:(121, 80) 错误:不兼容的类型:List 无法转换为 List
猜你喜欢
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 2015-07-08
相关资源
最近更新 更多