1

Im trying to make mp3 player in android studio, i have loaded all songs from my phone in arraylist called audioList but i cant make recyclerView, can anyone find mistake?

MainActivity.java

import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;    
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private MediaPlayerService player;
    private boolean serviceBound = false;
    private ArrayList<Audio> audioList;
    private RWAdapter adapt;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        }

        RecyclerView rv = (RecyclerView) findViewById(R.id.myRecyclerView);
        assert rv != null;
        rv.setLayoutManager(new LinearLayoutManager(this));;

        loadAudio();
        RWAdapter rwa = new RWAdapter(audioList);
        rv.setAdapter(rwa);

        playAudio(audioList.get(22).getData());

    }

    //ulozi sa instancia
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("ServiceState", serviceBound);
        super.onSaveInstanceState(outState);
    }

    //obnovi sa instancia tam kde bola naposledy ulozena
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        serviceBound = savedInstanceState.getBoolean("ServiceState");
    }

    //znici instanciu
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(serviceBound){
            unbindService(serviceConnection);
            player.stopSelf();
        }
    }

    //viaze tuto triedu s prehravacom, nastavi hodnotu serviceBound na true ked sa vytvori spojenie
    private ServiceConnection serviceConnection = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
            player = binder.getService();
            serviceBound = true;

            Toast.makeText(MainActivity.this, "Service bound", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceBound = false;
        }
    };

    //Metoda dava spravu,intnet druhej aktivite o spusteni hudby
    private void playAudio(String media){
        if(!serviceBound){
            Intent playerIntent = new Intent(this,MediaPlayerService.class);
            playerIntent.putExtra("media",media);
            startService(playerIntent);
            bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);

        } else {    
        }
    }


    //nacita pesnicky z mobilu
    private void loadAudio() {
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);

        if(cursor != null && cursor.getCount() > 0) {
            audioList = new ArrayList<>();
            while (cursor.moveToNext()){
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                audioList.add(new Audio(data, title, album, artist));
            }
        }
        cursor.close();
    }            
}

RecyclerViewAdapter

package com.example.rsabo.mp3player;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;    
import java.util.Collections;
import java.util.List;

/**
 * Created by RSabo on 15-Apr-17.
 */

public class RWAdapter extends RecyclerView.Adapter<RWAdapter.MyViewHolder>{
    private List<Audio> list;
    private Context context;

        public class MyViewHolder extends RecyclerView.ViewHolder {

            TextView title;
            ImageView play_pause;

            MyViewHolder(View itemView) {
                super(itemView);
                title = (TextView) itemView.findViewById(R.id.title);
                play_pause = (ImageView) itemView.findViewById(R.id.play_pause);

                itemView.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        Audio currentAudio = list.get(getAdapterPosition());    
                    }
                });
            }
        }

    public RWAdapter(List<Audio> list) {
        this.list = list;
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //Inflate the layout, initialize the View Holder
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_songov, parent, false);
        return new MyViewHolder(v);   
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        //Use the provided View Holder on the onCreateViewHolder method to populate the current row on the RecyclerView
        holder.title.setText(list.get(position).getTitle());
    }

    @Override
    public int getItemCount() {
        //returns the number of elements the RecyclerView will display
        return list.size();
    }    
}

activity_main.xml

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.rsabo.mp3player.MainActivity">

<include layout="@layout/list_songov" />

list_songov.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/myRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

Sanjog Shrestha
  • 417
  • 9
  • 16
Rado Sabo
  • 33
  • 10
  • What problem you are facing ? Please explain . – Shishupal Shakya Apr 15 '17 at 12:43
  • the main problem is that im getting these errors java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.rsabo.mp3player.RWAdapter.onBindViewHolder(RWAdapter.java:59) at com.example.rsabo.mp3player.RWAdapter.onBindViewHolder(RWAdapter.java:19) – Rado Sabo Apr 15 '17 at 13:07

3 Answers3

1

You are not calling the function loadAudio() , you should call this function when instatiating your adapter class

Ramees Thattarath
  • 1,093
  • 11
  • 19
1

Basically your loadAudio() method should be AsyncTask (Background process) you have to wait while it load, so use AsyncTask and set adapter in onPostExecute method see example AsyncTask Android example or this https://developer.android.com/reference/android/os/AsyncTask.html

 //nacita pesnicky z mobilu
 private void loadAudio() {
    ContentResolver contentResolver = getContentResolver();
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
    String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
    Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);

    if(cursor != null && cursor.getCount() > 0) {
        audioList = new ArrayList<>();
        while (cursor.moveToNext()){
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            audioList.add(new Audio(data, title, album, artist));
        }
    }
    cursor.close();
}      
Community
  • 1
  • 1
Rajesh
  • 2,618
  • 19
  • 25
  • i tried to sleep the thread after loading for 5 seconds and it isnt helping, i think that the problem is somewhere else – Rado Sabo Apr 15 '17 at 13:10
1

Check following code in your adapter .

@Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //Inflate the layout, initialize the View Holder
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_songov, parent, false);
        return new MyViewHolder(v);   
    }

Now , inside list_songov.xml layout file , there is no TextView , ImageView for Title and play_pause .

Please check if you have set the correct layout inside onCreateViewHolder() .

Shishupal Shakya
  • 1,632
  • 2
  • 18
  • 41