请帮助我是新手,但是却遇到此错误?
当我启动应用程序时,我请求存储许可,但此后应用程序崩溃并给我这个错误:-尝试获取null数组的长度。请帮忙。

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.techx.storysaver/com.techx.storysaver.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
      at android.app.ActivityThread.-wrap12(ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6126)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
   Caused by: java.lang.NullPointerException: Attempt to get length of null array
      at com.techx.storysaver.ImageAdapter.getCount(ImageAdapter.java:40)
      at android.widget.GridView.setAdapter(GridView.java:206)
      at com.techx.storysaver.ImageFragment.onCreateView(ImageFragment.java:53)
      at android.support.v4.app.Fragment.performCreateView(Fragment.java:2189)
      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
      at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
      at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
      at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
      at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
      at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
      at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
      at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
      at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
      at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
      at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249)
      at android.app.Activity.performStart(Activity.java:6696)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
      at android.app.ActivityThread.-wrap12(ActivityThread.java) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:154) 
      at android.app.ActivityThread.main(ActivityThread.java:6126) 
      at java.lang.reflect.Method.invoke(Native Method)




这是我的ImageAdapter

public class ImageAdapter extends BaseAdapter {

    private Context context;


    String path = Environment.getExternalStorageDirectory().toString()+"/Pictures/";
    File f = new File(path);
    File file[] = f.listFiles();



    public ImageAdapter(Context c)
    {
        context = c;
    }


    @Override
    public int getCount() {

            return file.length;     //Line 40, Here i am gettin Error

    }

    @Override
    public Object getItem(int position) {
        return file[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(context);
        Glide
                .with( context )
                .load( file[position] )
                .into( imageView );
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(360,480));

        return imageView;
    }

}


这是我的图像片段

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.image_fragment, container, false);

    GridView gridView = (GridView)rootView.findViewById(R.id.grid_view);
    gridView.setAdapter(new ImageAdapter(getActivity())); //Line 50, Here Also i am getting Error



    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(getActivity(),FullImageActivity.class);
            i.putExtra("id",position);
            startActivity(i);
        }
    });

    return rootView;
}

最佳答案

String path = Environment.getExternalStorageDirectory().toString()+"/Pictures/";
File f = new File(path);
File file[] = f.listFiles();


file[]为空,因此该语句return file.length;或任何其他涉及该变量的语句都会失败。也请使用异常处理来处理文件中的文件。例如FileNotFound。

也试试这个String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

String pic_path = String.format("%s/%s",path,specific_path);


使用它代替获取文件的句柄。

   File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);


然后if(storageDir.exists()){File file[] = storageDir.listFiles();}

调用getExternalFilesDir的语法,它取决于上下文。


片段中的getActivity()。getExternalFilesDir()
类,在其中传递Context的context.getExternalFilesDir()
    作为参数
YourActivity.this.getExternalFilesDir();什么时候
        在Activity的内部类中调用

07-24 13:47