Walking a DocumentFile tree - android

I'm trying to walk an Android DocumentFile tree recursively but I cannot get a list of files to be returned for a subfolder. When I attempt listFiles() on the folder URI, I get the list of root files returned each time.
Why is this not working?
package com.example.usbfoldertest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "USBFolderTest";
private static final int RQS_OPEN_DOCUMENT_TREE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, RQS_OPEN_DOCUMENT_TREE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE){
Uri uriTree = data.getData();
Log.d(TAG, "WalkTree: " + uriTree.toString() );
WalkTree( uriTree );
}
super.onActivityResult(requestCode,resultCode,data);
}
private void WalkTree( Uri uriTop ) {
Log.d( TAG, "LoadFileList: " + uriTop.toString() );
DocumentFile documentFile = DocumentFile.fromTreeUri(this, uriTop);
DocumentFile files[] = documentFile.listFiles();
if( files == null ) {
Log.d( TAG, "files is null in LoadFileList()" );
} else {
for( DocumentFile f : files ) {
if( f.isDirectory() ) {
Log.d( TAG, "FOLDER: " + f.getName());
if( f.getName().toLowerCase().contains("lost.dir") ) {
Log.d( TAG, "IGNORE LOST.DIR");
} else {
// Recurse into the folder..
WalkTree( f.getUri() );
}
} else {
Log.d( TAG, "FILE: " + f.getName());
}
}
}
}
}

It looks as though upgrading the documentfile library fixes the problem. I add this to my build.gradle and it works as expected now:
implementation 'androidx.documentfile:documentfile:1.0.1'

Related

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.

How to get the file extension in 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"

user select image and detect colour

package com.example.hello;
//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
* This activity displays the gallery image picker.
* It displays the image that was picked.
*
* #author ITCuties
*
*/
public class GalleryActivity extends Activity implements OnClickListener {
// Image loading result to pass to startActivityForResult method.
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
// Find references to the GUI objects
button = (Button)findViewById(R.id.button);
image = (ImageView)findViewById(R.id.image);
// Set button's onClick listener object.
button.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
#Override
public void onClick(View v) {
// Create the Intent for Image Gallery.
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i, LOAD_IMAGE_RESULTS);
}
}
this code select image from gallery ..
package com.example.hello;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
public class ColourPickerActivity extends Activity {
TextView touchedXY, invertedXY, imgSize, colorRGB;
ImageView imgSource1, imgSource2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colourpicker);
// touchedXY = (TextView)findViewById(R.id.xy);
// invertedXY = (TextView)findViewById(R.id.invertedxy);
// imgSize = (TextView)findViewById(R.id.size);
colorRGB = (TextView)findViewById(R.id.colorrgb);
// imgSource1 = (ImageView)findViewById(R.id.source1);
imgSource2 = (ImageView)findViewById(R.id.source2);
//imgSource1.setOnTouchListener(imgSourceOnTouchListener);
imgSource2.setOnTouchListener(imgSourceOnTouchListener);
}
OnTouchListener imgSourceOnTouchListener
= new OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] {eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView)view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int)eventXY[0]);
int y = Integer.valueOf((int)eventXY[1]);
// touchedXY.setText(
// "touched position: "
// + String.valueOf(eventX) + " / "
// + String.valueOf(eventY));
// invertedXY.setText(
// "touched position: "
// + String.valueOf(x) + " / "
// + String.valueOf(y));
Drawable imgDrawable = ((ImageView)view).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
// imgSize.setText(
// "drawable size: "
// + String.valueOf(bitmap.getWidth()) + " / "
// + String.valueOf(bitmap.getHeight()));
//Limit x, y range within bitmap
// if(x < 0){
// x = 0;
// }else if(x > bitmap.getWidth()-1){
// x = bitmap.getWidth()-1;
// }
//
// if(y < 0){
// y = 0;
// }else if(y > bitmap.getHeight()-1){
// y = bitmap.getHeight()-1;
// }
int touchedRGB = bitmap.getPixel(x, y);
colorRGB.setText("touched color: " + "#" + Integer.toHexString(touchedRGB));
colorRGB.setTextColor(touchedRGB);
return true;
}};
}
this code tell colour of pixel on touch of image which is in drawable folder .. how can i integrate these two activities .. i want to select image from gallery and apply colour detector on this image which is selected from gallery
Firs you'll need to call the second class from the fist one inside onActivityResult, adding the imagePath to the Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
(previous code)
Intent intent = new Intent(this, ColourPickerActivity.class);
intent.putExtra("IMAGE_PATH", imagePath);
startActivity(intent)
}
}
Then in your ColourPickerActivity you'll need to extract that path and load it into your ImageView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(previous code)
String imagePath = getIntent().getStringExtra("IMAGE_PATH");
//Load image into the ImageView
imgSource2.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
Hope that helps, cheers!

Droid RAZR M Camera Freezes when invoked via ACTION_IMAGE_CAPTURE Intent

I'm having trouble invoking the built-in camera app on my Droid Razr M using an ACTION_IMAGE_CAPTURE Intent on ICS and was hoping someone else has seen this and knows how to solve/work-around the issue.
My app launches the Camera, waits for the user to capture and accept the image, then processes it upon return. But note that there is NO processing of the image in the sample app, below, and the problem still happens. The key element here is that we immediately re-invoke the camera upon the return from the Intent, to allow the user to continue taking pictures, one after another. This has been working fine on many devices (more than a dozen different devices) but fails on the Droid Razr M running 4.1.2 (as well as earlier versions of ICS). The failure manifests after taking the second photo -- all of the buttons on the camera become disabled and only the back button works. The problem does not happen if we put in a delay of 5 or more seconds in our app before relaunching the Intent -- but that is unacceptable.
Here's a simple repro app that demonstrates the problem (note that you will need to enable the WRITE_EXTERNAL_STORAGE permission for this to work):
public class MainActivity extends Activity {
private static final int RESPONSE_SINGLE_SHOT = 45;
private static final String TAG = "CameraTest";
private String mCameraFilePath = null;
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
onLaunchCamera( true ); //The launch is here only for simplification - it also fails in onStart()
}
#Override
protected void onActivityResult( final int requestCode, final int resultCode, final Intent intent )
{
super.onActivityResult(requestCode, resultCode, intent);
processImage( requestCode, resultCode, intent );
}
public void onLaunchCamera( boolean fromUserAction )
{
final String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED))
{
final Intent cameraIntent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
cameraIntent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET );
final List<ResolveInfo> list = getPackageManager().queryIntentActivities( cameraIntent, 0 );
//Grab the first camera in the list, this should be the camera app that came with the device:
final String packageName = list.get(0).activityInfo.packageName;
final String name = list.get(0).activityInfo.name;
final File publicDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM );
final Time t = new Time();
t.setToNow();
File cameraFile = new File( publicDir, "/Camera/" + makePhotoFileName( t ) );
mCameraFilePath = cameraFile.getAbsolutePath();
Log.i( TAG, "creating camera file: " + mCameraFilePath );
try
{
if ( cameraFile.exists() == false )
{
cameraFile.getParentFile().mkdirs();
if ( cameraFile.createNewFile() )
{
cameraIntent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( cameraFile ) );
} else {
Log.e( TAG, "failed to create file:" + cameraFile.getAbsolutePath() );
return;
}
}
} catch ( IOException e )
{
Log.e( TAG, "Could not create file.", e );
return;
}
cameraIntent.setComponent( new ComponentName( packageName, name ) );
startActivityForResult( cameraIntent, RESPONSE_SINGLE_SHOT );
} else {
Log.e(TAG, "SD card not present");
}
}
private void processImage( final int requestCode, final int resultCode, final Intent intent ) {
switch (requestCode)
{
case RESPONSE_SINGLE_SHOT:
if ( resultCode == RESULT_OK )
{
runOnUiThread( new Runnable() {
#Override
public void run() {
onLaunchCamera( false ); //Immediately re-run camera
}
});
}
else {
// delete the placeholder file we created
if ( mCameraFilePath != null ) {
final File cameraFile = new File( mCameraFilePath );
cameraFile.delete();
mCameraFilePath = null;
}
}
break;
default:
break;
}
}
private String makePhotoFileName( final Time t ) {
final String fileName = t.format("IMG_%Y%m%d_%H%M%S") + ".jpg";
return fileName;
}
}
Any help is greatly appreciated.
The only solution that we've been able to come up with for the default camera on the Razr M is to not immediately return to the camera after capturing an image. We did this by inserting the following code just before the try-catch block in onLaunchCamera():
if ( !fromUserAction && name.equals( "com.motorola.camera.Camera" ) && Build.MODEL.equals( "XT907" ) )
return;
This is just a work-around, but does keep the camera from hanging up.

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