Android:在列表视图中以特定扩展名显示存储中的文件

时间:2015-12-08 13:13:06

标签: java android

我正在创建一个活动,通过' .mp4'来显示设备中的文件(包括外部存储空间)。 ListView中的扩展名。

这是活动文件

public class FindVideoActivity extends AppCompatActivity {

private List<String> fileNames;
private ListView lv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_find_video);

    fileNames = new ArrayList<>();
    lv = (ListView) findViewById(R.id.find_video_list);

    updateFileList();
}

public void updateFileList() {
    String path;

    String extension = Environment.getExternalStorageState();
    if(extension.equals(Environment.MEDIA_MOUNTED)) {
        path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videostreaming/";
    } else {
        path = Environment.MEDIA_UNMOUNTED;
    }

    File file = new File(path);

    ArrayAdapter<String> fileList = new ArrayAdapter<>(this, R.layout.file_list_item, fileNames);

    VideoFinder finder = new VideoFinder();
    File[] files = file.listFiles(finder);

    for(File f: files) {
        fileNames.add(f.getName());
    }

    lv.setAdapter(fileList);
  }
 }

为了过滤掉&#39; .mp4&#39;我创建了另一个类并将其命名为VideoFinder.java。该类实现java.io.FilenameFilter。这是代码。

public class VideoFinder implements FilenameFilter {

// overriding the method from the FilenameFilter interface.
@Override
public boolean accept(File dir, String filename) {
    if(filename.endsWith(".mp4")) {
        return true;
    }
    return false;
   }
  }

When I run the code above, it returns `NullPointerException` like the following.

Caused by: java.lang.NullPointerException
                                                     at com.marshall.videostreaming.FindVideoActivity.updateFileList(FindVideoActivity.java:46)
                                                     at com.marshall.videostreaming.FindVideoActivity.onCreate(FindVideoActivity.java:26) 

所以它说for方法中的updateFileList()循环正在捕获异常。我仍然无法捕捉到此代码中缺少的内容。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

检查您的路径,因为分配Environment.MEDIA_UNMOUNTED似乎不正确。还要检查Files是否为null,因为这就是你获得NPE的原因。

答案 1 :(得分:0)

我的主Java

/**
 * Created by ravindra on 2/12/15.
 */
public class GalleryScreen extends Activity implements View.OnClickListener{

    private ArrayList<String> file_path = new ArrayList<String>();
    GridView gridview;



    ImageView left_iv;
    TextView header_tv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.gallery_screen);

        Bundle bundle = getIntent().getExtras();

        gettingIds();

        gettingOnClickListener();

        fetchDeviceGallery();



    }

    private void fetchDeviceGallery() {

        String[] projection = {MediaStore.Images.Thumbnails._ID};
        // Create the cursor pointing to the SDCard
        Cursor cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                projection, // Which columns to return
                null,       // Return all rows
                null,
                MediaStore.Images.Thumbnails.IMAGE_ID);
        // Get the column index of the Thumbnails Image ID
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);


        file_path = getFilePaths();

        GalleryAdapter adapter = new GalleryAdapter(GalleryScreen.this,file_path);
        gridview.setAdapter(adapter);

        System.out.println("Gallery images================="+cursor.getCount()+"    "+columnIndex);

    }


    private void gettingIds() {

        gridview = (GridView) findViewById(R.id.gridview);

        left_iv = (ImageView) findViewById(R.id.left_iv);
        header_tv = (TextView) findViewById(R.id.header_tv);


        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                finish();
//                overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);


            }
        });

    }


    private void gettingOnClickListener() {

        left_iv.setOnClickListener(this);

    }

    public ArrayList<String> getFilePaths() {


        Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Images.ImageColumns.DATA};
        Cursor c = null;
        SortedSet<String> dirList = new TreeSet<String>();
        ArrayList<String> resultIAV = new ArrayList<String>();

        String[] directories = null;
        if (u != null) {
            c = GalleryScreen.this.managedQuery(u, projection, null, null, null);
        }

        if ((c != null) && (c.moveToFirst())) {
            do {
                String tempDir = c.getString(0);
                tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
                try {
                    dirList.add(tempDir);
                } catch (Exception e) {

                }
            }
            while (c.moveToNext());
            directories = new String[dirList.size()];
            dirList.toArray(directories);

        }

        for (int i = 0; i < dirList.size(); i++) {
            File imageDir = new File(directories[i]);
            File[] imageList = imageDir.listFiles();
            if (imageList == null)
                continue;
            for (File imagePath : imageList) {
                try {

                    if (imagePath.isDirectory()) {
                        imageList = imagePath.listFiles();

                    }



                    if (imagePath.getName().contains(".jpg") || imagePath.getName().contains(".JPG")
                            || imagePath.getName().contains(".jpeg") || imagePath.getName().contains(".JPEG")
                            || imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
                            || imagePath.getName().contains(".mp4") || imagePath.getName().contains(".MP4")
                    ||imagePath.getName().contains(".mp3") || imagePath.getName().contains(".MP3"))


                             {


                        System.out.println("RESOURCES  ARE====="+imagePath);

                        String path = imagePath.getAbsolutePath();
                        resultIAV.add(path);



                }
                //  }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return resultIAV;


    }


    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.left_iv:

                finish();
                overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);



                break;


        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        finish();
        overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);



    }
}

它的适配器类如下: -

/**
 * Created by ravindra on 2/12/15.
 */
public class GalleryAdapter extends BaseAdapter {


    private final DisplayImageOptions options;
    private final ImageLoader imageLoader;
    Activity activity;
    ArrayList<String> arrayList = new ArrayList<String>();


    public GalleryAdapter(Activity activity, ArrayList<String> arrayList) {
        this.activity = activity;
        this.arrayList = arrayList;
        imageLoader = ImageLoader.getInstance();
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(activity));
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.loader)
                .showImageForEmptyUri(R.drawable.loader)
                .showImageOnFail(R.drawable.loader)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

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

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


    public class ViewHolder {

        ImageView gallery_item;

    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {



        final ViewHolder _viewHolder;
        if (convertView == null) {


            _viewHolder = new ViewHolder();
            LayoutInflater _layInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = _layInflater.inflate(R.layout.gallery_item, null);


            _viewHolder.gallery_item = (ImageView) convertView.findViewById(R.id.gallery_item);



            convertView.setTag(_viewHolder);


        } else {
            _viewHolder = (ViewHolder) convertView.getTag();
        }


        if (arrayList.get(position).contains(".mp3") || arrayList.get(position).contains(".MP3"))
        {
            _viewHolder.gallery_item.setImageResource(R.drawable.audio_img);
        }
        else {
            imageLoader.displayImage("file://" + arrayList.get(position), _viewHolder.gallery_item, options, null);
        }

        return convertView;
    }
}