RecyclerView什么都没显示

时间:2017-08-12 19:00:27

标签: android android-recyclerview

我是这个Android世界的新人。我目前正在开发Android项目,即音乐播放器,但由于我的回收站视图没有显示任何应该是歌曲列表的内容,所以我在某一时刻停了下来。 我甚至检查了我的logcat,但无法弄清楚数据是否有约束力。任何一种帮助都会感激不尽。

SongListAdapter.java

public class SongListAdapter extends RecyclerView.Adapter<SongListAdapter.MyViewHolder> {

ArrayList<SongDetailsJDO> mSongDetailsJDOs;
LayoutInflater mLayoutInflater;
Context mContext;
private static final String TAG = "SongListAdapter";
private boolean mIsSongPlaying = false;
private String mCurrentSongId = "-1";

public SongListAdapter(Context context, ArrayList<SongDetailsJDO> pSongDetailsJDOs) {
    mContext = context;
    mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mSongDetailsJDOs = pSongDetailsJDOs;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View lView = mLayoutInflater.inflate(R.layout.recycler_view_item, parent, false);

    return new MyViewHolder(lView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    Uri lUri = null;
    if (mSongDetailsJDOs.get(position).getAlbumId() != null && !mSongDetailsJDOs.get(position).getAlbumId().equals("")) {
        lUri = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), Long.parseLong(mSongDetailsJDOs.get(position).getAlbumId()));
        Picasso.with(mContext).load(lUri).resize(100, 100).placeholder(R.drawable.placeholder).into(holder.albumImageIV);
    } else
        holder.albumImageIV.setImageResource(R.drawable.placeholder);

    String lTrackName = mSongDetailsJDOs.get(position).getTitle();
    if (lTrackName != null)
        holder.trackNameTV.setText(lTrackName.trim());
    else
        holder.trackNameTV.setText("<Unknown>");

    String lAlbumName = mSongDetailsJDOs.get(position).getAlbumName();
    if (lAlbumName != null)
        holder.albumAndArtistDetailsTV.setText(lAlbumName.trim());
    else
        holder.albumAndArtistDetailsTV.setText("<Unknown>");

    if (mSongDetailsJDOs.get(position).getFavouriteStatus() == 1)
        holder.favouriteIV.setImageResource(R.drawable.fav);
    else
        holder.favouriteIV.setImageResource(R.drawable.fav_u);

    // TODO: @holder.animationDrawable use it change Visibility and start (Animation)
    if (mIsSongPlaying && mSongDetailsJDOs.get(position).getSongId().equals(mCurrentSongId)) {
        holder.eqIv.setVisibility(View.VISIBLE);
        holder.animationDrawable = (AnimationDrawable) holder.eqIv.getBackground();
        holder.animationDrawable.start();

    } else {
        holder.eqIv.setVisibility(View.INVISIBLE);
    }
}

@Override
public int getItemCount() {
    if (mSongDetailsJDOs != null)
        return mSongDetailsJDOs.size();
    else
        return 0;
}

/**
 * Called when data is being updated in DB
 */
public void favChanged(int pPosition, int pFavStatus) {
    mSongDetailsJDOs.get(pPosition).setFavouriteStatus(pFavStatus);
    notifyItemChanged(pPosition);
}


/**
 * View Holder class for Rec view
 */
class MyViewHolder extends RecyclerView.ViewHolder {

    ImageView albumImageIV;
    TextView trackNameTV;
    TextView albumAndArtistDetailsTV;
    ImageView favouriteIV;
    ImageView eqIv;
    AnimationDrawable animationDrawable;

    MyViewHolder(View itemView) {
        super(itemView);
        albumImageIV = (ImageView) itemView.findViewById(R.id.album_artwork_iv);
        trackNameTV = (TextView) itemView.findViewById(R.id.title_name_tv);
        albumAndArtistDetailsTV = (TextView) itemView.findViewById(R.id.artist_author_name_tv);
        favouriteIV = (ImageView) itemView.findViewById(R.id.fav_iv);
        eqIv = (ImageView) itemView.findViewById(R.id.eq_iv);
    }
}

/**
 * Swap the data with the new JDO list
 *
 * @param pSongDetailsJDOs
 */
public void swapData(ArrayList<SongDetailsJDO> pSongDetailsJDOs) {
    mSongDetailsJDOs = pSongDetailsJDOs;
    notifyDataSetChanged();
}


/**
 * Returns the list of currently loaded JDO's
 * @return
 */
public List<SongDetailsJDO> getData() {
    return mSongDetailsJDOs;
}

/**
 * Gets the @{@link SongDetailsJDO} object at the specified position
 * @param pPosition
 * @return the {@link SongDetailsJDO} object
 */
public SongDetailsJDO getItemAtPosition(int pPosition) {
    return mSongDetailsJDOs.get(pPosition);
}

/**
 * Update Song Play status
 * @param pStatus the status weather is playing or not
 * @param lSongId the song id the playing song
 */
public void updateSongPlayStatus(boolean pStatus, String lSongId) {
    mIsSongPlaying = pStatus;
    mCurrentSongId = lSongId;
    notifyDataSetChanged();
}


}

SongListActivity.java

 public class SongsListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>, SharedPreferences.OnSharedPreferenceChangeListener {

    private RecyclerView mRecyclerView;
    private SongListAdapter mAdapter;
    private ArrayList<SongDetailsJDO> mSongDetailsJDOs;
    private TextView mNoSongTV;

    private static final int LOADER_ID = 101;
    private int REQUEST_CODE = 102;

    private static final String TAG = "SongsListActivity";
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mPrefEditor;
    private SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener;
    private FirebaseAnalytics mFirebaseAnalytics;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.rec_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(SongsListActivity.this));
        mNoSongTV = (TextView) findViewById(R.id.no_song_tv);
        mSongDetailsJDOs = new ArrayList<>();

        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mPrefEditor = mSharedPreferences.edit();
        mSharedPreferences.registerOnSharedPreferenceChangeListener(this);

        FirebaseApp.initializeApp(this);
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        loadData();

    }



    private void loadData() {
        FirebaseCrash.report(new Exception("OMG An Exception"));
        boolean lIsAppLoadingFirstTime = mSharedPreferences.getBoolean(getString(R.string.is_app_loading_first_time), true);

        if (lIsAppLoadingFirstTime) {

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            } else {
                mPrefEditor.putBoolean(getString(R.string.is_app_loading_first_time), false);
                mPrefEditor.apply();
                new LoadDataToDbBackground().execute();

                // TODO: Create Loader here
            }
        } else {
            loadDataToRecyclerView();

            if (mSharedPreferences.getBoolean(getString(R.string.is_song_playing), false)) {
                // TODO: Create Loader here
                SongDetailsJDO lJDO = getSongJDO(mSharedPreferences.getString(getString(R.string.song_id), ""));
                startActivityForResult(new Intent(SongsListActivity.this, PlayerActivity.class)
                        .putExtra(getString(R.string.song_jdo), lJDO), REQUEST_CODE);
            }

        }

    }


    private class LoadDataToDbBackground extends AsyncTask<Void, Integer, Void> {

        ProgressDialog mProgressDialog;

        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(SongsListActivity.this);
            mProgressDialog.setMessage("Please Wait");
            mProgressDialog.setTitle("Loading");
            mProgressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgressDialog.dismiss();
            super.onPostExecute(aVoid);
        }

        @Override
        protected Void doInBackground(Void... params) {

            CommonHelper lHelper = new CommonHelper();
            lHelper.loadSongToDB(SongsListActivity.this);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadDataToRecyclerView();
                }
            });

            return null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0) {
            boolean lGranted = true;
            for (int lResult : grantResults) {
                if (lResult == PackageManager.PERMISSION_DENIED)
                    lGranted = false;
            }
            if (lGranted)
                loadData();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (data != null && data.getExtras() != null && resultCode == PlayerActivity.RESULT_CODE) {
                //if data changed reload the recyclerView
                if (data.getBooleanExtra(getString(R.string.is_data_changed), false)) {
                    mSongDetailsJDOs = new SongDetailTable(this).getAllSongs();
                    mAdapter.swapData(mSongDetailsJDOs);
                }
            }
        }
//        updateCurrentSongIndication();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater lMenuInflater = getMenuInflater();
        lMenuInflater.inflate(R.menu.menu_song_list, menu);

        SearchManager lSearchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        SearchView lSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        lSearchView.setSearchableInfo(lSearchManager.getSearchableInfo(getComponentName()));
        lSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                filterRecView(newText);
                return true;
            }
        });

        return true;
    }


    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.TITLE + " ASC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

        ArrayList<SongDetailsJDO> lSongDetailsNew = new ArrayList<>();

        if (data.moveToFirst()) {
            do {
                lSongDetailsNew.add(new SongDetailsJDO(data.getString(data.getColumnIndex(MediaStore.Audio.Media.TITLE)),
                        data.getString(data.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
                        data.getString(data.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
                        data.getString(data.getColumnIndex(MediaStore.Audio.Media._ID)),
                        data.getInt(data.getColumnIndex(MediaStore.Audio.Media.DURATION)), 0));
            } while (data.moveToNext());
        }
        compareDataAndMakeChangesToDB(lSongDetailsNew);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        Log.d(TAG, "onWindowFocusChanged: ");
        updateCurrentSongIndication();
    }


    private void updateCurrentSongIndication() {
        if (mSharedPreferences.getBoolean(getString(R.string.is_song_playing), false)) {
            mAdapter.updateSongPlayStatus(true, mSharedPreferences.getString(getString(R.string.song_id), ""));
            mRecyclerView.smoothScrollToPosition(getPositionOfSongId(mSharedPreferences.getString(getString(R.string.song_id), "")));
        } else {
            if(mAdapter!=null)
                mAdapter.updateSongPlayStatus(false, "-1");
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        updateCurrentSongIndication();
    }



    private void compareDataAndMakeChangesToDB(ArrayList<SongDetailsJDO> pSongDetailsNew) {

        Log.d(TAG, "compareDataAndMakeChangesToDB: Called ============");

        ArrayList<String> lSongIdsToBeDeleted = new ArrayList<>();
        for (SongDetailsJDO lSongDetailsJDO : mSongDetailsJDOs) {
            lSongIdsToBeDeleted.add(lSongDetailsJDO.getSongId());
        }
        ArrayList<SongDetailsJDO> lNewSongsToBeAdded = new ArrayList<>();

        for (SongDetailsJDO lSongDetailsJDO : pSongDetailsNew) {
            if (lSongIdsToBeDeleted.contains(lSongDetailsJDO.getSongId())) {
                lSongIdsToBeDeleted.remove(lSongDetailsJDO.getSongId());
            } else
                lNewSongsToBeAdded.add(lSongDetailsJDO);
        }


        if (lSongIdsToBeDeleted.size() > 0 || lNewSongsToBeAdded.size() > 0) {

            SongDetailTable lSongDetailTable = new SongDetailTable(this);
            lSongDetailTable.removeSongsForIds(lSongIdsToBeDeleted);
            lSongDetailTable.insertSongs(lNewSongsToBeAdded);
            loadDataToRecyclerView();

//
//            SongPlayerService lSongPlayerService = SongPlayerService.getRunningInstance();
//            if (lSongPlayerService != null)
//                lSongPlayerService.dataChanged();
        }

    }


    public void onFavClick(View pView) {

        //Firebase Logging
        Bundle lBundle = new Bundle();
        lBundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY,"Favourite Clicked");
        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM,lBundle);

        int lPosition = mRecyclerView.getChildLayoutPosition((View) pView.getParent());

        SongDetailsJDO lSongDetailsJDO = mAdapter.getItemAtPosition(lPosition);
        String lSongId = lSongDetailsJDO.getSongId();
        SongDetailTable lSongDetailTable = new SongDetailTable(this);

        int lNewFavStatus = lSongDetailsJDO.getFavouriteStatus() == 0 ? 1 : 0;
        lSongDetailTable.setFavouriteStatus(lSongId, lNewFavStatus);
        mAdapter.favChanged(lPosition, lNewFavStatus);

        SongPlayerService mSongPlayerService = SongPlayerService.getRunningInstance();
        if (mSongPlayerService != null)
            mSongPlayerService.favChanged(lPosition, lNewFavStatus);
    }


    public void onRowClick(View pView) {

        int lPosition = mRecyclerView.getChildLayoutPosition(pView);
        SongDetailsJDO lJDO = mAdapter.getItemAtPosition(lPosition);

        startActivityForResult(new Intent(SongsListActivity.this, PlayerActivity.class)
                .putExtra(getString(R.string.song_jdo), lJDO), REQUEST_CODE);

        overridePendingTransition(R.anim.from_right, R.anim.scale_down);
    }


    private SongDetailsJDO getSongJDO(String pSongId) {
        SongDetailsJDO lJDO = null;
        for (SongDetailsJDO lSongDetailsJDO : mSongDetailsJDOs) {
            if (lSongDetailsJDO.getSongId().equals(pSongId)) {
                lJDO = lSongDetailsJDO;
                break;
            }
        }
        return lJDO;
    }


    private void filterRecView(String pText) {
        if (pText != null) {
            if (pText.equals("")) {
                mAdapter.swapData(mSongDetailsJDOs);
                toggleVisibilityForNoResult(mSongDetailsJDOs.size(), pText);
            } else {
                ArrayList<SongDetailsJDO> lSongDetailsJDOs = new ArrayList<>();

                pText = pText.toLowerCase();
                for (SongDetailsJDO lDetailsJDO : mSongDetailsJDOs) {
                    if (lDetailsJDO.getTitle().toLowerCase().contains(pText) || lDetailsJDO.getAlbumName() != null && lDetailsJDO.getAlbumName().toLowerCase().contains(pText))
                        lSongDetailsJDOs.add(lDetailsJDO);
                }
                toggleVisibilityForNoResult(lSongDetailsJDOs.size(), pText);
                mAdapter.swapData(lSongDetailsJDOs);
            }
        }

    }


    public void toggleVisibilityForNoResult(int pNumberOfSongs, String query) {

        if (pNumberOfSongs == 0) {
            mNoSongTV.setVisibility(View.VISIBLE);
            mNoSongTV.setText(getString(R.string.nosong) + " " + query);
        } else
            mNoSongTV.setVisibility(View.INVISIBLE);
    }


    public void loadDataToRecyclerView() {
        //Loading data to RecyclerView
        mSongDetailsJDOs = new SongDetailTable(this).getAllSongs();
        mAdapter = new SongListAdapter(SongsListActivity.this, mSongDetailsJDOs);
        mRecyclerView.setAdapter(mAdapter);
    }


    public int getPositionOfSongId(String pSongId) {
        int lPostion = -1;
        for (int i = 0; i < mSongDetailsJDOs.size(); i++) {
            if (mSongDetailsJDOs.get(i).getSongId().equals(pSongId)) {
                lPostion = i;
                break;
            }
        }
        return lPostion;
    }
}

1 个答案:

答案 0 :(得分:0)

查看您的问题,无法确定问题的确切原因。 但我仍然会对问题提出一些暗示。

检查你的代码 mSongDetailsJDOs.size();什么是列表的大小,它应该是&gt; 0.如果没有,请在活动中查看您如何通过列表。

@Override
public int getItemCount() {
    if (mSongDetailsJDOs != null)
        return mSongDetailsJDOs.size();
    else
        return 0;
}

如果以上列表是&gt; 0然后在onBindViewHolder()中检查它是否逐个获取位置并尝试一次渲染一个项目。

如果上述内容适合您,请告诉我。