Listing image files in a directory and populate a ListView from it in Android

I have a directory in sdcard called “mydir” and there are lot of .png image files with another files. Then I want to list only that .png files and populate a ListView from it.

I do it like this:

String path = "/sdcard/mydir";
File directory = new File(path);
if (!directory.exists()){
	directory.mkdir();
}
File[] files = directory.listFiles();

String[] localfiles = new String[files.length];
for (int i = 0; i < files.length; i++)
{
	localfiles[i] = files[i].getName();
}
ArrayAdapter<String> lbadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, localfiles);


List<String> localfiles = new ArrayList<String>();
for (int i = 0; i < files.length; i++)
{
	if(files[i].getName().contains(".png"))
		localfiles.add(files[i].getName());
}
ArrayAdapter<String> lbadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, localfiles);

lblist.setAdapter(lbadapter);

lblist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
		final String itemname = (String) parent.getItemAtPosition(position);
		Toast.makeText(getApplicationContext(), itemname, Toast.LENGTH_LONG).show();
	}

});

 

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *