Null pointer exception trying to remove from listview - android

I get a null pointer exception in the deleteIt method in the filelist.notifyDataSetChanged();
I need some help trying to remove the file, please be kind. It took me a couple of hours how to add the longclick method. This could could be used by someone but I need to help with the removing item from list.
public class AndroidExplorer extends ListActivity
{
private List<String> item = null;
private List<String> path = null;
private TextView myPath;
ArrayAdapter filelist = null;
File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/GV-Skynet");
String root2 = myFile.getAbsolutePath();;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
getDir(root2);
ListView list = getListView();
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id)
{
File file = new File(path.get(position));
deleteIt("Do you want to Delete", file.getName(), file );
return true;
}
});
}
private void showToast(String msg)
{
Toast error = Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG);
error.show();
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root2))
{
item.add("Return to GV-Skynet Directory");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
String fileName = file.getName();
String fname="";
String ext="";
int mid= fileName.lastIndexOf(".");
fname=fileName.substring(0,mid);
ext=fileName.substring(mid+1,fileName.length());
if(ext.equals("jpg"))
{
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(file);
intent.setDataAndType (uri, "image/*");
this.startActivity(intent);
}
if(ext.equals("3gp"))
{
Intent intent = new Intent("android.intent.action.VIEW");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra ("oneshot", 0);
intent.putExtra ("configchange", 0);
Uri uri = Uri.fromFile(file);
intent.setDataAndType (uri, "video/*");
this.startActivity(intent);
}
}
}
public void deleteIt( String title, String name, File file )
{
final String name1 = name;
final File tmFile = file;
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(name1)
.setPositiveButton("YES", new DialogInterface.OnClickListener() // OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//item = new ArrayList<String>();
item.remove(tmFile.getName()); // remove the item
filelist.notifyDataSetChanged(); // let the adapter know to update
showToast("File Deleted: " + tmFile.getName() );
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() // OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1) {
// do stuff onclick of CANCEL
showToast("CANCELLING DELETE");
}
}).show();
}
}

just try this change your statement
ArrayAdapter filelist = null;
with
ArrayAdapter<String> filelist = null;
and also you are re-declaring filelist in your getDir method so change it to
filelist = new ArrayAdapter<String>(this,R.layout.row, item);
setListAdapter(filelist);

onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
File file = new File(path.get(position));
if (file.exists()) {
deleteIt("Do you want to Delete", file.getName(), file);
} else {
Toast.makeText(this, "File not Exist", Toast.LENGTH_SHORT).show();
}
}

Related

Blank screen when opening a pdf using 'com.github.barteksc:android-pdf-viewer:2.8.2' library

I have an issue with using this library
compile 'com.github.barteksc:android-pdf-viewer:2.8.2'
Well I have a couple of pdfs created from my app and I want to give th user an option to view them from the app.Im loading the files from a dialog and on select the selected pdf shoulld open.Here is the dialog.
public class FileExplore extends BaseActivityAlt {
private static final String TAG = "F_PATH";
private static final int DIALOG_LOAD_FILE = 1000;
ArrayList<String> str = new ArrayList<String>();
ListAdapter adapter;
private Boolean firstLvl = true;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory() + "/Travelite/Saved/");
private String chosenFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this,TicketActivity.class);
startActivity(intent);
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.mipmap.pdf_icon);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.company;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Up", R.drawable.forward);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle(R.string.choose_file);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
File file = new File(Environment.getExternalStorageDirectory(),
chosenFile);
Intent intent = new Intent(FileExplore.this,PdfViewer.class);
intent.putExtra("Filename",chosenFile);
startActivity(intent);
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}}
And here is the class loaded onClicking an item in the dialog
public class PdfViewer extends BaseActivityAlt implements OnLoadCompleteListener, OnPageErrorListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf_viewer);
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
String filename = getIntent().getStringExtra("Filename");
File pdffile = new File(Environment.getExternalStorageDirectory(),filename);
Uri file = Uri.fromFile(pdffile);
Toast.makeText(PdfViewer.this, filename, Toast.LENGTH_LONG).show();
pdfView.fromUri(file)
.defaultPage(1)
.password(null)
.load();
}
#Override
public void loadComplete(int nbPages) {
}
#Override
public void onPageError(int page, Throwable t) {
}}
I just realised my mistake: I completely forgot to add the path.

how to convert an class extends activity into independent class

I have a class that is currently extending Activity and I have methods like onCreate(),OnBackPress() etc. I want to turn it into an independent class but all the above methods become undefined. What is the problem? Shouldn't importing the classes be enough? For eg, I import android.view.View for findViewById but it still makes no difference. Please advise.
File_Explore
public class File_Explorer extends Activity {
// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;
String aDataRow = "";
static StringBuilder aBuffer = new StringBuilder();
String aBuffer1="";
private static final String TAG = "F_PATH";
static long fileSizeInMB;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 0;
static String fileExtension="";
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.ic_launcher);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.ic_launcher;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Back", R.drawable.ic_launcher);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablePadding(
fileList[position].icon);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("Back") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
fileExtension
= MimeTypeMap.getFileExtensionFromUrl(sel.toString());
// Toast.makeText(getApplication(), fileExtension, Toast.LENGTH_LONG).show();
long fileSizeInBytes = sel.length();
fileSizeInMB = fileSizeInBytes/(1024*1024);
Toast.makeText(getApplication(), String.valueOf(fileSizeInMB).toString(), Toast.LENGTH_LONG).show();
if(fileSizeInMB >1){
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
}
else{
try{
// ArrayList<String> MyFiles = new ArrayList<String>();
FileInputStream fIn = new FileInputStream(sel);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer.append(aDataRow.toString()).append("\n");
}
// aBuffer1 = aBuffer.toString();
myReader.close();
}catch (FileNotFoundException e)
{e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
finish();
}
}
aBuffer.delete(0, aBuffer.length());
// aBuffer1=null;
}
}
);
break;
}
dialog = builder.show();
return dialog;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i= new Intent(this, File_Selecter.class);
startActivity(i);
}
}

Android: How to make user selected images become the image of the ImageButton?

I'm new to android and I need the image from the users choice after choosing the image from any location to be the image of the image button. Can anyone provide me with a sample code to help me out? Thanks.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_explorer);
myPath = (TextView)findViewById(R.id.action_settings);
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.file_row, item);
setListAdapter(fileList);
}
protected void onListItemClick(ListView l, View v, int position, long id, String[] writeinfo, Options options) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.mufc)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
}
Another thing, I am also not sure of how to save the image. Thanks.
Set an item clicked listener on the list view. http://developer.android.com/reference/android/widget/AdapterView.html#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
On its callback you will probably be able to get the file info needed. Then it's just a matter of setting the drawable on the button. http://developer.android.com/reference/android/widget/ImageView.html#setImageBitmap(android.graphics.Bitmap)

Trying to add onLongListItemClick and getting an exception

I commented out the section I was adding protected boolean onLongListItemClick(ListView l, View v, int position, long id).
If I un-comment I get an exception. I am trying to add if there is long press I will delete the file, which will be added later. Is there a simple way to do this.
public class AndroidExplorer extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private TextView myPath;
File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Boot");
String root2 = myFile.getAbsolutePath();;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
getDir(root2);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root2))
{
item.add("Return to Boot Directory");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
// protected boolean onLongListItemClick(ListView l, View v, int position, long id) {
// // Log.i(TAG, "onLongListItemClick id=" + id);
// Toast.makeText(this,
// "I will be terminated",
// Toast.LENGTH_LONG).show();
// return true;
// }
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
String fileName = file.getName();
String fname="";
String ext="";
int mid= fileName.lastIndexOf(".");
fname=fileName.substring(0,mid);
ext=fileName.substring(mid+1,fileName.length());
if(ext.equals("jpg"))
{
Toast.makeText(this,
"view the jpg",
Toast.LENGTH_LONG).show();
}
if(ext.equals("3gp"))
{
Toast.makeText(this,
"play the video",
Toast.LENGTH_LONG).show();
}
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
}
add an AdapterView.OnItemLongClickListener. See setOnItemLongClickListener.
.
listView.setOnItemLongClickListener (new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
//do your stuff here
}
});

How to list the data in sdcard

I want to display the file name which is residing in specific location in sdcard. is it possible to display it in listview format? pls guide me.
This is the stuff,
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File("/sdcard/");
// or you can use File f=new File(Environment.getExternalStorageDirectory().getPAth());
File[] files = f.listFiles();
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
For more detail look at: Implement a simple File Explorer in Android .
If you know the location/path of the directory from where you want to get the files from, then you can use the following code to get the list of files and display them in list view.
//Assuming that MEDIA_PATH is the location from where the files are to be retrieved.
List<String> songs=new ArrayList<String>();
File home = new File(MEDIA_PATH); // Getting file representation of the directory
File[] musicFiles=home.listFiles();
if(musicFiles.length>0){
for( File f:musicFiles) { songs.add(f.getName()); }
ListAdapter adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,songs);
setListAdapter(adapter);
}
If you are using ListActivity, you wouldn't need to use setContentView(...).
You can also use a FilenameFilter, if you want only specific type of files(e.g mp3 files) to be fetched and displayed.
Use this code,
public class RecordedVideos extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root="/sdcard/Recorded Videos";
private TextView myPath;
Button back;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filelist);
back=(Button)findViewById(R.id.back);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
File file = new File(path.get(arg2));
boolean b=file.delete();
return false;
}
});
myPath = (TextView)findViewById(R.id.path);
getDir(root);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("..../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
/*new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show(); */
Intent intent= new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri filetype= Uri.parse("file://" + file.getPath());
String filename=file.getName();
if(filename.endsWith(".txt")||filename.endsWith(".doc"))
{
intent.setDataAndType(filetype, "text/*");
startActivity(intent);
}
else if(filename.endsWith(".gif")||filename.endsWith(".jpg")||filename.endsWith(".png"))
{
intent.setDataAndType(filetype, "image/*");
startActivity(intent);
}
else if(filename.endsWith(".mp4")||filename.endsWith(".3gp"))
{
intent.setDataAndType(filetype, "video/*");
startActivity(intent);
}
else
{
intent.setDataAndType(filetype, "audio/*");
startActivity(intent);
}
}
}
}

Categories

Resources