Oct 13, 2011

Start activity using intent of ACTION_VIEW, for specified MIME type.

In the last post, we can Get File Extension and MIME Type. According to the detected MIME Type, we can start another activity with intent of ACTION_VIEW to view the file.

package com.AndroidListFiles;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AndroidListFilesActivity extends ListActivity {

private List<String> fileList = new ArrayList<String>();

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

File root = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath());
ListDir(root);

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File selected = new File(fileList.get(position));
if(selected.isDirectory()){
ListDir(selected);
}else {
Uri selectedUri = Uri.fromFile(selected);
String fileExtension
= MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
String mimeType
= MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

Toast.makeText(AndroidListFilesActivity.this,
"FileExtension: " + fileExtension + "\n" +
"MimeType: " + mimeType,
Toast.LENGTH_LONG).show();

//Start Activity to view the selected file
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, mimeType);
startActivity(intent);

}
}

void ListDir(File f){
File[] files = f.listFiles();
fileList.clear();
for (File file : files){
fileList.add(file.getPath());
}

ArrayAdapter<String> directoryList
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
setListAdapter(directoryList);
}

}



next:
- Back in history for File Explorer



No comments:

Post a Comment

Infolinks In Text Ads