I am a newbie in android app development. I have a simple question. I googled about it but couldn't find any satisfactory answer. My question is :
Can we copy and move images to another folder using startactivityforresult() method. If yes, then how can we pass the position of the selected images we want to move or copy ?
Thanks
In your main activity:
Create new ArrayList to hold selected images:
ArrayList<Model_images> selectedImages = new ArrayList<Model_Images>();
Add all selected images to selectedImages in your adapter's
onClick using:
selectedImages.add(al_images.get(position));
Then once you have the list of selected images, Build the intent and
call the activity:
Intent moveIntent = new Intent(this, MoveActivity.class);
moveIntent.putExtra("selected_images", selectedImages);
startActivityForResult(moveIntent, REQUEST_CODE); // REQUEST_CODE is a unique int value within your app for this intent.
Override onActivityResult to receive the response:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed(REQUEST_CODE)
if(requestCode==REQUEST_CODE)
{
if (resultCode == RESULT_OK){
//The called activity completed successfully.
String message=data.getStringExtra("MESSAGE"); //The message passed along with result
}
}
}
In your MoveActivity activity:
Get the passed ArrayList:
ArrayList<model_Images> selectedImages = new ArrayList<Model_Images>();
if(getIntent().getSerializableExtra("selected_images") != null)
selectedImages = getIntent().getSerializableExtra("selected_images");
Move the images to destination folder:
//Move each selected file to destination
for (Model_Images image : selectedImages{
File sourceImage = image.getFile(); //returns the image File from model class to be moved.
File destinationImage = new File("path/to/destination", "filename.extension");
moveFile(sourceImage, destinationImage);
}
//Method to move the file
private void moveFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
source.delete();
}
Set the result to calling activity once done:
// Set result back to the calling activity
Intent intent=new Intent();
intent.putExtra("MESSAGE",message); // Set a message for the calling activity
setResult(RESULT_OK,intent); //RESULT_OK represents success result
finish();//finishing activity
P.S: handling storage permission is not discussed and is required to read/write.
Related
I can't get the normal taken picture by my phone in java. Everything is working while I choose picture from the gallery which is screenshot but when It's normal taken picture it's not returning anything. I will give you some parts of the code where u can see how I'm getting picture.
#Override
public void onActivityResult(int reqCode, int resultCode, final Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
final Uri imageUri = data.getData();
final String path = getPath(getActivity(), imageUri);
if (path != null) {
try {
File f1 = new File(path);
final AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
client.addHeader("accept", "application/json");
final RequestParams params = new RequestParams();
params.put("id", id);
params.put("token", token);
params.put("avatar", f1);
And also this
add_avatar.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
// filePickUtils.requestImageGallery(STORAGE_PERMISSION_IMAGE, true, true);
if (getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
if (getActivity().checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
photoPickerIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PICK_IMAGE);
}
});
What would you suggest?
Thanks for your help
Given that you only need to read the image, and upload the data to your backend server, I'd suggest if you use Intent.ACTION_GET_CONTENT instead of Intent.ACTION_PICK.
Why
Your problem might related to what Intent.ACTION_PICK needs to have. The documentation stated:
Input: getData() is URI containing a directory of data (vnd.android.cursor.dir/*) from which to pick an item.
So it means, if you want to use Intent.ACTION_PICK, you need to provide the directory of the data.
Meanwhile if you use Intent.ACTION_GET_CONTENT, you can just set the MIME type of the file that you want to search (just as what you are doing now), and use Context.startActivity(intent).
Additional note from the documentation that you might want to read:
Input: getType() is the desired MIME type to retrieve. Note that no URI is supplied in the intent, as there are no constraints on where the returned data originally comes from. You may also include the CATEGORY_OPENABLE if you can only accept data that can be opened as a stream. You may use EXTRA_LOCAL_ONLY to limit content selection to local data. You may use EXTRA_ALLOW_MULTIPLE to allow the user to select multiple items.
Output: The URI of the item that was picked. This must be a content: URI so that any receiver can access it.
Add a comment here, if you need further information.
Sample Code:
In your activity
private searchImageFile() {
Intent intent = new Intent(Intent.GET_CONTENT);
// Filter to only show results that can be "opened"
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only images, using the image MIME data type.
// it would be "*/*".
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
final Uri imageUri = resultData.getData();
//Do something with your Uri.
}
}
I am trying to capture an image and then display it on the screen using another activity. I am able to successfully capture the images and save them in my desired directory. However, even after hours of struggle, I am still unable to solve this problem. The touch listener is added to the screen though there's no image.
Here's the code:
private void takeImage(){ Intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, PHOTO_TAKEN); }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PHOTO_TAKEN){
data.putExtra(SET_CAPTURED_IMAGE, true);
} else{
Log.d(MainActivity.DEBUGTAG, "Photo = null");
}
}
Now in another activity (ImageActivity):
addTouchListener() is called in onCreate() method of this activity.
Till here, the image is successfully captured and saved in the directory.
private void addTouchListener(){
ImageView imageView = (ImageView)findViewById(R.id.unlocker_image);
Bundle extras = getIntent().getExtras();
//The following if block is not executed
if (extras != null && extras.getBoolean(MainActivity.SET_CAPTURED_IMAGE)){
Uri imageUri= Uri.parse(extras.getString(MediaStore.EXTRA_OUTPUT));
imageView.setImageURI(imageUri);
} else {
imageView.setImageResource(R.drawable.unlocker_image);
//this is the default image added
}
imageView.setOnTouchListener(collector);
}
At this point, the touch listener is added but there's no image.
Right now I've got an app that takes a photo via an intent. After taking the photo, I want the user to be able to confirm it and push the photo to another activity where they can add details. I'm struggling to find the correct way to pass the photo from activity to activity.
Right now, confirming the photo brings the user back to the main activity.
Here's my relevant code:
Main Activity
public void takePhoto(View view) {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Log.d("MySecondApp",fileUri.toString());// create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data!=null) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MySecondApp");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MySecondApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
I would try something like
if(resultCode == Activity.RESULT_OK)
handleCameraPhoto(data);
handle method:
private void handleCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", mImageBitmap);
startActivity(intent);
}
and then, retrieve it in your other activity
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
and assign it to your ImageView
ImageView iv = (ImageView)findViewById(R.id.myImageView);
iv.setImageBitmap(bitmap);
Make a constructor in your new class that takes an intent or even the image:
class newClass {
public newClass(Intent intent){
...
}
...
}
And then just make the intent the size of a thumbnail in this new class where you can do the confirmation in a popup or something similar and then have the information to be filled on the page for this class. This will also be better because if they wanted to retake the picture you could have this class which they are taken to after the picture is taken if not accepted go to take another picture.
Take a look at this blog post I wrote on how to take a full size image and a thumbnail version as well:
Use Camera Activity for Thumbnail and Full Size Image
after you did that you can extract the file path of the saved file from the file instance using getAbsolutePath() method and pass it to the following Activity.
in my android application I want to copy file from one directory to another , I have the path of file filePath , and have the path of directory dirPath in what I must copy the file. I tried many ways , but nothing helped , some ways only make some empty(0 kb) file with strange name different from the name of my file. SO help please :)
here is some part of code, if it help's you, I have two buttons for Gallery and for Camera , and I must pick images from there
Button btnCam = (Button) dialog.findViewById(R.id.btncamera);
btnCam.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.cancel();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2500);
}
});
//end of camera button
Button btnGal = (Button) dialog.findViewById(R.id.btngalary);
btnGal.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.cancel();
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
and Activity Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
url = new String(selectedImage.toString());
//here I must copy file with path `selectedImage` and replace it in
// directory with path `currentDir.hetPath()`
}
if (requestCode == 2500)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
//here I must do the same thing above
}
}
I found some way , in my Activity result I must call copyFile(String, String) function , here is the body
public static boolean copyFile(String from, String to) {
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
int end = from.toString().lastIndexOf("/");
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+1, from.length());
File source = new File(str1, str2);
File destination= new File(to, str2);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
return true;
} catch (Exception e) {
return false;
}
}
If you feel up to it, you can include Apache Commons I/O in your app. I don't know how big it is. See Standard concise way to copy a file in Java?
Or maybe you could download the source, and cherry-pick the source to FileUtils.copyFile()
I'm trying to get a program to let the user to import a custom background.
Here's where I'm at:
I have the getDrawable function taking another function as an argument:
mDrawableBg = getResources().getDrawable(getImage());
getImage() is suppose to return a integer referencing the selected image, here is the code (so far) for that function:
public int getImage(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 10);
}
This is suppose to open the gallery and let the user select an image. I would then use mDrawableBg to set the background. I'm not sure how to return a reference ID to that selected image though. Any suggestions?
Try this:
String pathName = "selected Image path";
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
BitmapDrawable bd = new BitmapDrawable(res, bitmap);
View view = findViewById(R.id.container);
view.setBackgroundDrawable(bd);
The way you're attempting to do it is not possible, I'm afraid. One of the things you'll want to learn as a new Android developer is how the cycle between activities works. In your case, you're running an Activity that calls upon an Intent to get data from it. However, in the Android API, an Intent can only be referenced on its own time. This means you can't use your getImage() method the way you had tried.
There is hope, though!
What you first need to do is call the Intent. You will do this through the code you have now in getImage():
public void getImage() { // This has to be a void!
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 10);
}
This method will now start the Image Picker that you want users to select from. Next, you have to catch what is returned. This cannot be returned from your getImage() method, but instead must be collected from elsewhere.
You must implement the below method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
final int SELECT_PICTURE = 1; // Hardcoded from API
if (requestCode == SELECT_PICTURE) {
String pathToImage = data.getData().getPath(); // Get path to image, returned by the image picker Intent
mDrawableBg = Drawable.createFromPath(pathToImage); // Get a Drawable from the path
}
}
}
Lastly, instead of calling mDrawableBg = getResources().getDrawable(getImage());, just call getImage();. This will initialize the Image Picker.
Some reading:
Android Activity (notably stuff about Intents and getting a result back)
Android Drawable
Getting a Drawable from a path
More on the Image Picker Intent
Good luck!
I'm not sure, but if you mean you don't know how to receive results from that intent, you can use :
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
if (requestCode == 10)
{
// DoSomething
}
}
}