专辑封面未显示

时间:2018-01-11 11:35:03

标签: android android-fragments android-mediaplayer

我刚接触到android。在我的音乐应用程序中,我试图显示专辑封面,但它没有显示它。我不知道这是什么问题。请告诉我如何做到这一点。无法在互联网上找到。

public class BlankFragment2 extends Fragment {
    private ArrayList<songInfo> _songs = new ArrayList<songInfo>();
    RecyclerView recyclerView;
    SeekBar seekBar;
    public songAdapter songAdapter1;
    ImageView album_art;
    MediaPlayer mediaPlayer;
    private Handler myHandler = new Handler();
    byte[] art;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private BlankFragment.OnFragmentInteractionListener mListener;

    public BlankFragment2() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView= inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
        recyclerView = (RecyclerView)rootView. findViewById(R.id.recyclerView);
        seekBar = (SeekBar) rootView.findViewById(R.id.seekBar);
        songAdapter1 = new songAdapter(getActivity(),_songs);
        recyclerView.setAdapter(songAdapter1);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                linearLayoutManager.getOrientation());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(dividerItemDecoration);
        songAdapter1.setOnItemClickListener(new songAdapter.OnItemClickListener() {
            public void onItemClick(RecyclerView.ViewHolder holder, View view, final songInfo obj, int position) {

                if(mediaPlayer.isPlaying()){
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.release();
                    mediaPlayer = null;

                }else {

                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(obj.getSongUrl());
                                mediaPlayer.prepareAsync();
                                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                    @Override
                                    public void onPrepared(MediaPlayer mp) {
                                        mp.start();
                                        seekBar.setProgress(0);
                                        seekBar.setMax(mediaPlayer.getDuration());
                                        Log.d("Prog", "run: " + mediaPlayer.getDuration());
                                    }
                                });

                            }catch (Exception e){}
                        }

                    };
                    myHandler.postDelayed(runnable,100);

                }
            }
        });
        checkUserPermission();

        Thread t = new runThread();
        t.start();
        return rootView;
    }

    public class runThread extends Thread {


        @Override
        public void run() {
            while (true) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("Runwa", "run: " + 1);
                if (mediaPlayer != null) {
                    seekBar.post(new Runnable() {
                        @Override
                        public void run() {
                            seekBar.setProgress(mediaPlayer.getCurrentPosition());
                        }
                    });

                    Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
                }
            }
        }

    }

    private void checkUserPermission(){
        if(Build.VERSION.SDK_INT>=23){
            if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},123);
                return;
            }
        }
        loadSongs();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 123:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    loadSongs();
                }else{
                    Toast.makeText(getContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
                    checkUserPermission();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        }

    }

    private void loadSongs() {
        MediaMetadataRetriever metaRetriver = new MediaMetadataRetriever();

        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
        Cursor cursor = getContext().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {

                    String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                    String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                    String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));



                    try {
                        String pathId = cursor.getString(Integer.parseInt(url));
                        metaRetriver.setDataSource(pathId);
                        Log.d(this.getClass().getName(), "path id=" + pathId);
                        art = metaRetriver.getEmbeddedPicture();
                        BitmapFactory.Options opt = new BitmapFactory.Options();
                        opt.inSampleSize = 2;
                        Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length, opt);
                        album_art.setImageBitmap(songImage);
                    } catch (Exception e) {
                       // album_art.setBackgroundColor(Color.GRAY);
                        songInfo s = new songInfo(name, artist, url);
                        _songs.add(s);

                    }
                }
                while (cursor.moveToNext());
                cursor.close();
                songAdapter1 = new songAdapter(getActivity(), _songs);
            }
        }

    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (BlankFragment.OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}
adapter
public  class songAdapter extends RecyclerView.Adapter<songAdapter.SongHolder> {

    private ArrayList<songInfo> _songs = new ArrayList<>();
    private Context context;

    private OnItemClickListener mOnItemClickListener;

    public songAdapter(Context context, ArrayList<songInfo> songs) {
        this.context = context;
        this._songs = songs;
    }


    public interface OnItemClickListener {
        void onItemClick(RecyclerView.ViewHolder holder, View view, songInfo obj, int position);

        // void onItemClick(Button b, View view, songInfo obj, int position);
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mOnItemClickListener = mItemClickListener;
    }


    @Override
    public SongHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View myView = LayoutInflater.from(context).inflate(R.layout.card,viewGroup,false);
        return new SongHolder(myView);
    }

    @Override
    public void onBindViewHolder(final SongHolder songHolder, final int i) {

        final songInfo s = _songs.get(i);
        songHolder.tvSongName.setText(_songs.get(i).getSongName());
        songHolder.tvSongArtist.setText(_songs.get(i).getArtistName());
        setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder holder, View view, songInfo obj, int position) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(songHolder, view, s, i);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return _songs.size();
    }

    public class SongHolder extends RecyclerView.ViewHolder {
        TextView tvSongName,tvSongArtist;
        ImageView album_art;
        public SongHolder(View itemView) {
            super(itemView);
            tvSongName = (TextView) itemView.findViewById(R.id.songName);
            tvSongArtist = (TextView) itemView.findViewById(R.id.artistName);
            album_art = (ImageView) itemView.findViewById(R.id.albumArt);
        }
    }
}

这是我的日志。

  

没有连接适配器;跳过布局01-11 00:30:16.000   8631-8665 / com.example.murarilal.atry D / Runwa:运行:1 01-11   00:30:16.002 8631-8631 / com.example.murarilal.atry I / Choreographer:   跳过63帧!应用程序可能在其上做了太多工作   主线程。 01-11 00:30:16.030 8631-8664 / com.example.murarilal.atry   D / EGL_emulation:eglMakeCurrent

1 个答案:

答案 0 :(得分:0)

在您加载未绑定到recyclerView

的歌曲后,您正在创建适配器的新实例

所以不要创建新实例

songAdapter1 = new songAdapter(getActivity(), _songs);

调用适配器的notifyDataSetChanged()方法,如下所示:

songAdapter1.notifyDataSetChanged()

或者您只需删除songAdapter1字段即可通过调用

完成工作
recyclerView.getAdapter().notifyDataSetChanged()