I have a filechooser that I call in a webview in order to upload a file.
The method allowing me to retrieve the file in my filechooser activity is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Option o = adapter.getItem(position);
if (o.isFolder() || o.isParent()) {
currentDir = new File(o.getPath());
fill(currentDir);
} else {
//onFileClick(o);
fileSelected = new File(o.getPath());
Intent intent = new Intent();
intent.putExtra("fileSelected", fileSelected.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
finish();
}
}
This only allows me to get the path in the onActivityResult of my webview (which calls my filechooser to upload file).
The method onActivityResult is given by the code below.
If I use another application installed in my phone other than my filechooser I use :
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
then the result is sent by:
this.mUploadMessage.onReceiveValue(uri);
Since then, it works normally. But with my filechooser intent.getData () equals to null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
if (resultCode != RESULT_OK) {
mUploadMessage.onReceiveValue(null);
var = 0;
return;
}
// Toast.makeText(getApplicationContext() , "onActivityResult()" + String.valueOf(requestCode) ,Toast.LENGTH_LONG).show();
// Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
// this.mUploadMessage = null;
String fileSelected = intent.getStringExtra("fileSelected");
Bundle result = intent.getExtras();
//result = Uri.parse(fileSelected);
//this.mUploadMessage.onReceiveValue(result);
if (resultCode == RESULT_OK) {
if (intent != null) {
// Get the URI of the selected file
final Uri uri = intent.getData();
Log.i("TOTOTOT", "Uri = " + uri.toString());
Toast.makeText(this, fileSelected + " " + uri.toString() , Toast.LENGTH_SHORT).show();
this.mUploadMessage.onReceiveValue(uri);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
What should I return in my two methods in order to retrieve both data and path, not only the path of the sent file ? Should it be all the bundle or do you know how to get Data while using Intent.getData()?
What is need to get data from directory selected inside onActivityResult()
You got path selected so you can read file from there which you want ..
Use this method to read file as a string
private String readURLFromPath(File filePath){
String dataString = "";
// i have kept text.txt in the sd-card
if (file.exists()) // check if file exist
{
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e){
// You'll need to add proper error handling here
}
// Set the text
dataString = text.toString();
}
return dataString ;
}
this method will return data as a string now you can send this string data on server...
the solution is to Get content uri from file path in android as mentioned Get content uri from file path
Related
On huawei honor 8 with android 7.0 the uri.getPath() returns something like /external/file/3344 instead of real path of the file.This code also works fine on many devices and also on android emulator with android 7.0 and uri.getPath() returns /storage/emulated/0/PCalculator/main.js but not on honor 8. I used Intent to choose a file in my program as below :
private void fileBrowse(){
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser
(intent,"Open File"),RCODE_OPENFILE);
}
And in onActivityResult I want to read the file as below :
public void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode,resultCode,data);
switch(requestCode){
case RCODE_OPENFILE:
if(resultCode == RESULT_OK &&
data != null && data.getData() != null){
fileOpen(data.getData());
}
break;
}
}
And the fileOpen function :
private void fileOpen(Uri uri){
File mFile = new File(uri.getPath());
StringBuilder mText = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(mFile));
String line;
while ((line = br.readLine()) != null) {
mText.append(line);
mText.append('\n');
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
etCode.setText(mText);
tvTitle.setText(mFile.getName());
}
I've created a basic activity with an imageView and two buttons. 1 Button opens the gallery, the other opens the camera. Both of which pass the result into a image cropping library. The cropped image is saved and shown in the imageView.
The first I do this with either button, everything works smoothly. However on the second attempt the imageView does not get replaced but the image that has been saved has changed.
So basically the imageView doesn't change to the new image if it already has the first result.
Here's Code:
public void takeDisplayPicture(View view) {
final String TAKE_DISPLAY_PICTURE = "Take Display Picture";
Log.d(TAKE_DISPLAY_PICTURE, "Clicked");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e(TAKE_DISPLAY_PICTURE, "Error Occurred");
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
Log.d(TAKE_DISPLAY_PICTURE, photoFile.getAbsolutePath());
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
} else {
Log.d(TAKE_DISPLAY_PICTURE, "No Camera");
Toast.makeText(getApplicationContext(),"No Camera Available",Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
final String ON_ACTIVITY_RESULT = "On Activity Result";
Log.d(ON_ACTIVITY_RESULT, "Triggered");
Log.d(ON_ACTIVITY_RESULT, "Request Code: "+Integer.toString(requestCode)+" Result Code: "+Integer.toString(resultCode));
Uri img = Uri.parse("file:///"+Config.APP_PATH+Config.APP_USER_PATH+"/"+Config.DISPLAY_PICTURE_NAME+".png");
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Log.d(ON_ACTIVITY_RESULT, "Beginning Crop");
Log.d(ON_ACTIVITY_RESULT,img.toString());
beginCrop(img, img);
} else if (requestCode == Crop.REQUEST_CROP) {
Log.d(ON_ACTIVITY_RESULT, "Handling Crop");
handleCrop(resultCode, result);
} else if (requestCode == 2){
Log.d(ON_ACTIVITY_RESULT, "Gallery Image Returned");
File file = new File(img.getPath());
file.delete();
Uri src = result.getData();
Log.d(ON_ACTIVITY_RESULT, src.toString());
beginCrop(src, img);
}
}
private void beginCrop(Uri source, Uri output){
final String BEGIN_CROP = "Begin Crop";
Log.d(BEGIN_CROP, "Beginning");
new Crop(source).output(output).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
final String HANDLE_CROP = "Handle Crop";
if (resultCode == RESULT_OK) {
Log.d(HANDLE_CROP, "Set ImageView");
displayPicture.setImageURI(Crop.getOutput(result));
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Crop.getOutput(result));
} catch (Exception e ){
Log.d(HANDLE_CROP, "Error Occurred");
}
} else if (resultCode == Crop.RESULT_ERROR) {
Log.d(HANDLE_CROP, "Error Occurred");
}
}
String currentPhotoPath;
private File createImageFile() throws IOException {
final String CREATE_IMAGE_FILE = "Create Image File";
String fileName = "display_picture";
File dir = new File(Config.APP_PATH+Config.APP_USER_PATH);
dir.mkdirs();
File image = new File(dir,fileName+".png");
return image;
}
public void chooseFromGallery(View view) {
final String CHOOSE_FROM_GALLERY = "Choose From Gallery";
Log.d(CHOOSE_FROM_GALLERY, "Clicked");
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
If you read setImageURI:
if (mResource != 0 ||
(mUri != uri &&
(uri == null || mUri == null || !uri.equals(mUri)))) {
//Set URI...
}
Basically, setImageURI only works if the Uri of the image isn't equal to the Uri you want to currently set. Your button doesn't work second time because Crop.getOutput(result) returns the same Uri everytime you press the button, so setImageURI does nothing.
To solve this, you can add displayPicture.setImageURI(null); before displayPicture.setImageURI(Crop.getOutput(result));.
I'm trying to set an 'EditText' to the contents of a simple txt file. After looking at the developer page I stumbled across some code that gets a photo. I edited to what I thought would suit my needs but it doesn't work:
private void importText(){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("text/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
String textContent = data.getDataString();
mEditText.setText(textContent);
}
}
What this does is it puts the string name of what appears to be the files location in the EditText not the contents of it. My app right now only supports API 19 so I thought I would be able to use this as a feature. Is this function possible using ACTION_OPEN_DOCUMENT or do I need to do something else?
Use following method to read data :
public static String readTextFromUri(Context context, Uri uri) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream =
context.getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(inputStream)))) {
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
}
return stringBuilder.toString();
}
and get uri from given intent in onActivityResult method :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
Uri uri = data.getData();
String myText = readTextFromUri(yourContext , uri);
}
}
You need to retrieve an Input Stream from the Uri as explained in the documentation. (Section "Get an Input Stream").
HI i am getting null pointer exception while sending image path to another activity
here is below my code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
System.out.println(requestCode + ", " + resultCode);
if (requestCode == SELECT_PICTURE) {
if (data.getData() != null) {
Uri selectedImageUri = data.getData();
String path = getPath(selectedImageUri);
System.out.println("PATH = "+path);
Intent _intent = new Intent(MainActivity.this,AndroidFaceDetector.class);
_intent.putExtra("mypath", path);
startActivityForResult(_intent, CROPPED_FACE_IMAGE);
}
else
{
Toast.makeText(MainActivity.this, "Please try again", Toast.LENGTH_SHORT).show();
}
}
else {
setImage(data);
}
}
}
Now in AndroidFaceDetector class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new myView(this));
Intent _intent = getIntent();
path = _intent.getStringExtra("mypath");
System.out.println("Path is gettting "+path); //here i am getting null value
}
because
here i am getting path value null.. can any body solve this problem....
try like this in Second Activity
Intent myintent = getIntent();
if(null != myintent.getExtras())
{
// do your work here
String path = myintent.getExtras().getString("mypath");
}
else
{
// not here you can't get values
Toast.makeText(getApplicationContext(),"No Recor Here..",12).show();
}
In your second activity try with this code instead of yours,
path = _intent.getString("mypath");
(or)
Bundle bundle = this.getIntent().getExtras();
String pic = bundle.getString("mypath");
If you wish to pass image instead of URI means try this code
In your First activity,
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Intent intent = new Intent();
intent.setClass(AndroidPassingBitmap.this, AndroidReceiveBitmap.class);
intent.putExtra("Bitmap", bitmap);
startActivity(intent);
In your Second activity,
Bitmap bitmap = (Bitmap)this.getIntent().getParcelableExtra("Bitmap");
ImageView viewBitmap = (ImageView)findViewById(R.id.bitmapview);
viewBitmap.setImageBitmap(bitmap);
Write below Code to get data from intent, it will solve your problem.
Bundle bdl=getIntent().getExtras();
String path=bdl.getString("mypath");
And see below link for more information.
pass bitmap between activities in android
Hi there is a way to select folder where user want to save file in android . I check out http://code.google.com/p/android-file-dialog/
it has functionality to select file but i want to select folder , please provide me usable link or examples.
How about using OI File Manager? This App has the following Intents: PICK_FILE, PICK_DIRECTORY.
There is even sample code on the page for using the Intents.
I used the same source in my app (pretty sure), and there is a block of code:
protected void onListItemClick(ListView l, View v, int position, long id) {
if (file.isDirectory()) {
selectButton.setEnabled(false);
if (file.canRead()) {
lastPositions.put(currentPath, position);
getDir(path.get(position));
} else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName() + "] "
+ getText(R.string.cant_read_folder))
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
} else {
selectedFile = file;
v.setSelected(true);
selectButton.setEnabled(true);
}
}
You just have to edit how it handle's if (file.isDirectory()). I would recommend declaring a boolean value in your Activity which you change to true if the file is a directory and it is already false. Then if said value is true, then traverse the directory. Also when you change said value to true, you would need to call selectButton.setEnabled(true). This would be quite a bit less complicated than making your own code, I would say.
Check out this answer https://stackoverflow.com/a/28479561/779140
I am mentioned library author so don't hesitate to ask any questions.
I encountered the same issue and I end up using NoNonsense-FilePicker
Add to gradle file
compile 'com.nononsenseapps:filepicker:4.0.0'
Trigger file/folder/dir pick
try {
Utils.makeHepticFeedback(getActivity());
Intent selectDirectoyIntent = new Intent(getActivity(), FilePickerActivity.class);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
startActivityForResult(selectDirectoyIntent, FILE_CODE);
} catch (Exception e) {
Log.e(LOG_TAG, "exception", e);
e.printStackTrace();
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
}
Handle Activity result to get selected file or files
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == CHOOSE_IMAGE_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURI(selectedImageUri);
// NOW WE HAVE OUR WANTED STRING
if (selectedImagePath != null) {
System.out
.println("selectedImagePath is the right one for you!");
PreferenceHelper.getPreferenceHelperInstance().setString(getActivity(),
PreferenceHelper.PLAYER_BACKGROUND,
selectedImageUri.toString());
Glide.with(getActivity()).load(Uri.parse(
PreferenceHelper.getPreferenceHelperInstance().getString(getActivity(),
PreferenceHelper.PLAYER_BACKGROUND
, AppConstants.DEFAULT_BACKGROUND_URL))).
into((ImageView) ButterKnife.findById(getActivity(), R.id.play_back));
}
} else if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) {
if (null != data && !data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
// The URI will now be something like content://PACKAGE-NAME/root/path/to/file
Uri uri = data.getData();
// A utility method is provided to transform the URI to a File object
File file = com.nononsenseapps.filepicker.Utils.getFileForUri(uri);
// If you want a URI which matches the old return value, you can do
Uri fileUri = Uri.fromFile(file);
// Do something with the result...
Snackbar.make(fileFormat, "Recording folder updated to" + fileUri.getPath() + " ¯\\_(ツ)_/¯ ", Snackbar.LENGTH_SHORT).show();
AppConfig.RECORDING_FOLDER = fileUri.getPath();
PreferenceHelper.getPreferenceHelperInstance().setString(getActivity(), PreferenceHelper.RECORDING_FOLDER, AppConfig.RECORDING_FOLDER);
setUpSettingValue();
} else {
// Handling multiple results is one extra step
ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS);
if (paths != null) {
for (String path : paths) {
Uri uri = Uri.parse(path);
// Do something with the URI
File file = com.nononsenseapps.filepicker.Utils.getFileForUri(uri);
// If you want a URI which matches the old return value, you can do
Uri fileUri = Uri.fromFile(file);
// Do something with the result...
Toast.makeText(getActivity(), "Selected dir" + fileUri.getPath(), Toast.LENGTH_SHORT).show();
}
}
}
}
}