Main Activity class
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.w3c.dom.Document;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ImageButton text,word,pdf;
BufferedReader reader = null;
StringBuilder builder = null;
Button fileclick;
File file;
Document document;
String f1;
private static final int REQUEST_PICK_FILE = 1;
private TextView mFilePathTextView, ccc;
String str;
// private Button mStartActivityButton;
private File selectedFile;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, FilePickerActivity.class);
startActivityForResult(intent, REQUEST_PICK_FILE);
// str=(String) mFilePathTextView.getText();
// file = new File(str);
// mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
// fileclick=(Button)findViewById(R.id.search);
// ccc=(TextView)findViewById(R.id.showtext);
// mFilePathTextView=(TextView)findViewById(R.id.file_path_text_view);
// fileclick.setOnClickListener(this);
// fileopen.setOnClickListener(this);
}
// public void onClick(View v)
// {
//
//// Intent intent = new Intent(this, FilePickerActivity.class);
////
//// startActivityForResult(intent, REQUEST_PICK_FILE);
//// str=(String) mFilePathTextView.getText();
//// file = new File(str);
////
//
// }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch(requestCode) {
case REQUEST_PICK_FILE:
if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
// Get the file path
selectedFile = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
// Set the file path text view
mFilePathTextView.setText(selectedFile.getPath());
//Now you have your selected file, You can do your additional requirement with file.
}
}
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.w3c.dom.Document;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ImageButton text,word,pdf;
BufferedReader reader = null;
StringBuilder builder = null;
Button fileclick;
File file;
Document document;
String f1;
private static final int REQUEST_PICK_FILE = 1;
private TextView mFilePathTextView, ccc;
String str;
// private Button mStartActivityButton;
private File selectedFile;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, FilePickerActivity.class);
startActivityForResult(intent, REQUEST_PICK_FILE);
// str=(String) mFilePathTextView.getText();
// file = new File(str);
// mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
// fileclick=(Button)findViewById(R.id.search);
// ccc=(TextView)findViewById(R.id.showtext);
// mFilePathTextView=(TextView)findViewById(R.id.file_path_text_view);
// fileclick.setOnClickListener(this);
// fileopen.setOnClickListener(this);
}
// public void onClick(View v)
// {
//
//// Intent intent = new Intent(this, FilePickerActivity.class);
////
//// startActivityForResult(intent, REQUEST_PICK_FILE);
//// str=(String) mFilePathTextView.getText();
//// file = new File(str);
////
//
// }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch(requestCode) {
case REQUEST_PICK_FILE:
if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
// Get the file path
selectedFile = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
// Set the file path text view
mFilePathTextView.setText(selectedFile.getPath());
//Now you have your selected file, You can do your additional requirement with file.
}
}
}
}
}
file picker Activity Class
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FilePickerActivity extends ListActivity
{
BufferedReader reader;
FileInputStream fis=null;
final StringBuffer buffer= new StringBuffer();
static String text_word=null;
StringBuilder builder;
public final static String EXTRA_FILE_PATH = "file_path";
public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
private final static String DEFAULT_INITIAL_DIRECTORY = "/";
String txtPattern=".txt", docPattern=".doc",docxPattern=".docx",DocPattern=".DOC",DocxPattern=".DOCX",TxtPattern=".TXT",pdfPattern=".pdf",PdfPattern=".PDF";
Vector<String> mStrings =new Vector<String>();
protected File mDirectory;
protected ArrayList<File> mFiles;
protected FilePickerListAdapter mAdapter;
protected boolean mShowHiddenFiles = false;
protected String[] acceptedFileExtensions;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the view to be shown if the list is empty
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View emptyView = inflator.inflate(R.layout.file_picker_empty_view, null);
((ViewGroup)getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
// Set initial directory
mDirectory = new File(DEFAULT_INITIAL_DIRECTORY);
// Initialize the ArrayList
mFiles = new ArrayList<File>();
// Set the ListAdapter
mAdapter = new FilePickerListAdapter(this, mFiles);
setListAdapter(mAdapter);
// Initialize the extensions array to allow any file extensions
acceptedFileExtensions = new String[] {};
// Get intent extras
if(getIntent().hasExtra(EXTRA_FILE_PATH)) {
mDirectory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH));
}
if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES)) {
mShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
}
if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
ArrayList<String> collection = getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
acceptedFileExtensions = (String[]) collection.toArray(new String[collection.size()]);
}
}
protected void onResume() {
refreshFilesList();
super.onResume();
}
/**
* Updates the list view to the current directory
*/
protected void refreshFilesList() {
// Clear the files ArrayList
mFiles.clear();
// Set the extension file filter
ExtensionFilenameFilter filter = new ExtensionFilenameFilter(acceptedFileExtensions);
// Get the files in the directory
File[] files = mDirectory.listFiles(filter);
if(files != null && files.length > 0)
{
for (int i = 0; i < files.length; i++)
{
String mCheck=files[i].getAbsoluteFile().toString();
mCheck=mCheck.substring(mCheck.lastIndexOf("/")+1);
// System.out.println("listFile[i].getAbsoluteFile().toString()"+files[i].getAbsoluteFile().toString());
// System.out.println("mCheck..."+mCheck);
if (files[i].isDirectory() && !(mCheck.startsWith(".")) )
{
System.out.println(files[i].toString()+" "+"created by amit singh tomar");
// if(files[i].getName().equals("/sdcard"));
// {
// mFiles.add(files[i]);
// }
if (files[i].toString().equals("/sdcard"))
{
mFiles.add(files[i]);
System.out.println("dinesh +amit ........");
}
}
else
{
if (files[i].getName().endsWith(txtPattern) ||files[i].getName().endsWith(DocPattern)||files[i].getName().endsWith(docPattern) ||files[i].getName().endsWith(docxPattern) ||files[i].getName().endsWith(DocxPattern) ||files[i].getName().endsWith(TxtPattern) ||files[i].getName().endsWith(pdfPattern) ||files[i].getName().endsWith(PdfPattern))
{
mFiles.add(files[i]);
}
}
}
// for(File f : files)
// {
//
//
// if(f.isHidden() && !mShowHiddenFiles) {
// // Don't add the file
// continue;
// }
// mFiles.add(f);
}
Collections.sort(mFiles, new FileComparator());
// }
mAdapter.notifyDataSetChanged();
}
public void onBackPressed() {
if(mDirectory.getParentFile() != null) {
// Go to parent directory
mDirectory = mDirectory.getParentFile();
refreshFilesList();
return;
}
super.onBackPressed();
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
//Toast.makeText(getApplicationContext(), "pos"+" "+position, Toast.LENGTH_LONG).show();
File newFile = (File)l.getItemAtPosition(position);
if(newFile.isFile())
{
// Set result
Intent extra = new Intent();
extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
setResult(RESULT_OK, extra);
if(newFile.getName().endsWith(".doc")||newFile.getName().endsWith(".docx") ||newFile.getName().endsWith(".DOCX") ||newFile.getName().endsWith(".DOC"))
{
Uri path = Uri.fromFile(newFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path,"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);
}
else if(newFile.getName().endsWith(".pdf") ||newFile.getName().endsWith(".PDF"))
{
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0 && newFile.isFile())
{
Intent intent1 = new Intent();
intent1.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(newFile);
intent1.setDataAndType(uri,"application/pdf");
startActivity(intent1);
}
}
else
{
try {
fis = openFileInput(newFile.toString());
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
if ((strLine = reader.readLine()) != null)
{
buffer.append(strLine);
text_word= buffer.toString();
}
dataIO.close();
fis.close();
// reader = new BufferedReader(new FileReader(newFile));
// builder = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null)
// {
// builder.append(line);
//
//
// }
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Finish the activity
finish();
}
else
{
mDirectory = newFile;
// Update the files list
refreshFilesList();
}
super.onListItemClick(l, v, position, id);
}
private class FilePickerListAdapter extends ArrayAdapter<File> {
private List<File> mObjects;
public FilePickerListAdapter(Context context, List<File> objects) {
super(context, R.layout.file_picker_list_item, android.R.id.text1, objects);
mObjects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_picker_list_item, parent, false);
} else {
row = convertView;
}
File object = mObjects.get(position);
ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image);
TextView textView = (TextView)row.findViewById(R.id.file_picker_text);
// Set single line
textView.setSingleLine(true);
textView.setText(object.getName());
if(object.isFile()) {
// Show the file icon
imageView.setImageResource(R.drawable.fileimg);
} else {
// Show the folder icon
imageView.setImageResource(R.drawable.folderimg);
}
return row;
}
}
private class FileComparator implements Comparator<File> {
public int compare(File f1, File f2) {
if(f1 == f2) {
return 0;
}
if(f1.isDirectory() && f2.isFile()) {
// Show directories above files
return -1;
}
if(f1.isFile() && f2.isDirectory()) {
// Show files below directories
return 1;
}
// Sort the directories alphabetically
return f1.getName().compareToIgnoreCase(f2.getName());
}
}
private class ExtensionFilenameFilter implements FilenameFilter
{
private String[] mExtensions;
public ExtensionFilenameFilter(String[] extensions)
{
super();
mExtensions = extensions;
}
public boolean accept(File dir, String filename)
{
if(new File(dir, filename).isDirectory())
{
// Accept all directory names
return true;
}
if(mExtensions != null && mExtensions.length > 0)
{
for(int i = 0; i < mExtensions.length; i++)
{
if(mExtensions[i].endsWith(".txt"))
{
// The filename ends with the extension
return true;
}
}
// The filename did not match any of the extensions
return false;
}
// No extensions has been set. Accept all file extensions.
return true;
}
}
}
Manifest File
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.practise_pdf_word_docx_file"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".FilePickerActivity"
android:label="@string/app_name">
</activity>
</application>
</manifest>
Permission :
READ_CONTACTS
WRITE_CONTACTS
WRITE_EXTERNAL_STORAGE
Comments
Post a Comment