在onResume()之后不调用Custom ArrayAdapter中的getView()

时间:2015-01-11 15:27:25

标签: android-fragments android-listview android-viewpager android-arrayadapter getview

我对此毫无希望! 我试图找到4天内发生的事情..

基本上我从设备中取出所有歌曲并将它们显示在listView中。

listView位于一个名为MainFragment的简单片段中。

片段位于ViewPager内部,左右滑动选项。

listView和它的适配器在第一次初始运行时工作正常。

但是,在我的应用程序进入后台并且用户将应用程序带回到前面之后,listView没有被加载! 这三行位于我使用listView和ArrayList:

启动适配器的位置
            Log.d("Main Fragment", "Songs List View - " + String.valueOf(songsListView.getCount()));
        Log.d("Main Fragment", "Songs List Adapter - " + String.valueOf(songListAdapter.getCount()));
        Log.d("Main Fragment", "Songs List - " + String.valueOf(Constants.songList.size()));

他们都会在设备中返回正确数量的歌曲!

但在适配器内部,getView()根本没有被调用。 我试图清除适配器'清除listView,清除歌曲列表,清除整个应用程序的整个布局!然后重新加载onResume().. 但似乎没有任何作用:(

MainFragment:

public class MainFragment extends Fragment {

  public static boolean stopSearch = false;

  public static ListView songsListView;
  public ListView playListListView;
  public PlayListListAdapter playeListAdapter;
  public SongListAdapter songListAdapter;

  public RelativeLayout play_list_container;
  public Button cancelPlayList;
  public Button okPlayList;
  public Button chooseAll;

  private View mRootView;@
  Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    mRootView = inflater.inflate(R.layout.all_songs_layout, container,
      false);

    Log.w("Main Fragment", "Has been created");
    return mRootView;
  }

  @
  Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  public void initLists() {
    try {
      if (songsListView == null) {
        Log.d("Main Fragment", "initListView");
        songsListView = (ListView) mRootView.findViewById(R.id.songsListView);
      }

      if (playListListView == null) {
        playListListView = (ListView) mRootView.findViewById(R.id.playListListView);
        play_list_container = (RelativeLayout) mRootView.findViewById(R.id.play_list_container);
      }

    } catch (NullPointerException e) {
      Log.d("Main Fragment", "initLists " + e.toString());
    }
  }

  public void onResume() {
    try {
      initLists();
    } catch (NullPointerException e) {
      songsListView = (ListView) mRootView.findViewById(R.id.songsListView);
      playListListView = (ListView) mRootView.findViewById(R.id.playListListView);
      play_list_container = (RelativeLayout) mRootView.findViewById(R.id.play_list_container);
    }
    //		
    Log.d("Main Fragment", "startSongsScan");
    SongsHelper.getInstance().startSongsScan();

    setOnClicks();
    super.onResume();
  }

  private void setOnClicks() {
    songsListView.setOnItemClickListener(new OnItemClickListener() {@
      Override
      public void onItemClick(AdapterView <? > parent, View arg1, int position, long var4) {
        ((Main) getActivity()).performListViewClick(position);
      }
    });
    songsListView.setOnItemLongClickListener(new OnItemLongClickListener() {@
      Override
      public boolean onItemLongClick(AdapterView <? > parent, View arg1, int position, long var4) {
        final Song song = (Song) parent.getItemAtPosition(position);
        song.setCanDelete(true);
        songListAdapter.notifyDataSetChanged();
        return true;
      }
    });
    chooseAll = (Button) mRootView.findViewById(R.id.chooseAll);
    chooseAll.setOnClickListener(new OnClickListener() {@
      Override
      public void onClick(View v) {
        ((Main) getActivity()).initPlayListAllSongsSelected();
      }
    });
    okPlayList = (Button) mRootView.findViewById(R.id.okPlayList);
    okPlayList.setOnClickListener(new OnClickListener() {@
      Override
      public void onClick(View v) {
        ((Main) getActivity()).mPlayerUiHelper.savePlayList();
        play_list_container.setVisibility(View.GONE);
        songsListView.setVisibility(View.VISIBLE);
      }
    });
    cancelPlayList = (Button) mRootView.findViewById(R.id.cancelPlayList);
    cancelPlayList.setOnClickListener(new OnClickListener() {@
      Override
      public void onClick(View v) {
        ((Main) getActivity()).mPlayerUiHelper.cancelPlayList();
        play_list_container.setVisibility(View.GONE);
        songsListView.setVisibility(View.VISIBLE);
      }
    });
  }

  public void setListAdapter() {

    if (songListAdapter == null) {
      songListAdapter = new SongListAdapter(getActivity(), R.layout.song_row, Constants.songList);
      songsListView.setAdapter(songListAdapter);
    } else {
      songListAdapter.notifyDataSetChanged();
    }

    if (songsListView == null || songsListView.getVisibility() == View.GONE) {
      Log.d("Main Fragment", "Restart Views");
    } else {
      //Songs UI Helper
      Log.d("Main Fragment", "Songs List View - " + String.valueOf(songsListView.getCount()));
      Log.d("Main Fragment", "Songs List Adapter - " + String.valueOf(songListAdapter.getCount()));
      Log.d("Main Fragment", "Songs List - " + String.valueOf(Constants.songList.size()));
    }
  }

}

SongListAdapter

public class SongListAdapter extends ArrayAdapter < Song > {

  Context mContext;
  int mResource;
  List < Song > mSongs;
  private ViewHolder holder;

  public SongListAdapter(Context context, int resource, List < Song > objects) {
    super(context, resource, objects);
    this.mContext = context;
    this.mResource = resource;
    this.mSongs = objects;

    try {
      Comparator cp = Song.getComparator(Song.SortParameter.TITLE_ASCENDING);
      Collections.sort(mSongs, cp);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Log.d("Songs Adapter", "started");
    Log.d("Songs Adapter", "Songs Count When Started - " + mSongs.size());
  }

  @
  Override
  public View getView(int position, View convertView, ViewGroup parent) {
    final Song song = getItem(position);

    Log.d("Songs Adapter", "getView");
    Log.d("Songs Adapter", "Songs Count - " + mSongs.size());
    Log.d("Songs Adapter", "Song - " + song.getTitle());

    if (convertView == null) {
      //create new view
      convertView = LayoutInflater.from(getContext()).inflate(mResource, parent, false);
      holder = new ViewHolder();
      holder.songText = (ZenTextView) convertView.findViewById(R.id.songTitle);
      holder.songArtist = (ZenTextView) convertView.findViewById(R.id.songArtist);
      holder.songPhoto = (ImageView) convertView.findViewById(R.id.songIcon);
      convertView.setTag(holder);

    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    //Set Artist Name
    if (song.getArtist() != null && !song.getArtist().startsWith("<unknown>")) {
      holder.songText.setText(song.getTitle());
      holder.songArtist.setText(song.getArtist());
    } else {
      holder.songText.setText(song.getTitle());
      holder.songArtist.setText(song.getArtist());
    }

    //Set Song image
    setAlbumArt(song);

    //Set item selected
    holder.song_rl = (RelativeLayout) convertView.findViewById(R.id.song_rl);
    if (song.isSelected() == true) {
      holder.song_rl.setBackgroundResource(R.drawable.row_trans_back_selected);
    } else {
      holder.song_rl.setBackgroundResource(R.drawable.row_trans_back);
    }

    //Spinning record animation
    if (song.isAnimationActive()) {
      holder.songPhoto.startAnimation(
        AnimationUtils.loadAnimation(getContext(), R.anim.rotate));
    } else {
      holder.songPhoto.clearAnimation();
    }


    //Set item for deletion
    holder.deleteSong = (ImageView) convertView.findViewById(R.id.deleteFromList);
    if (song.isCanDelete() == true) {
      final int positionSelected = position;
      holder.deleteSong.setVisibility(View.VISIBLE);
      holder.deleteSong.setOnClickListener(new OnClickListener() {

        @
        Override
        public void onClick(View v) {
          Main.mPlayerUiHelper.showSpecialToast(mSongs.get(positionSelected).getTitle() + " Has Been Deleted..");
          mSongs.remove(positionSelected);
          notifyDataSetChanged();
          notifyDataSetInvalidated();
        }
      });
    } else
      holder.deleteSong.setVisibility(View.GONE);

    return convertView;
  }

  static class ViewHolder {
    RelativeLayout song_rl;
    ZenTextView songText;
    ZenTextView songArtist;
    ImageView songPhoto;
    ImageView deleteSong;
  }

  private void setAlbumArt(Song song) {
    if (song.getAlbumID() > 0) {
      Uri artUri = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), song.getAlbumID());
      try {
        Picasso.with(mContext)
          .load(artUri)
          .error(R.drawable.list_image)
          .into(holder.songPhoto);
      } catch (IllegalArgumentException e) {
        Picasso.with(mContext)
          .load(R.drawable.list_image)
          .into(holder.songPhoto);
      }
    }
  }

  @
  Override
  public int getCount() {
    Log.d("Songs Adapter", "getCount() - " + mSongs.size());
    return mSongs.size();
  }
}

主要活动:

	@
	Override
	 protected void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.main);
	  mainLayout = (RelativeLayout) findViewById(R.id.main_layout);

	  //For Phone Listening
	  Constants.mContext = this;
	}

	@
	Override
	 protected void onResume() {

	  if (Constants.songList == null) {
	    Log.d("PlayerUiHelper", "songList was null..");
	    Constants.songList = new ArrayList < Song > ();
	    Constants.songListSearch = new ArrayList < Song > ();
	    Constants.songListShuffle = new ArrayList < Song > ();
	  }

	  Constants.activityOff = false;
	  initStartPlayer();
	  super.onResume();
	}

	public void initUIfromService() {
	  introPrefs = PreferenceManager.getDefaultSharedPreferences(Constants.mContext);

	  setViews();
	  initMediaControllersOnClicks();
	  initTabViews();
	  initMoreButton();

	  mPlayerUiHelper.setHeaderOnClicks();

	  //Start Service
	  Intent songIntent = new Intent(Main.this, SongsHelper.class);
	  startService(songIntent);
	}

	private void initStartPlayer() {
	  Constants.activityOff = false;
	  //Broadcast from service
	  LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(Constants.mContext);
	  IntentFilter intentFilter = new IntentFilter();
	  intentFilter.addAction(Constants.serviceBroadcastIntent);
	  bManager.registerReceiver(mServiceBroadcast, intentFilter);

	  //Start Songs Helper Service
	  Constants.mBackUpContentResolver = getContentResolver();

	  setEnglishLang();

	  mAnalytics = new AnalyticsHelper((AppumApplication) getApplication(),
	    getString(R.string.app_analytics_id), getString(R.string.app_name));
	  //Songs UI Helper
	  mPlayerUiHelper = PlayerUiHelper.getInstance();

	  tinydb = new TinyDB(Constants.mContext);
	  tinydb.putBoolean("restart_service", false);
	  utils = new Utilities();

	  initUIfromService();
	  Log.d(TAG, "Main Created");
	}

	public void setViews() {

	  Log.i(TAG, "Load Fragment Adapter");

	  if (fragMngr == null)
	    fragMngr = getSupportFragmentManager();

	  if (mPager != null) {
	    mPager.removeAllViews();
	  }

	  mPager = (ViewPager) findViewById(R.id.pager);
	  mPager.setOffscreenPageLimit(Constants.NUM_PAGES);
	  mPagerAdapter = new ScreenSlidePagerAdapter(fragMngr);
	  mPager.setAdapter(mPagerAdapter);
	  mPager.setOnPageChangeListener(new CustomCircularViewPagerHandler());

	  footer = (LinearLayout) findViewById(R.id.player_footer_bg);

	  //Play lists spinner
	  playListListView = (ListView) findViewById(R.id.playListListView);
	  listButton = (ImageView) findViewById(R.id.listButton);
	  initPlayLists();

	  albumCover = (ImageView) findViewById(R.id.albumCover);
	  songLabel = (ZenTextView) findViewById(R.id.songName);
	  albumName = (ZenTextView) findViewById(R.id.album_name);

	  songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
	  songCurrentDurationLabel = (ZenTextView) findViewById(R.id.songCurrentDurationLabel);
	  songTotalDurationLabel = (ZenTextView) findViewById(R.id.songTotalDurationLabel);
	  bypass = (ImageButton) findViewById(R.id.bypass);

	  // All player buttons
	  btnPlay = (ImageButton) findViewById(R.id.btnPlay);
	  btnNext = (ImageButton) findViewById(R.id.btnNext);
	  btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
	  btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
	  btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);

	  prevButton = (ImageView) findViewById(R.id.prevButton);
	  prevButton.setOnClickListener(new View.OnClickListener() {

	    @
	    Override
	    public void onClick(View arg0) {
	      mPager.setCurrentItem(2);
	    }
	  });
	  nextButton = (ImageView) findViewById(R.id.nextButton);
	  nextButton.setOnClickListener(new View.OnClickListener() {

	    @
	    Override
	    public void onClick(View arg0) {
	      mPager.setCurrentItem(3);
	    }
	  });
	}

此代码 - ** SongsHelper.getInstance()。startSongsScan();正在扫描AsyncTask中的歌曲,它在onPoastExcecute()之后加载ListView

拜托,拜托!帮我休息一下:)

3 个答案:

答案 0 :(得分:0)

在initLists()方法中调用setListAdapter();

答案 1 :(得分:0)

你应该在主onResume()上创建和设置适配器和列表,并在完成AsyncTask并填充列表后,在适配器上调用notifyDataSetChanged。

答案 2 :(得分:0)

谢谢大家的回答和帮助!

我终于找到了解决方案。

完全清除每个片段使用的适配器:

        try {
        mainFragment.songListAdapter.clear();
        mainFragment.songListAdapter = null;
    } catch (NullPointerException e1) {
    }
    try {
        albumSongListAdapter.clear();
        albumSongListAdapter = null;
    } catch (NullPointerException e1) {
    }
    try {
        artistSongListAdapter.clear();
        artistSongListAdapter = null;
    } catch (NullPointerException e1) {
    }
    try {
        albumGridAdapter.clear();
        albumGridAdapter = null;
    } catch (NullPointerException e1) {
    }
    try {
        artistGridAdapter.clear();
        artistGridAdapter = null;
    } catch (NullPointerException e1) {
    }

而不是改变这个:

if (songsListView == null) {
    Log.d("Main Fragment", "initListView");
    songsListView = (ListView) mRootView.findViewById(R.id.songsListView);
  }

  if (playListListView == null) {
    playListListView = (ListView) mRootView.findViewById(R.id.playListListView);
    play_list_container = (RelativeLayout) mRootView.findViewById(R.id.play_list_container);
  }

到此:

        songsListView = (ListView) mRootView.findViewById(R.id.songsListView);            
        playListListView = (ListView) mRootView.findViewById(R.id.playListListView);
        play_list_container = (RelativeLayout) mRootView.findViewById(R.id.play_list_container);

显然,在ViewPager中的片段内使用listVies时,这是一个已知的错误。