-6

Note:- Please stop Down Voting my question, I am not a android developer.

I am not in android programming and unable to find the error, i have purchased the source code of one app from which you can download the .mp3 songs. I have changed the package name as per developer instruction but after that i am getting this error "java.lang.NullPointerException: Attempt to get length of null array". But if run the old application with old package name it is working fine, i contacted the seller but he didn't reply so i decided to post my question here. Kindly help me on this error. Below is the code where logcat is showing the error and also screenshot attached for review.

enter image description here

    package com.mp3songsdownloader.searchonline;

    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Environment;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.RelativeLayout;
    import android.widget.Toast;
    import java.io.File;
    import java.util.ArrayList;


    public class DownloadFragment extends Fragment implements  constants {
    View view;
    ListView lv;
    String[] items;
    RelativeLayout NoShow;
    ArrayAdapter<String> adp;
    ArrayList<File> mySongs;
    public DownloadFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        if (visible) {
            mySongs = findSongs(new File(Environment.getExternalStorageDirectory()+DOWNLOAD_DIRECTORY));

            setVal();
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_two, container, false);
        lv=(ListView)view.findViewById(R.id.lvVideo);
        NoShow=(RelativeLayout)view.findViewById(R.id.NothingToShow);
        File dir  =  new File(Environment.getExternalStorageDirectory()+DOWNLOAD_DIRECTORY);


        if (!dir.exists() && !dir.isDirectory()) {
                    dir.mkdir();
        }
        mySongs = findSongs(dir);

        setVal();

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
                final CharSequence[] items = {"Play", "Delete"};

                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Options");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {


                        if (items[item].equals("Delete")) {
                            removeItemFromList(position);
                        } else if (items[item].equals("Play")) {


                            Intent intent1 = new Intent(getActivity(), PlayerActivity.class);
                            Bundle extras = new Bundle();
                            //intent.putExtra(ID, m.getID());

                            //extras.putString("TITLE", mySongs.get(position).getName().toString());
                            extras.putString("TITLE", mySongs.get(position).getName());
                            extras.putString("ARTWORK", "nothing");
                            extras.putString("STREAM", mySongs.get(position).getAbsolutePath());
                            intent1.putExtras(extras);

                            startActivity(intent1);
                        }

                    }
                });
                AlertDialog alert = builder.create();
                alert.show();

            }
        });
        return  view;
    }

    public void setVal(){
        items = new String[mySongs.size()];

        if(mySongs.size()>0){
            NoShow.setVisibility(NoShow.INVISIBLE);
            lv.setVisibility(lv.VISIBLE);
        }
        for(int i=0; i<mySongs.size(); i++){
            //toast(mySongs.get(i).toString());
        //    items[i]=mySongs.get(i).getName().toString().replace(".mp3","");
            items[i]=mySongs.get(i).getName().replace(".mp3","");

        }
        adp= new ArrayAdapter<String>(getActivity(),R.layout.song_down_layout,R.id.title,items);
        lv.setAdapter(adp);
    }

    protected void removeItemFromList(int position) {
        final int deletePosition = position;

        AlertDialog.Builder alert = new AlertDialog.Builder(
                getActivity());

        alert.setTitle("Delete");
        alert.setMessage("Do you want delete this item?");
        alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                File  f = new File(mySongs.get(deletePosition).getAbsolutePath());
                f.delete();
              mySongs.remove(deletePosition);
                setVal();
                adp.notifyDataSetChanged();
                adp.notifyDataSetInvalidated();
                Toast.makeText(getActivity(), "Song Deleted!", Toast.LENGTH_SHORT).show();

            }
        });
        alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });

        alert.show();

    }
    public ArrayList<File> findSongs(File root){
        ArrayList<File> inFiles = new ArrayList<File>();
        File[] files = root.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                inFiles.addAll(findSongs(file));
            } else {
                if(file.getName().endsWith(".mp3")){
                    inFiles.add(file);
                }
            }
        }
        return inFiles;

    }

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

    }


}

Android Manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mp3songsdownloader.searchonline" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/MyMaterialTheme"
        android:name="com.mp3songsdownloader.searchonline.App" >
        <!--This meta-data tag is required to use Google Play Services.-->
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
        <activity
            android:name="com.mp3songsdownloader.searchonline.MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustNothing" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.mp3songsdownloader.searchonline.PlayerActivity"
            android:label="@string/app_name"
            android:theme="@style/MyDialogTheme" >
            </activity>
    </application>

</manifest>
Amit Rana
  • 33
  • 9
  • *Attempt to get length of null array* what is not clear in that message? – Lino Dec 15 '17 at 12:29
  • how to solve this becuz i am not a android developer. I just changed the package name as per developer instructions. – Amit Rana Dec 15 '17 at 12:31
  • post your `AndroidManifest.xml` file. – Dharmishtha Dec 15 '17 at 12:34
  • @Dharmishtha updated the android manifest file. – Amit Rana Dec 15 '17 at 12:37
  • Guys, please don't do the down vote my question i am not a android developer. Just asking the my problem how to solve it. – Amit Rana Dec 15 '17 at 12:38
  • 1
    Amit - you misunderstand the purpose of StackOverflow. It is not a place where non-developers can say *"I am a non-developer"* and expect developers to solve their problems ... for free. – Stephen C Dec 15 '17 at 12:49
  • @StephenC i have just started the android development and not have much knowledge about it , i just try to ask my query bcuz i have no idea about this error. I think experienced developers need to help the new beginners instead of downgrading them. – Amit Rana Dec 15 '17 at 12:51
  • 3
    What you think, and what StackOverflow actually is .... are different. What I think is that StackOverflow newbies need to do is to read the Help Centre info about how to ask **good** questions, what downvotes mean and so on. And above all, they should not waltz in and demand that people help them. 'Cos that *never* ends well. – Stephen C Dec 15 '17 at 12:56
  • @StephenC okay, agree with your point than from where newbies ask the help from experienced developers? – Amit Rana Dec 15 '17 at 12:59
  • A training course. A discussion forum. A rent-a-coder site. An IT mentoring or tutoring site. – Stephen C Dec 15 '17 at 13:04
  • Looks like you don't actually have the `READ_EXTERNAL_STORAGE` permission. http://stackoverflow.com/questions/32635704 – Mike M. Dec 15 '17 at 19:07
  • 1
    @MikeM. yes Mike, i figure it out it was External Storage permission issue. thanks – Amit Rana Dec 16 '17 at 09:59

2 Answers2

2

The exception means that

 File[] files = root.listFiles();

is setting files to null. That means that listFiles() has returned null. The javadoc for listFiles() says:

"Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs."

So you need to work out what is wrong with the way that you have formed the File for the directory you are trying to list.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

The problem was due to no permission of external storage.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Amit Rana
  • 33
  • 9