Android Java copyFile not working for Gallery Image - java

I have a little camera app that is storing the image to the Pictures folder:
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "preview.jpg");
Later I want to copy this Image and save it with a new Filename. Therefore i used this copy function i found here:
private void copyFile(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();
}
}
The copyFile is called here:
// OLD FILE
File oldFile = new File(imageUri.getPath());
// NEW FILE
File newFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test123.jpg");
// COPY FILE
copyFile(oldFile,newFile);
But it is doing nothing. Also no Exception or something. What am I doing wrong?
EDIT: Full Code
public class ParticipateActivity extends AppCompatActivity {
private static String logtag = "Camera APP";
private static int TAKE_PICTURE = 1;
private Uri imageUri;
private Bitmap cameraImage;
static final String appDirectoryName = "album name";
static final File imageRoot = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageRoot.mkdirs();
verifyStoragePermissions(this);
setContentView(R.layout.activity_participate);
Button cameraButton = (Button) findViewById(R.id.camera_button);
Button saveButton = (Button) findViewById(R.id.save_button);
cameraButton.setOnClickListener(cameraListener);
saveButton.setOnClickListener(saveListener);
}
private View.OnClickListener cameraListener = new View.OnClickListener() {
public void onClick(View v) {
takePhoto(v);
}
};
private View.OnClickListener saveListener = new View.OnClickListener() {
public void onClick(View v) {
try {
savePhoto(v);
} catch (IOException e) {
e.printStackTrace();
Log.e(logtag,"Error copying file!");
}
}
};
private void takePhoto(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(imageRoot, "preview.jpg");
//Log.e(logtag,"test");
imageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PICTURE);
}
private Boolean copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
//Log.e(logtag,sourceFile.getAbsolutePath());
return false;
} else {
//Log.e(logtag,sourceFile.getAbsolutePath());
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
try {
destination.transferFrom(source, 0, source.size());
} catch (Exception e) {
e.printStackTrace();
return false;
}
//source.transferTo(0, source.size(), destination);
Log.e(logtag,"transfer started");
}
if (source != null) {
source.close();
} else {return false;}
if (destination != null) {
destination.close();
return true;
} else {return false;}
}
private void savePhoto(View v) throws IOException {
EditText input_name = (EditText) findViewById(R.id.input_name);
EditText input_mail = (EditText) findViewById(R.id.input_mail);
EditText input_phone = (EditText) findViewById(R.id.input_phone);
String name = input_name.getText().toString();
String mail = input_mail.getText().toString();
String phone = input_phone.getText().toString();
if (name.length() != 0 && mail.length() != 0) {
if (phone.length() == 0) {
phone = "NoPhone";
}
// set fileName
String fileName = name + "-" + mail + "-" + phone;
// Log.e(logtag,fileName);
// OLD FILE
File oldFile = new File(imageUri.getPath());
//Log.e(logtag,"Path: " + imageUri.getPath());
// NEW FILE
File newFile = new File(imageRoot, "test123.jpg");
Log.e(logtag,"path: " + newFile.getAbsolutePath());
// COPY FILE
if(oldFile.exists()) {
Boolean copied = copyFile(oldFile,newFile);
Log.e(logtag,copied.toString());
// log text
if(copied) Toast.makeText(ParticipateActivity.this, "Gespeichert!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ParticipateActivity.this, "Konnte nicht gespeichert werden! Kein Foto?", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(ParticipateActivity.this, "Bitte Name und Email ausfüllen!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.image_camera);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
// Change height of image
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.height = (int) getResources().getDimension(R.dimen.imageView_height);
imageView.setLayoutParams(layoutParams);
// Hide Label and Button
TextView uploadText = (TextView) findViewById(R.id.upload_text);
uploadText.setVisibility(View.GONE);
Button uploadButton = (Button) findViewById(R.id.camera_button);
uploadButton.setVisibility(View.GONE);
// Show Image Name
//Toast.makeText(ParticipateActivity.this,selectedImage.toString(),Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(logtag, e.toString());
}
}
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
* <p>
* If the app does not has permission then the user will be prompted to grant permissions
*
* #param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}

Related

Android Save Video To Gallery

I am developing app using camera on fragment,so for camera I have used this library https://natario1.github.io/CameraView/home because I am using watermarks in camera, now I want to save pictures and videos to gallery, for pictures I have done with below code, for video I done research but not get a solution, for pictures this library is giving bitmap so pictures are saving perfectly but for video I can't figure out kindly help me.
Thank you
public class VideoPreviewActivity extends AppCompatActivity {
private VideoView videoView;
private static VideoResult videoResult;
private Button btnSaveVideo;
public static void setVideoResult(#Nullable VideoResult result) {
videoResult = result;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_preview);
final VideoResult result = videoResult;
if (result == null) {
finish();
return;
}
btnSaveVideo = findViewById(R.id.save_video);
videoView = findViewById(R.id.video);
videoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playVideo();
}
});
AspectRatio ratio = AspectRatio.of(result.getSize());
MediaController controller = new MediaController(this);
controller.setAnchorView(videoView);
controller.setMediaPlayer(videoView);
videoView.setMediaController(controller);
videoView.setVideoURI(Uri.fromFile(result.getFile()));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
ViewGroup.LayoutParams lp = videoView.getLayoutParams();
float videoWidth = mp.getVideoWidth();
float videoHeight = mp.getVideoHeight();
float viewWidth = videoView.getWidth();
lp.height = (int) (viewWidth * (videoHeight / videoWidth));
videoView.setLayoutParams(lp);
playVideo();
if (result.isSnapshot()) {
// Log the real size for debugging reason.
Log.e("VideoPreview", "The video full size is " + videoWidth + "x" + videoHeight);
}
}
});
//Click this button to save video
btnSaveVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Calling 1st Method but not working
//SaveVideo(videoResult.getFile().toString());
//2nd method calling but still not working
saveVideoToInternalStorage(videoResult.getFile().toString());
}
});
}
void playVideo() {
if (!videoView.isPlaying()) {
videoView.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!isChangingConfigurations()) {
setVideoResult(null);
}
}
//first method which I tried but not working
private void SaveVideo(Uri f) {
//I don't know what data type I have to pass in the methods parameters
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath();
File myDir = new File(root + "/Push Videos");
if (!myDir.exists()) {
myDir.mkdirs();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Video-"+ n +".mp4";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
Toast.makeText(VideoPreviewActivity.this, "PUSH Video Saved", Toast.LENGTH_LONG).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//Tried this 2nd method but it is also not giving a desired result
//For saving Video...
private void saveVideoToInternalStorage (String filePath) {
File newfile;
try {
File currentFile = new File(filePath);
String fileName = currentFile.getName();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("videoDir", Context.MODE_PRIVATE);
newfile = new File(directory.getAbsolutePath(), fileName);
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
scanner(filePath);
in.close();
out.close();
Log.v("", "Video file saved successfully.");
Toast.makeText(this, "Push Video Saved TO Gallery", Toast.LENGTH_SHORT).show();
}else{
Log.v("", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
Log.d("Err ", "EXS " + e.getMessage());
e.printStackTrace();
}
}
}

FileNotFoundException: No files supported by provider at content

I have an error whenever I try to take a picture by using camera intent.
This is the error
FileNotFoundException: No files supported by provider at content://com.example.fahad.inventory/my_images/dcim/Inventory/JPEG20170922_170324_1975076666.jpg
at com.example.fahad.inventory.AddProductActivity.getBitmap(AddProductActivity.java:270) 09-22 17:03:30.117 12950-12950/? W/System.err: at com.example.fahad.inventory.AddProductActivity.onActivityResult(AddProductActivity.java:197)
This is my code
public class AddProductActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_SELECT_IMAGE = 2;
private static final String IMAGE_PATH = "imagePath";
private static final String IMAGE_URI = "imageUri";
private static final String BITMAP = "bitmap";
private static final String CAMERA_DIR = "/dcim/";
private String imagePath = "";
private String imageUri = "";
private ImageView imageView;
private Bitmap bitmap;
private Uri mUri;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
Button addProduct = (Button) findViewById(R.id.id_btn_add_product);
Button addImage = (Button) findViewById(R.id.id_btn_add_image);
Button addGalleryImage = (Button) findViewById(R.id.id_btn_add_gallery_image);
imageView = (ImageView) findViewById(R.id.id_image_view);
if (savedInstanceState != null) {
imagePath = savedInstanceState.getString(IMAGE_PATH);
imageUri = savedInstanceState.getString(IMAGE_URI);
bitmap = (Bitmap) savedInstanceState.get(BITMAP);
imageView.setImageBitmap(bitmap);
}
addProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insert();
}
});
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
File f = createImageFile();
mUri = FileProvider.getUriForFile(
AddProductActivity.this, ProductContract.CONTENT_AUTHORITY, f);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
// Solution taken from http://stackoverflow.com/a/18332000/3346625
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, mUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
addGalleryImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
} else {
intent = new Intent(Intent.ACTION_GET_CONTENT);
}
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select image"), REQUEST_SELECT_IMAGE);
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG" + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
return imageF;
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ getString(R.string.app_name));
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
public void insert() {
EditText editProductName = (EditText) findViewById(R.id.id_edit_product_name);
EditText editProductPrice = (EditText) findViewById(R.id.id_edit_product_price);
EditText editProductQuantity = (EditText) findViewById(R.id.id_edit_product_quantity);
String name = editProductName.getText().toString();
String quantity = editProductQuantity.getText().toString();
String price = editProductPrice.getText().toString();
ContentValues values = new ContentValues();
values.put(ProductContract.ProductColumns.PRODUCT_NAME, name);
values.put(ProductContract.ProductColumns.PRODUCT_QUANTITY, quantity);
values.put(ProductContract.ProductColumns.PRODUCT_PRICE, price);
values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_PATH, imagePath);
values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_URI, imagePath);
Uri uri = getContentResolver().insert(ProductContract.ProductColumns.CONTENT_URI, values);
if (uri != null) {
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
imageUri = mUri.getPath();
bitmap = getBitmap(mUri);
imageView.setImageBitmap(bitmap);
} else if (requestCode == REQUEST_SELECT_IMAGE && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final int flags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
ContentResolver contentResolver = getContentResolver();
contentResolver.takePersistableUriPermission(uri, flags);
}
imageView.setImageBitmap(getBitmapFromUri(uri));
imageUri = uri.toString();
imagePath = uri.toString();
}
}
}
public Bitmap getBitmapFromUri(Uri uri) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
fne.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
}
}
}
private Bitmap getBitmap(Uri uri) {
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (parcelFileDescriptor != null) {
parcelFileDescriptor.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(IMAGE_PATH, imagePath);
outState.putString(IMAGE_URI, imageUri);
outState.putParcelable(BITMAP, bitmap);
}
The contentAuthority is my package name.
com.example.fahad.inventory
And this is my paths :
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="my_images" />
</paths>
And this is my provider in manifest :
<provider
android:name=".data.ProductProvider"
android:authorities="com.example.fahad.inventory"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
I have seen some posts like this by I don't understands it. or it didn't help me with my problem.
The error in the logs are pointing to :
getContentResolver().openFileDescriptor(uri, "r");
Also the data returned in onActivityResult from the camera is always null.
I think the problem is I have to implement OpenFile method in my custom contentProvider but the problem I don't know what to write in that method.
Or the getUriForFile return wrong uri.
Please help me I'm in this problem for two weeks now and it seems I'm not going anywhere.
And I'm new to contentProvider.
Thanks in Advance And happy coding !

Android changing google gallery picker to normal gallery picker

i found a code about gallery picker and it pick photos from google images. But i want to pick photos from normal gallery. Here is the code :
public class ImageCrop {
private static final String TAG = "ImageCrop";
private static final boolean REMOVE_TEMP_FILE = true;
private static final boolean DEBUG = false;
Context context;
public static final int PICK_FROM_CAMERA = 0;
public static final int PICK_FROM_ALBUM = 1;
public static final int PERMISSION_FROM_CAMERA = 3;
private static final int PHOTO_SIZE = 1000;
private static final String ACTIVITY_NAME_PHOTOS = "com.google.android.apps.photos";
private static final String ACTIVITY_NAME_PLUS = "com.google.android.apps.plus";
private static boolean mUseActivityPhoto = false;
private static boolean mUseActivityPlus = false;
private static Uri mImageCaptureUri;
private static Bitmap mCropBitmap;
private static String mTempImagePath;
private static int mLastAction = PICK_FROM_CAMERA;
private static final String CAMERA_TEMP_PREFIX = "camera_";
private static final String CROP_TEMP_PREFIX = "crop_";
private static final String IMAGE_EXT = ".png";
public static void checkPackages(Activity context, Intent intentPhoto) {
final PackageManager pm = context.getPackageManager();
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
mUseActivityPhoto = false;
mUseActivityPlus = false;
final List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
for (ResolveInfo info : infos) {
if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
Log.d(TAG,"mUseActivityPhoto TRUE");
mUseActivityPhoto = true;
break;
}
}
}
else if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
Log.d(TAG,"mUseActivityPlus TRUE");
mUseActivityPlus = true;
break;
}
}
}
}
}
public static void takeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeCameraAction");
if (ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeCameraAction(context);
} else {
mLastAction = ImageCrop.PICK_FROM_CAMERA;
}
}
public static void takeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeAlbumAction");
if(ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeAlbumAction(context);
}
else {
mLastAction = ImageCrop.PICK_FROM_ALBUM;
}
}
private static void doTakeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final String url = CAMERA_TEMP_PREFIX + String.valueOf(System.currentTimeMillis()) + IMAGE_EXT;
final File file = new File(Environment.getExternalStorageDirectory(), url);
mTempImagePath = file.getAbsolutePath();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
context.startActivityForResult(intent, PICK_FROM_CAMERA);
}
private static void doTakeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
final Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
checkPackages(context, intent);
if(mUseActivityPhoto) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PHOTOS");
intent.setPackage(ACTIVITY_NAME_PHOTOS);
}
else if(mUseActivityPlus) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PLUS");
intent.setPackage(ACTIVITY_NAME_PLUS);
}
context.startActivityForResult(intent, ImageCrop.PICK_FROM_ALBUM);
}
private static void removeTempFile() {
// 캡쳐 파일 삭제
if(mImageCaptureUri != null) {
final String capturePath = mImageCaptureUri.getPath();
if(capturePath != null) {
Log.w(TAG, "removeTempFile capturePath=" + capturePath);
final File captureFile = new File(capturePath);
if(captureFile != null) {
if (captureFile.getAbsoluteFile().exists()) {
captureFile.delete();
}
}
}
}
if(mTempImagePath != null) {
Log.w(TAG, "removeTempFile mTempImagePath=" + mTempImagePath);
final File tempFile = new File(mTempImagePath);
if(tempFile != null) {
if(tempFile.getAbsoluteFile().exists()) {
tempFile.delete();
}
}
}
}
private static void removeDataFile(Intent data) {
if(data == null) {
Log.w(TAG, "removeDataFile data == null");
return;
}
if(data.getData() == null) {
Log.w(TAG, "removeDataFile data.getData() == null");
return;
}
final String dataPath = data.getData().getPath();
if(dataPath == null) {
Log.w(TAG, "removeDataFile dataPath == null");
return;
}
Log.w(TAG, "removeDataFile dataPath=" + dataPath);
final File dataFile = new File(dataPath);
if(dataFile == null) {
Log.w(TAG, "removeDataFile dataFile == null");
return;
}
if(dataFile.getAbsoluteFile().exists()) {
dataFile.delete();
}
}
private static File cropFileFromPhotoData(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData");
if(data.getData() == null) {
Log.e(TAG, "cropFileFromPhotoData data.getData() == null");
return null;
}
final String dataPath = data.getData().getPath();
if (dataPath == null) {
Log.e(TAG, "cropFileFromPhotoData dataPath == null");
return null;
}
File dataFile = null;
if(dataPath.startsWith("/external")) {
final Uri dataUri = Uri.parse("content://media"+dataPath);
final String dataFilePath = getRealPathFromURI(context, dataUri);
dataFile = new File(dataFilePath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataFilePath=" + dataFilePath + " exist="+exist + " length=" +length);
}
else {
dataFile = new File(dataPath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataPath=" + dataPath + " exist="+exist + " length=" +length);
}
return dataFile;
}
public static void pickFromCamera(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "pickFromCamera => launchCropActivity");
if(mTempImagePath == null || mTempImagePath.isEmpty()) {
Log.e(TAG, "pickFromCamera mTempImagePath error");
return;
}
}
public static String getRealPathFromURI(Activity context, Uri contentUri) {
Cursor cursor = null;
final String[] proj = { MediaStore.Images.Media.DATA };
String ret = null;
try {
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
final int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ret = cursor.getString(column_index);
}
catch(Exception e) {
Log.e(TAG, "getRealPathFromURI exception");
return null;
}
if (cursor != null) {
cursor.close();
}
return ret;
}
if(readEnable && writeEnable && cameraEnable) {
switch(mLastAction) {
case ImageCrop.PICK_FROM_CAMERA:
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
ImageCrop.doTakeCameraAction(context);
break;
case ImageCrop.PICK_FROM_ALBUM:
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
ImageCrop.doTakeAlbumAction(context);
break;
}
}
}
}
I want to use this way to pick photos:
private void selectCover() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_COVER);
}
But i can't convert this to normal gallery. How to solve this? Thanks
You can use this, it will open only Gallery :
public void handleGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
public void handleCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (Exception e) {
Log.d("error", "cannot take picture", e);
}
}
Then onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Bitmap bitmap;
switch (requestCode) {
case REQUEST_CODE_GALLERY:
try {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Bitmap bitmapScaled = Bitmap.createScaledBitmap(bitmap, 800, 800, true);
Drawable drawable=new BitmapDrawable(bitmapScaled);
mImage.setImageDrawable(drawable);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
} catch (IOException e) {
Log.v("galeri", "hata var : "+e.getMessage());
}
} catch (Exception e) {
Log.v("kamera", "hata var : "+e.getMessage());
}
break;
case REQUEST_CODE_TAKE_PICTURE:
bitmap = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(bitmap);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}

I download an image from the internet with a service. How do i show it?

I download an image from the internet with a service. When the download is complete it changes the textview. I tried this on my device and it works.
Now i want the imageview in my layout to change to the downloaded image.
ServiceFile java
public class ServiceFile extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "be.ehb.arnojansens.fragmentexampleii";
public ServiceFile() {
super("ServiceFile");
}
// will be called asynchronously by Android
#Override
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
java.net.URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// successfully finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
private void publishResults(String outputPath, int result) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
This is my main activity where i have my textview and the future imageview
private TextView textView;
private ImageView imageView;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String string = bundle.getString(ServiceFile.FILEPATH);
int resultCode = bundle.getInt(ServiceFile.RESULT);
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this,
"Download complete. Download URI: " + string,
Toast.LENGTH_LONG).show();
textView.setText("Download done");
// here i shoud load my image i downloaded with my service
} else {
Toast.makeText(MainActivity.this, "Download failed",
Toast.LENGTH_LONG).show();
textView.setText("Download failed");
}
}
}
};
public void service (View view) {
Intent intent = new Intent(this, ServiceFile.class);
// add infos for the service which file to download and where to store
intent.putExtra(ServiceFile.FILENAME, "index.html");
intent.putExtra(ServiceFile.URL,
"http://en.wikipedia.org/wiki/Star_Wars#mediaviewer/File:Star_Wars_Logo.svg");
startService(intent);
textView.setText("Service started");
}
Better to use Picasso or Universal Image Loader than to pass the information per Intent.
If not, your service should write the image into a readable folder and you can send by intent the Uri to that file to whom it concerns with EventBus for instance

android dropbox authentication and upload in different activities

I am trying to upload a file from dropbox in another activity from where i autenticate to dropbox. I have this RegisterActivity.java where the user registers and then later when the registration is completed the webbrowser comes up and the user has to allow the dropbox authentication.
later in my app on another activity the user is going to upload a video to dropbox. the upload is made by ASyncTask and works well. The problem is now that i dont want to reauthenticate again. How do i fix that? Is it on the same session or do i start a new session? Now Iam trying to use the sam mDBApi form RegisterAcitivity but i think that is wrong. The keys are stored in the storeKeys() method and saves them in SharedPreferences.
Thank you very much in advance
Here is my RegisterActivity in pastebin which works. http://pastebin.com/K06JUWXv
Here is the activity that where i call my ASyncTask UploadFile:
public class ShowVideo extends Activity{
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private DropboxAPI<AndroidAuthSession> mDBApi = RegisterActivity.mDBApi;
private String[] storedKeys = getKeys();
UploadFile upload;
public static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
Button dbButton = (Button) findViewById(R.id.dropboxButton);
dbButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(v.getId() == R.id.dropboxButton){
if (mDBApi.getSession().isLinked() == true){
Log.d("ShowVideo", "TRUE");
}
if (mDBApi.getSession().isLinked() == false){
Log.d("ShowVideo", "FALSE");
}
}
}
});
yesButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
}
}
});
noButton.setOnClickListener(new OnClickListener() {
public void onClick(View w) {
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.e("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
});
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
//AndroidAuthSession session = new AndroidAuthSession(new AppKeyPair(ret[0], ret[1]), AccessType.APP_FOLDER);
//mDBApi = new DropboxAPI<AndroidAuthSession>(session);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
}
Here is my ASyncTask if you would take a look at that. Shouldn't be needed.
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private String SAVE_PATH;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dContext = context.getApplicationContext();
dDBApi = mDBApi;
SAVE_PATH = path;
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(SAVE_PATH);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), null);
}
catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
}
}
}
return null;
}
}

Categories

Resources