How to get the file extension in Android? - android

I am a newbie.
I have an EditText and a Browse Button to explore Folders and select files only.
From the Browse Button, when a file is clicked it stores the folder path in which that file is in one string and the file name without extension in other string, which I am using to store, either of these two, in the EditText.
I want to make the file name with the exactly file extension (whether one or two dots), but I don't have any idea how to get the file extension also.
All answers will be appreciated.
FileChooser.java
package com.threefriends.filecrypto;
/**
* Created by hp on 01-06-2016.
*/
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir=new File("/sdcard/");
fill(currentDir);
}
private void fill(File f)
{
File[]dirs=f.listFiles();
this.setTitle("Current Dir: "+f.getName());
List<Item>dir=new ArrayList<Item>();
List<Item>fls=new ArrayList<Item>();
try{
for(File ff: dirs)
{
Date lastModDate=new Date(ff.lastModified());
DateFormat formater=DateFormat.getDateTimeInstance();
String date_modify=formater.format(lastModDate);
if(ff.isDirectory()){
File[] fbuf=ff.listFiles();
int buf=0;
if(fbuf != null){
buf=fbuf.length;
}
else
buf=0;
String num_item=String.valueOf(buf);
if(buf == 0)
num_item=num_item+" item";
else
num_item = num_item+" items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(), num_item, date_modify, ff.getAbsolutePath(), "directory_icon"));
}
else
{
fls.add(new Item(ff.getName(), ff.length()+" Byte", date_modify, ff.getAbsolutePath(), "file_icon"));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0, new Item("..", "Parent Directory", "", f.getParent(), "directory_up"));
adapter=new FileArrayAdapter(FileChooser.this, R.layout.file_view, dir);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon") || o.getImage().equalsIgnoreCase("directory_up")){
currentDir=new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o);
}
}
private void onFileClick(Item o)
{
//Toast.makeText(this, "Folder Clicked: "+ currentDir, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("GetPath", currentDir.toString());
intent.putExtra("GetFileName", o.getName());
setResult(RESULT_OK, intent);
finish();
}
}
Part of MainActivity.java
//Defined for file edittext.
EditText editText2;
private static String TAG = MainFragment.class.getSimpleName(); //For File Exploring.
private static final int REQUEST_PATH = 1;
String curFileName;
String filePath;
EditText edittext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_main, container, false);
edittext = (EditText) view.findViewById(R.id.editText); //Done for File Exploring, EditText, Browse Button.
Button b1 = (Button) view.findViewById(R.id.skipButton);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent1 = new Intent(v.getContext(), FileChooser.class);
startActivityForResult(intent1, REQUEST_PATH);
}
}
);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// See which child activity is calling us back.
if (requestCode == REQUEST_PATH)
{
if (resultCode == Activity.RESULT_OK)
{
curFileName = data.getStringExtra("GetFileName");
filePath=data.getStringExtra("GetPath");
edittext.setText(filePath);
}
}
}

lots of ways . here are 2 sample-
String someFilepath = "image.fromyesterday.test.jpg";
String extension = someFilepath.substring(someFilepath.lastIndexOf("."));
So in you case, it should be something like that
String extension = ff.getAbsolutePath().substring(ff.getAbsolutePath().lastIndexOf("."));
In case if you don't want to do it yourself-
use FilenameUtils.getExtension from Apache Commons IO-
String extension = FilenameUtils.getExtension("/path/to/file/mytext.txt");
or in your case -
String extension = FilenameUtils.getExtension(ff.getAbsolutePath());

You could just do it with one line of code using MIME Type Map.
First grab the file:
Uri file = Uri.fromFile(new File(filePath));
Then
String fileExt = MimeTypeMap.getFileExtensionFromUrl(file.toString());

You can put your code in your activity like this:
private String getfileExtension(Uri uri)
{
String extension;
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
extension= mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
return extension;
}
"uri" is the file uri from the result of "Browse button" selected file

Kotlin Approach:
val fileExtention: String = file.extension
Check this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/extension.html

Function:
public String getExt(String filePath){
int strLength = filePath.lastIndexOf(".");
if(strLength > 0)
return filePath.substring(strLength + 1).toLowerCase();
return null;
}
Usage:
String ext = getExt(path);
if(ext != null && ext.equals("txt")){
// do anything
}
PS: If you don't use toLowerCase(), possible the function returns upper and lower cases (dependent the exists file).

In Kotlin
You can read the MimeTypeMap documentation here
This is example if you are using startActivityForResult and you get data from it. Then you define Content Resolver to get mime type from the uri.
val uri: Uri? = it.data?.data
val contentResolver = requireContext().contentResolver
val stringMimeType = contentResolver.getType(uri!!)
Using that code, if you choose pdf file you will get something like
"application/pdf"
After that, using the MimeTypeMap you'll get the extensions. Don't forget that you should add getSingleton() because it's only available in singleton.
val stringFileType = MimeTypeMap.getSingleton().getExtensionFromMimeType(stringMimeType)

I used DocumentFile to get the file name and extension
DocumentFile documentFile = DocumentFile.fromSingleUri(YourActivity.this, fileUri);
String fileName = documentFile.getName();
String extension = fileName.substring(fileName.lastIndexOf("."));
For example, if your file name is 'your_image.jpg' then the extension will be '.jpg'

In Java
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
In Kotlin
fun getFileExt(fileName: String): String? {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)
}

Kotlin
import android.webkit.MimeTypeMap
MimeTypeMap.getFileExtensionFromUrl("my.xlsx") // xlsx
MimeTypeMap.getFileExtensionFromUrl("my.pdf") // pdf
MimeTypeMap.getFileExtensionFromUrl("http://www.google.com/my.docx") // docx
MimeTypeMap.getFileExtensionFromUrl(File.createTempFile("aaa", ".txt").absolutePath) // txt

Getting extension of file in Kotlin:
fun getExtension(fileName: String): String {
return fileName.substring(if (fileName.lastIndexOf(".") > 0) fileName
.lastIndexOf(".") + 1 else return "",fileName.length)
}

getContentResolver().getType(theReceivedUri); // return "media/format"

Related

BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: .jpg (No such file or directory)

Good morning, I'm creating activity which take picture then store it in file. But I had this error :
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: .jpg (No such file or directory)
Also I want to know how to store this picutre file into my room db I have a class "Photo".
Thank you.
Here is my code:
takepictureActivity
public class PrendrePhoto extends AppCompatActivity {
private ImageView imageView;
private EditText titrImg2;
private Button take;
private String pathPic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prendre_photo);
imageView = (ImageView) findViewById(R.id.imageTaken);
titrImg2 = findViewById(R.id.titreImg2);
take = findViewById(R.id.take);
take.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePicture();
}
});
}
private void takePicture() {
Intent takepic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takepic.resolveActivity(getPackageManager()) != null) {
File pic = null;
pic = creerPhotoFile();
if (pic != null) {
pathPic = pic.getPath();
System.out.println("pic créer");
System.out.println(pathPic);
startActivityForResult(takepic, 1);
}else {
System.out.println("pic null");
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = BitmapFactory.decodeFile(pathPic);
imageView.setImageBitmap(photo);
}
}
//Hna je dois crée filePhoto
}
private File creerPhotoFile() {
ZonedDateTime now = ZonedDateTime.now();
String d = ("" + now.getDayOfMonth() + "/" + now.getMonthValue() +
"/" + now.getYear());
String heure = "" + now.getHour() + " : " + now.getMinute();
String titre = titrImg2.getText().toString();
File temp = new File("temp");
temp.mkdirs();
System.out.println(temp.getPath());
File image = null;
/* try {
image = File.createTempFile(titre, ".jpg",temp);//Even with this
it didn't work
} catch (IOException e) {
e.printStackTrace();
}*/
image = new File(titre + ".jpg");
return image;
}
}
Photo.java
#Entity
public class Photo implements Serializable
{
#PrimaryKey(autoGenerate = true)
private int idP;
private String titre;
private String path ;//this path to get to help to display this picture
private String dateHeure ;
public Photo(String titre, String dateHeure) {
this.titre = titre;
this.dateHeure = dateHeure;
}
}
Even after doing all the logic of creating a unique file path you are using
String titre = titrImg2.getText().toString();
Which is (as per the name suggest) image title, which is coming form UI.
image = new File(titre + ".jpg");
return image;
I think you need to look into this.
As far as saving images in room goes, it is not recommended. But if you have to do it then you can use BLOB.
Images are usually stored as a BLOB and room does provide this
datatype. BLOB Documentation
Implementation can be done like:
#ColumnInfo(typeAffinity = ColumnInfo.BLOB)
private byte[] image;
}

Unable to pick file on Oreo

On Android Nougat and below, I can simply get some file on my storage using this code :
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*.jpg");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, 111);
And get the file path using :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111 && resultCode == RESULT_OK && data.getData() != null)
String path = data.getData().getPath();
}
But on Android Oreo, this is not working. The file picker is showing up, but I cannot even pick the file using the default file picker. At first, I thought that this is related to permission. But after I add the permission to READ and WRITE external storage on runtime, and granted, this problem still occurred.
Since the default file picker on OREO is troublesome, currently I'm using a custom class to pick file or directory. Another solution is you can use ES File Explorer, etc, but not all of your user has it and the main problem still occurred.
public class FileChooser {
private Activity activity;
private Item[] fileList;
private File path;
private boolean rootDir = true; //check if the current directory is rootDir
private boolean pickFile = true; //flag to get directory or file
private String title = "";
private String upTitle = "Up";
private String positiveTitle = "Choose Path";
private String negativeTitle = "Cancel";
private ListAdapter adapter;
private ArrayList<String> str = new ArrayList<>(); //Stores names of traversed directories, to detect rootDir
private Listener listener;
/**
* #param pickFile true for file picker and false for directory picker
* */
public FileChooser(Activity activity, boolean pickFile, Listener fileChooserListener) {
this.activity = activity;
this.pickFile = pickFile;
this.listener = fileChooserListener;
title = pickFile ? "Choose File" : "Choose Directory";
path = new File(String.valueOf(Environment.getExternalStorageDirectory()));
}
/**
* The view of your file picker
* */
public void openDirectory() {
loadFileList();
AlertDialog.Builder builder = new AlertDialog.Builder(activity, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
if (fileList == null)
builder.create();
builder.setTitle(title + "\n" + path.toString());
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
String chosenFile = fileList[position].file;
File selectedFile = new File(path + File.separator + chosenFile);
if (selectedFile.isDirectory()) { // user click on folder
rootDir = false;
str.add(chosenFile); // Adds chosen directory to list
path = selectedFile;
openDirectory();
}
else if (chosenFile.equalsIgnoreCase(upTitle) && !selectedFile.exists()) { // 'up' was clicked
String s = str.remove(str.size() - 1); // present directory
path = new File(
path.toString().substring(0, path.toString().lastIndexOf(s))); // exclude present directory
if (str.isEmpty()) // no more directories in the list, rootDir
rootDir = true;
openDirectory();
}
else if (listener != null && pickFile)
listener.onSelectedPath(selectedFile.getAbsolutePath());
}
});
if (!pickFile) {
builder.setPositiveButton(positiveTitle, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (listener != null)
listener.onSelectedPath(path.getPath());
}
});
}
builder.setNegativeButton(negativeTitle, null);
builder.show();
}
/**
* Setup your file picker data
* */
private void loadFileList() {
fileList = null;
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File file = new File(dir, filename);
// Filters based on whether the file is hidden or not
return ((pickFile && file.isFile()) || file.isDirectory()) && !file.isHidden();
}
};
String[] fList = path.list(filter); //set filter
if (fList != null) {
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++)
fileList[i] = new Item(fList[i], new File(path, fList[i]).isDirectory() ?
R.drawable.ic_folder : R.drawable.ic_file); //set icon, directory or file
if (!rootDir) {
Item temp[] = new Item[fileList.length + 1];
System.arraycopy(fileList, 0, temp, 1, fileList.length);
temp[0] = new Item(upTitle, R.drawable.ic_undo);
fileList = temp;
}
}
} else
path = new File(String.valueOf(Environment.getExternalStorageDirectory()));
try {
adapter = new ArrayAdapter<Item>(activity,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = view.findViewById(android.R.id.text1);
textView.setTextColor(Color.WHITE);
// 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 * activity.getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
} catch (Exception e) {
e.printStackTrace();
}
}
private class Item {
public String file;
public int icon;
private Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
public interface Listener {
void onSelectedPath(String path);
}
}

Can't find method on extension class:

Hi Im making an android native extension in Gamemaker: Studio and when I run the game and try to use the extension i get this error code in the runner command window:
Can't find method on extension class:folderLoader[double, double]
It does not crash the game or throw any other errors, it just can't find my method in the java file. this is how I have it set up:
edit extension package properties-general tab-
name- DirectoryPicker
android checkbox ticked
inject to manifest-
<activity
android:name="${YYAndroidPackageName}.DirectoryPicker"
android:label="DirectoryPicker" />
inject to gradle (to activate my styles.xml)-
compile 'com.android.support:appcompat-v7:+'
edit extension package properties-android tab-
Class name- DirectoryPicker
Permissions- android.permission.WRITE_EXTERNAL_STORAGE
edit extension file properties box-
name- DirectoryPicker.extension.gmx
init function- set to folderLoader
copys to- ticked android and android yyc boxes only
edit extension functions box-
name- folderLoader
external name- folderLoader
help- folderLoader(double FolderOnly, double ShowHidden)
return type box- selected double
key and value box- argument 0 double argument1 double
the calling code for an object's left mouse pressed event:
folderLoader(1.0, 0.0);
the async event in the same object (set to social event):
var type2 = string(async_load[? "type2"])
var data2 = string(async_load[? "folder"])
if type2 == "folderFound"
{
var text = data2;
}
the java file- named DirectoryPicker.java
package ${YYAndroidPackageName};
import ${YYAndroidPackageName}.R;
import ${YYAndroidPackageName}.RunnerActivity;
import com.yoyogames.runner.RunnerJNILib;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class DirectoryPicker extends ListActivity {
private static final int EVENT_OTHER_SOCIAL = 70;
public static final String ONLY_DIRS = "onlyDirs";
public static final String SHOW_HIDDEN = "showHidden";
public static final String CHOSEN_DIRECTORY = "chosenDir";
public static final int PICK_DIRECTORY = 43522432;
private File dir;
private boolean onlyDirs = true;
private boolean showHidden = false;
public void folderLoader(double yesOrNo,double noOrYes)
{
if(yesOrNo == 0.0) onlyDirs = false;
if(yesOrNo == 1.0) onlyDirs = true;
if(noOrYes == 0.0) showHidden = false;
if(noOrYes == 1.0) showHidden = true;
findFolders();
}
public void findFolders() {
Bundle extras = getIntent().getExtras();
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
dir = new File(Root.getAbsolutePath());
}
if (extras != null) {
showHidden = extras.getBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.getBoolean(ONLY_DIRS, true);
}
setContentView(R.layout.chooser_list);
setTitle(dir.getAbsolutePath());
Button btnChoose = (Button) findViewById(R.id.btnChoose);
String name = dir.getName();
if(name.length() == 0)
name = "No folders found";
btnChoose.setText(name);
btnChoose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
returnDir(dir.getAbsolutePath());
}
});
ListView lv = getListView();
lv.setTextFilterEnabled(true);
if(!dir.canRead()) {
Context context = getApplicationContext();
String msg = "Could not read folders.";
Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
toast.show();
return;
}
final ArrayList<File> files = filter(dir.listFiles(), onlyDirs, showHidden);
String[] names = names(files);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, names));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!files.get(position).isDirectory())
return;
String path = files.get(position).getAbsolutePath();
Intent intent = new Intent((RunnerActivity.CurrentActivity), DirectoryPicker.class);
intent.putExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.putExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
(RunnerActivity.CurrentActivity).startActivityForResult(intent, PICK_DIRECTORY);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_DIRECTORY && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
String path = (String) extras.get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
int dsMapIndex = RunnerJNILib.jCreateDsMap(null, null, null);
RunnerJNILib.DsMapAddString( dsMapIndex, "type2", "folderFound" );
RunnerJNILib.DsMapAddString( dsMapIndex, "folder", path );
RunnerJNILib.CreateAsynEventWithDSMap(dsMapIndex, EVENT_OTHER_SOCIAL);
}
}
private void returnDir(String path) {
Intent result = new Intent();
result.putExtra(CHOSEN_DIRECTORY, path);
setResult(RESULT_OK, result);
finish();
}
public ArrayList<File> filter(File[] file_list, boolean onlyDirs, boolean showHidden) {
ArrayList<File> files = new ArrayList<File>();
for(File file: file_list) {
if(onlyDirs && !file.isDirectory())
continue;
if(!showHidden && file.isHidden())
continue;
files.add(file);
}
Collections.sort(files);
return files;
}
public String[] names(ArrayList<File> files) {
String[] names = new String[files.size()];
int i = 0;
for(File file: files) {
names[i] = file.getName();
i++;
}
return names;
}
}
There are 2 related xml files that i put in the layout folder which i put in the res folder, which is in the AndroidSource folder.
I have also downloaded some extensions to see how they did them, and they all have a file in the android source folder called yymanifest.xml, which is generated by gamemaker, this file never gets created in my extension project, I've tried saving, exporting the extension and re importing it but the file is never there, and it's not a file you can make yourself, gamemaker has to produce it when it makes the extension, but how can I get it to do this???
Any ideas or help would be greatly appreciated
Well everything seems fine you need to mention you folder in menifest file.

Android - no app found to open link within Edittext

If I click on the HYPERLINK, I get a dialog with the message that no app was found to handle this link, but I know that my android device has some applications to handle this file, becuase I open this file already by click the file itself. Here the code snippet:
case DragEvent.ACTION_DROP:
final String DATA = event.getClipData().getItemAt(0).getText().toString();
final String RECORDS_DIR = ((ScribeApplication ) getApplication()).RECORDS_DIRECTORY_ABSOLUTE_PATH;
final Spanned HYPERLINK = Html.fromHtml("" + RECORDS_DIR + DATA + "");
editor.setMovementMethod(LinkMovementMethod.getInstance());
if (editor.length() > 0)
{
editor.append("\n");
editor.append(HYPERLINK);
}
else
editor.append(HYPERLINK);
return true;
DATA is the file name e.g. record1.3pg
RECORDS_DIR is the absolute path to the directory with the recording files.
HYPERLINK is the absolute path of a record file.
editor is an instance of Eidttext
As mentioned above, if I navigate to the records directory and click the record file itself I get an app chooser and can select an app to handle this record file. So what I did wrong that I dont get an app chooser by clicking the hyperlink within the edittext but rather an dialog with the failure that no app was found?
Many thanks in advance!
Here is my solution for the issue described by CommonsWare:
public class ClickableIntentURLSpan extends URLSpan
{
private Context context;
private Intent intent;
public ClickableIntentURLSpan(final Context CONTEXT, final String URL, final Intent INTENT)
{
super(URL);
final boolean INPUT_OK = (CONTEXT != null) && (INTENT != null);
if (INPUT_OK)
{
context = CONTEXT;
intent = INTENT;
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
else
throw new IllegalArgumentException("Illegal refer to null.");
}
#Override
public void onClick(final View VIEW)
{
context.startActivity(intent);
}
}
case DragEvent.ACTION_DROP:
final String DATA = event.getClipData().getItemAt(0).getText().toString();
final String RECORDS_DIR = ((ScribeApplication ) getApplication()).RECORDS_DIRECTORY_ABSOLUTE_PATH;
final String ABSOLUTE_URL = "file://" + RECORDS_DIR + '/' + DATA;
final Intent PLAY_RECORD_INTENT = new Intent(Intent.ACTION_VIEW);
final File RECORD_FILE = new File(RECORDS_DIR, DATA);
PLAY_RECORD_INTENT.setDataAndType(Uri.fromFile(RECORD_FILE), "audio/*");
final ClickableIntentURLSpan INTENT_URL = new ClickableIntentURLSpan(getApplicationContext(), ABSOLUTE_URL, PLAY_RECORD_INTENT);
final SpannableString HYPERLINK = new SpannableString(DATA);
HYPERLINK.setSpan(INTENT_URL, 0, DATA.length(), 0);
editor.setMovementMethod(LinkMovementMethod.getInstance());
if (editor.length() > 0)
{
editor.append("\n");
editor.append(HYPERLINK);
}
else
editor.append(HYPERLINK);
return true;

How to select a file from Android Emulator?

These are the codes which appeared to have no error but activity stops when I clicked on the Select File button. I wish to upload a file to Amazon S3 but I have to choose a file before uploading. The File I wish to upload is from "Downloads" of the emulator.
Anyone know what's wrong?
package sit.nyp.edu.sg.filepicker;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class FilePicker2Activity extends Activity {
/** Called when the activity is first created. */
TextView textFile, textFileName, textFolder;
TextView textFileName_WithoutExt, textFileName_Ext;
private static final int PICKFILE_RESULT_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPick = (Button)findViewById(R.id.buttonpick);
textFile = (TextView)findViewById(R.id.textfile);
textFolder = (TextView)findViewById(R.id.textfolder);
textFileName = (TextView)findViewById(R.id.textfilename);
textFileName_WithoutExt = (TextView)findViewById(R.id.textfilename_withoutext);
textFileName_Ext = (TextView)findViewById(R.id.textfilename_ext);
buttonPick.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_PICK);
intent.setType("file/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
String FilePath = data.getData().getPath();
String FileName = data.getData().getLastPathSegment();
int lastPos = FilePath.length() - FileName.length();
String Folder = FilePath.substring(0, lastPos);
textFile.setText("Full Path: \n" + FilePath + "\n");
textFolder.setText("Folder: \n" + Folder + "\n");
textFileName.setText("File Name: \n" + FileName + "\n");
filename thisFile = new filename(FileName);
textFileName_WithoutExt.setText("Filename without Ext: " + thisFile.getFilename_Without_Ext());
textFileName_Ext.setText("Ext: " + thisFile.getExt());
}
break;
}
}
private class filename{
String filename_Without_Ext = "";
String ext = "";
filename(String file){
int dotposition= file.lastIndexOf(".");
filename_Without_Ext = file.substring(0,dotposition);
ext = file.substring(dotposition + 1, file.length());
}
String getFilename_Without_Ext(){
return filename_Without_Ext;
}
String getExt(){
return ext;
}
}
}
My guess is that, you dont have any file browser apps which can handle get content intent on the emulator, though if you post the log , can come to conclusion clearly.

Categories

Resources