0

I am making a music player application.

its giving NullPointerException in a class.This is the code of player.java

package com.example.mudit.take6;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
  import android.support.v7.app.AppCompatActivity;
  import android.support.v7.widget.Toolbar;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
  import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
   import android.widget.Toast;

    import java.io.File;
   import java.util.ArrayList;


 public class MainActivity extends AppCompatActivity {
     ListView lv;
    String[] items;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    lv = (ListView) findViewById(R.id.lvplaylist);

    final ArrayList<File> mySongs = findsongs(Environment.getExternalStorageDirectory());

    items = new String[mySongs.size()];

    for (int i = 0; i < mySongs.size(); i++) {
        //toast(mySongs.get(i).getName().toString());
        items[i] = mySongs.get(i).getName().toString().replace(".mp3", "").replace("", "");
    }

    ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), R.layout.song_layout, R.id.textView, items);
    lv.setAdapter(adp);


    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                  @Override
                                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                      startActivity(new Intent(getApplicationContext(), Player.class).putExtra("pos", position).putExtra("SongList", mySongs));
                                  }
                              }
    );

}

public ArrayList<File> findsongs(File root) {
    ArrayList<File> al = new ArrayList<File>();
    File[] files = root.listFiles();
    for (File SingleFiles : files) {
        if (SingleFiles.isDirectory() && !SingleFiles.isHidden()) {
            al.addAll(findsongs(SingleFiles));
        } else {
            if (SingleFiles.getName().endsWith(".mp3")) {
                al.add(SingleFiles);

            }
        }
    }
    return al;
}

public void toast(String text) {
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();

}

@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

errors:-

04-16 01:00:56.575 17684-17684/? I/art: Late-enabling -Xcheck:jni
04-16 01:00:56.640 17684-17684/com.example.mudit.take6 W/System:         ClassLoader referenced unknown path: /data/app/com.example.mudit.take6-  1/lib/arm
04-16 01:00:56.822 17684-17684/com.example.mudit.take6 D/AndroidRuntime: Shutting down VM
04-16 01:00:56.825 17684-17684/com.example.mudit.take6 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.example.mudit.take6, PID: 17684
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mudit.take6/com.example.mudit.take6.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
                                                                         at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                      Caused by: java.lang.NullPointerException: Attempt to get length of null array
                                                                         at com.example.mudit.take6.MainActivity.findsongs(MainActivity.java:59)
                                                                         at com.example.mudit.take6.MainActivity.onCreate(MainActivity.java:33)
                                                                         at android.app.Activity.performCreate(Activity.java:6259)
                                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
                                                                         at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                         at android.os.Looper.loop(Looper.java:148) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5443) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 

How can i run it successfully. please tell if i am doing it wrong way . if you can tell in right way . Any help will be appreciated.

Mudit
  • 199
  • 2
  • 21
  • The problem is with your array. A quick way to debug this, is to add some logging after: final ArrayList mySongs = findsongs(Environment.getExternalStorageDirectory()); and items = new String[mySongs.size()]; and check their size, etc. – Levon Apr 15 '16 at 20:03

3 Answers3

0

You need to include permission in your Manifest file as you are trying to access external storage. Since you are only reading SD card, so you can include read permission only -

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

And if anywhere you are trying to modify the SD card contents you should include -

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Shadab Ansari
  • 7,022
  • 2
  • 27
  • 45
0

The exception is being thrown on line no 59, which is for (File SingleFiles : files), here files array is null, which is causing the NullPointerException.

change your code to validate whether files array is null.

public ArrayList<File> findsongs(File root) {
    ArrayList<File> al = new ArrayList<File>();
    File[] files = root.listFiles();
    if(files != null){
    for (File SingleFiles : files) {
        if (SingleFiles.isDirectory() && !SingleFiles.isHidden()) {
            al.addAll(findsongs(SingleFiles));
        } else {
            if (SingleFiles.getName().endsWith(".mp3")) {
               al.add(SingleFiles);

         }
     }
   }
}
return al;

}

Sandeep Sukhija
  • 1,156
  • 16
  • 30
0

It looks like your array list "mySongs" is null. Check it by adding something like this into your code:

if(mySongs != null && mySongs.length > 0) {
   ...
}
Edward
  • 2,291
  • 2
  • 19
  • 33