0
votes

I have been working on this project to play mp3 files in the recyclerview automatically as we open the app. Now the problem I am facing is an exception.

This is my MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static  final String URL = "http://myurl.com/mylanguage/a_displays.php";

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    private List<Radio> radioList;
     ProgressDialog progressDialog;
    long queueid,queueid1;
    private ApplicationPreferences applicationPreferences;
    DownloadManager dm;
            private MediaPlayer mediaplayer;
    int next = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        applicationPreferences = new ApplicationPreferences(this);

        radioList = new ArrayList<>();

        mediaplayer = new MediaPlayer();

        mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaplayer.start();
            }
        });
        adapter = new RadioAdapter(radioList,this);
        applicationPreferences.getCodeValue();
        final String codeValue = getIntent().getStringExtra("CODEINTENT");
        //Log.d("valueID",codeValue);
        int flag = getIntent().getIntExtra("chckDownload",0);

        if(flag == 1)
        {
            String path = getExternalFilesDir(DIRECTORY_DOWNLOADS)+ "/" +codeValue+ "/uploads/";
            Log.d("Files", "Path: " + path);
            File directory = new File(path);
            final File[] files = directory.listFiles();
           final String [] myAray = new String[files.length];

            Log.d("Files", "Size: "+ files.length);
            myAray[next] = getExternalFilesDir(DIRECTORY_DOWNLOADS) + "/" + codeValue + "/uploads/" + files[next].getName();
            Log.d("Files", "StringArray:" + myAray[next] + "index" + next);
            Log.d("Files", "FileName:" + files[next].getName());
            Radio rad = new Radio(0, files[next].getName());
            radioList.add(rad);
            do {

                try {

                        mediaplayer.setDataSource(this, Uri.parse(myAray[next]));
                    mediaplayer.prepareAsync();
                    mediaplayer.start();
                    Log.d("ValueOfi", String.valueOf(next));

                    mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.start();
                            next++;

                        }
                    });


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }while(next <= files.length);

            }


        else{
            datadummy(codeValue);

        }
        recyclerView.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
                Radio rad = new Radio(0,fileEntry.getName());
                radioList.add(rad);

            }
        }
    }

    private void playmedia(String myAray[], String codeValue){
        try {

                Uri music_play = Uri.parse(getExternalFilesDir(DIRECTORY_DOWNLOADS) + "/" + codeValue + "/uploads/" + myAray[next]);
//                    MediaPlayer mp = MediaPlayer.create(this,music_play);
                mediaplayer.setDataSource(this, music_play);
                mediaplayer.prepareAsync();
                mediaplayer.start();
                next++;
                Log.d("ValueOfi", String.valueOf(next));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void datadummy(final String codeVal) {

        StringRequest stringRequest = new StringRequest(Request.Method.POST,URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response){
                        try {
                            JSONArray array = new JSONArray(response);

                            for (int i = 0; i < array.length(); i++) {
//

                                Log.d("MusicName", String.valueOf(array.getJSONObject(i).getString("audio_sound")));

                                final String music_uri = "http://myurl.in/mylanguage/" + array.getJSONObject(i).getString("audio_sound");

                                Uri uri = Uri.parse(music_uri);
                                applicationPreferences.getCodeValue();
                                dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                DownloadManager.Request request = new DownloadManager.Request(uri);

                                String.valueOf(request.setDestinationInExternalFilesDir(MainActivity.this,
                                        DIRECTORY_DOWNLOADS + "/"+codeVal,
                                        String.valueOf(array.getJSONObject(i).getString("audio_sound"))));
                                queueid = dm.enqueue(request);
                            }

                            BroadcastReceiver receiver = new BroadcastReceiver() {
                                @Override
                                public void onReceive(Context context, Intent intent) {
                                    String action = intent.getAction();
                                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

                                        DownloadManager.Query req_query = new DownloadManager.Query();
                                        req_query.setFilterById(queueid);

                                        Cursor c = dm.query(req_query);

                                        if (c.moveToFirst()) {
                                            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);

                                            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                                                File folder = new File(getExternalFilesDir(DIRECTORY_DOWNLOADS)+ "/" +codeVal+ "/uploads/" );
                                                Log.d("asd", String.valueOf(folder));

                                                listFilesForFolder(folder);
                                                adapter.notifyDataSetChanged();
                                            }

                                        }

                                    }
                                }
                            };
                            registerReceiver(receiver,new IntentFilter((DownloadManager.ACTION_DOWNLOAD_COMPLETE)));




                            Log.d("-response",response);


                        }catch (JSONException e){
                            e.printStackTrace();
                            Log.d("Main", "JsonException: " + e);
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("album_code", codeVal);
                return params;
            }
        };

        RequestQueue requestqueue = Volley.newRequestQueue(this);
        requestqueue.add(stringRequest);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent(MainActivity.this,HomeScreen.class);
                startActivity(intent);
                applicationPreferences.clearPreferences();
                return true;

            case R.id.action_refresh:
                // User chose the "Favorite" action, mark the current item
                // as a favorite...
                return true;

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }

}

This is my logcat:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.teaminertia.user.radioapplication, PID: 9625 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.teaminertia.user.radioapplication/com.teaminertia.user.radioapplication.MainActivity}: java.lang.IllegalStateException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) at android.app.ActivityThread.-wrap14(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6776) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) Caused by: java.lang.IllegalStateException at android.media.MediaPlayer._setDataSource(Native Method) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1323) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1306) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1216) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1129) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1075) at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1052) at com.teaminertia.user.radioapplication.MainActivity.onCreate(MainActivity.java:107) at android.app.Activity.performCreate(Activity.java:6955) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)  at android.app.ActivityThread.-wrap14(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6776)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 

My Objective is to play the mp3 files simultaneously one by one

1
@FaysalAhmed None of those help! It just displays the first item and doesn't play the mp3.shashank verma

1 Answers

0
votes

setDataSource only work if MediaPlayer is in idle state. in your case you getting IllegalStateException because you setting your setDataSource when MediaPlayer is playing or not in idle state

mediaplayer.reset() method Resets the MediaPlayer to its idle state (uninitialized state)

well then you need to initialize it again like this.

    mediaPlayer.setDataSource(your_data_source);
    mediaPlayer.prepare();
    mediaPlayer.start();

so you can simply reset you media player before setting setDataSource

here is the State Diagram of media player