I am working on a project where user can upload a document to my server. This file can be selected either from local storage or a cloud storage ,say google drive. When i click on the file from file chooser all i am receiving is an account info and doc info as a uri, When i tried to fetch doc from this URI it is showing FileNotFound . I have gone through Drive API also but It is a bit confusing to me. Following are the points i came accross while trying Google Drive API:
1. How to select file from local storage.
2. How do I get FileId form the selected file.
I tried with the following code snippet:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("**/");
startActivityForResult(intent, 1000);
and In onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code
// READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
// response to some other intent, and the code below shouldn't run at all.
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter.
// Pull that URI using resultData.getData().
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.i("URI", "Uri: " + uri.toString());
try {
readTextFromUri(uri);
getMimeType(this,uri);
} catch (IOException e) {
e.printStackTrace();
}
// showImage(uri);
}
}
}
private String readTextFromUri(Uri uri) throws IOException {
// FileInputStream fileInputStream=new FileInputStream(uri.)
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
// fileInputStream.close();
// parcelFileDescriptor.close();
return stringBuilder.toString();
}
Conclusion:
Can anyone please send me a link how to upload a document(I should even check the extension of the document) from both local storage and Google drive in a File chooser.
package com.example.ayyappaboddupalli.gdrive;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveClient;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResourceClient;
import com.google.android.gms.drive.OpenFileActivityOptions;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.SearchableField;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.api.services.drive.model.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Google drive";
private static final String SIGN_IN = "Sign In";
private static final String DOWNLOAD_FILE = "Download file";
private static final int REQUEST_CODE_SIGN_IN = 0;
private static final int REQUEST_CODE_OPEN_ITEM = 1;
private static final int REQUEST_WRITE_STORAGE = 112;
private GoogleSignInAccount signInAccount;
private Set<Scope> requiredScopes;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private OpenFileActivityOptions openOptions;
private TaskCompletionSource<DriveId> mOpenItemTaskSource;
private java.io.File storageDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main);
initialize();
requestPermission();
signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
// onDriveClientReady();
signIn();
}
Button button=(Button)findViewById(R.id.Submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDriveClientReady();
}
});
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode == RESULT_OK) {
Task<GoogleSignInAccount> getAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
showMessage("Sign in successfully.");
// binding.btnSubmit.setText(DOWNLOAD_FILE);
} else {
showMessage("Sign in failed.");
}
} else {
showMessage("Sign in failed.");
}
break;
case REQUEST_CODE_OPEN_ITEM:
if (resultCode == RESULT_OK) {
DriveId driveId = data.getParcelableExtra(OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
mOpenItemTaskSource.setResult(driveId);
} else {
mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
}
break;
}
}
private void initialize() {
requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
openOptions = new OpenFileActivityOptions.Builder()
.setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "application/pdf"))
.setActivityTitle("Select file")
.build();
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
}
private void signIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
private void onDriveClientReady() {
mOpenItemTaskSource = new TaskCompletionSource<>();
mDriveClient.newOpenFileActivityIntentSender(openOptions)
.continueWith(new Continuation<IntentSender, Void>() {
#Override
public Void then(#NonNull Task<IntentSender> task) throws Exception {
startIntentSenderForResult(
task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0);
return null;
}
});
Task<DriveId> tasks = mOpenItemTaskSource.getTask();
tasks.addOnSuccessListener(this,
new OnSuccessListener<DriveId>() {
#Override
public void onSuccess(DriveId driveId) {
retrieveContents(driveId.asDriveFile());
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("File not selected.");
}
});
}
private void retrieveContents(final DriveFile file) {
// [START open_file]
final Task<DriveContents> openFileTask = mDriveResourceClient.openFile(file, DriveFile.MODE_READ_ONLY);
// [END open_file]
// [START read_contents]
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
Log.v(TAG, "File name : " + contents.toString());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
InputStream input = contents.getInputStream();
try {
java.io.File file = new java.io.File(getExternalFilesDir(null), "umesh.pdf");
Log.v(TAG, storageDir + "");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
showMessage("Download file successfully.");
return mDriveResourceClient.discardContents(contents);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("Unable to download file.");
}
});
// [END read_contents]
}
private void requestPermission() {
String dirPath = getFilesDir().getAbsolutePath() + java.io.File.separator + "PDF";
storageDir = new java.io.File(dirPath);
if (!storageDir.exists())
storageDir.mkdirs();}}
//in gradle
implementation 'com.google.android.gms:play-services:11.8.0'
compile 'com.google.android.gms:play-services-auth:11.8.0'
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-drive:v3-rev110-1.23.0'
Related
Android version 12 camera and gallery not working solution
I am working on a camera application with camera API. I am able to save the image to the picture directory and set it to the image view till android version 11 but on android 12, the image is getting saved to the picture directory but not getting set to the image view I am getting an error
My Code is
Profile.java
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.cocosw.bottomsheet.BottomSheet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xxx.xx.view.MainFragment;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Profile extends AppCompatActivity implements View.OnClickListener {
private ActivityProfileBinding binding;
private String TAG = Profile.class.getSimpleName();
private Context mContext;
private ArrayList<ImageDTO> imageDatalist = new ArrayList<>();
private SharedPrefrence prefrence;
private LoginDTO loginDTO;
private HashMap<String, String> parms = new HashMap<>();
String dob = "";
String[] arrOfStr;
BottomSheet.Builder builder;
Uri picUri;
int PICK_FROM_CAMERA = 1, PICK_FROM_GALLERY = 2;
int CROP_CAMERA_IMAGE = 3, CROP_GALLERY_IMAGE = 4;
String imageName;
String pathOfImage;
Bitmap bm;
int flag = 1;
ImageCompression imageCompression;
byte[] resultByteArray;
File file;
Bitmap bitmap = null;
private HashMap<String, File> paramsFile = new HashMap<>();
HashMap<String, String> values = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
mContext = Profile.this;
prefrence = SharedPrefrence.getInstance(mContext);
loginDTO = prefrence.getLoginResponse(Consts.LOGIN_DTO);
parms.put(Consts.USER_ID, loginDTO.getUser_id());
values.put(Consts.USER_ID, loginDTO.getUser_id());
setUiaction();
}
public void setUiaction() {
binding.collapsingToolbar.setExpandedTitleColor(Color.TRANSPARENT);
binding.collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
binding.collapsingToolbar.setTitle("Profile");
binding.rlBio.setOnClickListener(this);
binding.ivCamera.setOnClickListener(this);
binding.rlGallaryClick.setOnClickListener(this);
binding.back.setOnClickListener(this);
binding.ivEditSelf.setOnClickListener(this);
binding.ivEditAbout.setOnClickListener(this);
binding.ivEditAppearance.setOnClickListener(this);
binding.ivEditImportant.setOnClickListener(this);
binding.ivEditCritical.setOnClickListener(this);
binding.ivEditLifestyle.setOnClickListener(this);
binding.ivEditFamily.setOnClickListener(this);
builder = new BottomSheet.Builder(Profile.this).sheet(R.menu.menu_cards);
builder.title(getResources().getString(R.string.select_img));
builder.listener(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case R.id.camera_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
ProjectUtils.pauseProgressDialog();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);
picUri = FileProvider.getUriForFile(Profile.this.getApplicationContext(), Profile.this.getApplicationContext().getPackageName() + ".fileprovider", file);
} else {
picUri = Uri.fromFile(file); // create
}
prefrence.setValue(Consts.IMAGE_URI_CAMERA, picUri.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri); // set the image file
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case R.id.gallery_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
picUri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_pic)), PICK_FROM_GALLERY);
}
}
break;
case R.id.cancel_cards:
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
});
break;
}
}
});
}
private File getOutputMediaFile(int type) {
String root = Environment.getExternalStorageDirectory().toString();
File mediaStorageDir = new File(root, Consts.APP_NAME);
/**Create the storage directory if it does not exist*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
Consts.APP_NAME + timeStamp + ".png");
imageName = Consts.APP_NAME + timeStamp + ".png";
} else {
return null;
}
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CROP_CAMERA_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
//bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
// bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
Log.e("image", imagePath);
changeImage();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == CROP_GALLERY_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
bm = MediaStore.Images.Media.getBitmap(Profile.this.getContentResolver(), picUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
changeImage();
Log.e("image", imagePath);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == PICK_FROM_CAMERA && resultCode == RESULT_OK) {
if (picUri != null) {
picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
} else {
picUri = Uri.parse(prefrence
.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
}
}
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
try {
Uri tempUri = data.getData();
Log.e("front tempUri", "" + tempUri);
if (tempUri != null) {
startCropping(tempUri, CROP_GALLERY_IMAGE);
} else {
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public void startCropping(Uri uri, int requestCode) {
Intent intent = new Intent(Profile.this, MainFragment.class);
intent.putExtra("imageUri", uri.toString());
intent.putExtra("requestCode", requestCode);
startActivityForResult(intent, requestCode);
}
#Override
protected void onResume() {
super.onResume();
if (NetworkManager.isConnectToInternet(mContext)) {
getImages();
} else {
ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_concation));
}
}
public void getImages() {
new HttpsRequest(Consts.GET_GALLARY_API, parms, mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
getMyProfile();
if (flag) {
try {
imageDatalist = new ArrayList<>();
Type getpetDTO = new TypeToken<List<ImageDTO>>() {
}.getType();
imageDatalist = (ArrayList<ImageDTO>) new Gson().fromJson(response.getJSONArray("data").toString(), getpetDTO);
if (imageDatalist.size() > 0) {
} else {
imageDatalist = new ArrayList<>();
}
} catch (JSONException e) {
e.printStackTrace();
imageDatalist = new ArrayList<>();
}
} else {
imageDatalist = new ArrayList<>();
}
}
});
}
#Override
public void onBackPressed() {
//super.onBackPressed();
finish();
overridePendingTransition(R.anim.anim_slide_in_right,
R.anim.anim_slide_out_right);
}
public void getMyProfile() {
ProjectUtils.showProgressDialog(mContext, true, getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.MY_PROFILE_API, getparmProfile(), mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
try {
loginDTO = new Gson().fromJson(response.getJSONObject("data").toString(), LoginDTO.class);
prefrence.setLoginResponse(loginDTO, Consts.LOGIN_DTO);
showData();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ProjectUtils.showToast(mContext, msg);
}
}
});
}
public HashMap<String, String> getparmProfile() {
HashMap<String, String> parms = new HashMap<>();
parms.put(Consts.USER_ID, loginDTO.getUser_id());
Log.e(TAG + " My Profile", parms.toString());
return parms;
}
public void changeImage() {
new HttpsRequest(Consts.SET_PROFILE_IMAGE_API, values,paramsFile, mContext).imagePost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
getMyProfile();
} else {
}
}
});
}
}
MainFragment.java
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import com.xxx.xx.R;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.CropCallback;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.isseiaoki.simplecropview.callback.SaveCallback;
import com.isseiaoki.simplecropview.util.Utils;
import java.io.File;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
#RuntimePermissions
public class MainFragment extends FragmentActivity {
private static final int REQUEST_PICK_IMAGE = 10011;
private static final int REQUEST_SAF_PICK_IMAGE = 10012;
private static final String PROGRESS_DIALOG = "ProgressDialog";
Uri myUri;
int requestCode;
private CropImageView mCropView;
private LinearLayout mRootLayout;
public MainFragment() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
myUri = Uri.parse(getIntent().getExtras().getString("imageUri"));
requestCode = getIntent().getExtras().getInt("requestCode");
bindViews();
FontUtils.setFont(mRootLayout);
mCropView.startLoad(myUri, mLoadCallback);
mCropView.setCropMode(CropImageView.CropMode.FREE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = result.getData().toString();
mCropView.startLoad(result.getData(), mLoadCallback);
} else if (requestCode == REQUEST_SAF_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = Utils.ensureUriPermission(this, result).toString();
mCropView.startLoad(Utils.ensureUriPermission(this, result), mLoadCallback);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
MainFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
private void bindViews() {
mCropView = (CropImageView) findViewById(R.id.cropImageView);
findViewById(R.id.buttonDone).setOnClickListener(btnListener);
findViewById(R.id.buttonFitImage).setOnClickListener(btnListener);
findViewById(R.id.button1_1).setOnClickListener(btnListener);
findViewById(R.id.button3_4).setOnClickListener(btnListener);
findViewById(R.id.button4_3).setOnClickListener(btnListener);
findViewById(R.id.button9_16).setOnClickListener(btnListener);
findViewById(R.id.button16_9).setOnClickListener(btnListener);
findViewById(R.id.buttonFree).setOnClickListener(btnListener);
findViewById(R.id.buttonPickImage).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateLeft).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateRight).setOnClickListener(btnListener);
findViewById(R.id.buttonCustom).setOnClickListener(btnListener);
findViewById(R.id.buttonCircle).setOnClickListener(btnListener);
findViewById(R.id.buttonShowCircleButCropAsSquare).setOnClickListener(btnListener);
mRootLayout = (LinearLayout) findViewById(R.id.layout_root);
}
#NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
public void pickImage() {
if (Build.VERSION.SDK_INT >= 33) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), REQUEST_PICK_IMAGE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_SAF_PICK_IMAGE);
}
}
#NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void cropImage() {
showProgress();
Log.e("cropImage", "called");
mCropView.startCrop(createSaveUri(), mCropCallback, mSaveCallback);
}
#OnShowRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
public void showRationaleForPick(PermissionRequest request) {
showRationaleDialog(R.string.permission_pick_rationale, request);
}
#OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void showRationaleForCrop(PermissionRequest request) {
showRationaleDialog(R.string.permission_crop_rationale, request);
}
public void showProgress() {
ProgressDialogFragment f = ProgressDialogFragment.getInstance();
getSupportFragmentManager()
.beginTransaction()
.add(f, PROGRESS_DIALOG)
.commitAllowingStateLoss();
}
public void dismissProgress() {
// if (!isAdded()) return;
FragmentManager manager = getSupportFragmentManager();
if (manager == null) return;
ProgressDialogFragment f = (ProgressDialogFragment) manager.findFragmentByTag(PROGRESS_DIALOG);
if (f != null) {
getSupportFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public Uri createSaveUri() {
return Uri.fromFile(new File(this.getCacheDir(), "cropped"));
}
private void showRationaleDialog(#StringRes int messageResId, final PermissionRequest request) {
new AlertDialog.Builder(this)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.proceed();
}
})
.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.cancel();
}
})
.setCancelable(false)
.setMessage(messageResId)
.show();
}
// Handle button event /////////////////////////////////////////////////////////////////////////
private final View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonDone:
MainFragmentPermissionsDispatcher.cropImageWithCheck(MainFragment.this);
break;
case R.id.buttonFitImage:
mCropView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
break;
case R.id.button1_1:
mCropView.setCropMode(CropImageView.CropMode.SQUARE);
break;
case R.id.button3_4:
mCropView.setCropMode(CropImageView.CropMode.RATIO_3_4);
break;
case R.id.button4_3:
mCropView.setCropMode(CropImageView.CropMode.RATIO_4_3);
break;
case R.id.button9_16:
mCropView.setCropMode(CropImageView.CropMode.RATIO_9_16);
break;
case R.id.button16_9:
mCropView.setCropMode(CropImageView.CropMode.RATIO_16_9);
break;
case R.id.buttonCustom:
mCropView.setCustomRatio(7, 5);
break;
case R.id.buttonFree:
mCropView.setCropMode(CropImageView.CropMode.FREE);
break;
case R.id.buttonCircle:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE);
break;
case R.id.buttonShowCircleButCropAsSquare:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE_SQUARE);
break;
case R.id.buttonRotateLeft:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
break;
case R.id.buttonRotateRight:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
break;
case R.id.buttonPickImage:
MainFragmentPermissionsDispatcher.pickImageWithCheck(MainFragment.this);
break;
}
}
};
// Callbacks ///////////////////////////////////////////////////////////////////////////////////
private final LoadCallback mLoadCallback = new LoadCallback() {
#Override
public void onSuccess() {
dismissProgress();
Log.e("", "success");
}
#Override
public void onError() {
dismissProgress();
Log.e("", "error");
}
};
private final CropCallback mCropCallback = new CropCallback() {
#Override
public void onSuccess(Bitmap cropped) {
}
#Override
public void onError() {
}
};
private final SaveCallback mSaveCallback = new SaveCallback() {
#Override
public void onSuccess(Uri outputUri) {
dismissProgress();
//addPicture.startResultActivity(outputUri);
Intent i = getIntent();
i.putExtra("resultUri", outputUri.toString());
setResult(requestCode, i);
finish();
}
#Override
public void onError() {
dismissProgress();
}
};
}
ProjectUtils.java
public static boolean hasPermissionInManifest(Context context, int requestCode, String permissionName) {
if (Build.VERSION.SDK_INT >= 29) {
Log.w(TAG, "hasPermissions: API version >= 29, returning true by default");
// DANGER ZONE!!! Changing this will break the library.
return true;
}
if (context == null) {
throw new IllegalArgumentException("Can't check permissions for null context");
}
if (ContextCompat.checkSelfPermission(context,
permissionName)
!= PackageManager.PERMISSION_GRANTED) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions((Activity) context,
new String[]{permissionName},
requestCode);
} else {
return true;
}
return false;
}
AndroidManifest.java
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"
tools:ignore="ScopedStorage" />
<!--Permission for the Android 11 and above-->
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android:requestLegacyExternalStorage="true"
've also added requestLegacyExternalStorage="true" to the application tag in the manifest to get it to work for the APIs below Android 12. Stuck with this issue since yesterday, Please help.
Android version 12 camera and gallery not working solution
Hello greetings and salutation.
i have two different Android codes that almost work the same way. The first code Capture image from gallery and upload it with title to php server while the second code capture image from gallery and when resize button is pressed the image is compressed both size and memory is reduced but also maintaining the same picture Quality. Let me Upload / paste the two codes.
But my question is
how will i make the second code upload to server after it have compressed the image memory? or how will i make the first code before uploading to server let it compress it like code two ?
The first code
package net.simplifiedcoding.androiduploadimage;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
private EditText editText;
private ImageView imageView;
public static final String KEY_IMAGE = "image";
public static final String KEY_TEXT = "name";
public static final String UPLOAD_URL = "http://simplifiedcoding.16mb.com/PhotoUploadWithText/upload.php";
private int PICK_IMAGE_REQUEST = 1;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editText = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String text = editText.getText().toString().trim();
final String image = getStringImage(bitmap);
class UploadImage extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TEXT,text);
param.put(KEY_IMAGE,image);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
}
if(v == buttonUpload){
uploadImage();
}
}
}
The second Code
package id.zelory.compressor.sample;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;
import id.zelory.compressor.Compressor;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private ImageView actualImageView;
private ImageView compressedImageView;
private TextView actualSizeTextView;
private TextView compressedSizeTextView;
private File actualImage;
private File compressedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actualImageView = (ImageView) findViewById(R.id.actual_image);
compressedImageView = (ImageView) findViewById(R.id.compressed_image);
actualSizeTextView = (TextView) findViewById(R.id.actual_size);
compressedSizeTextView = (TextView) findViewById(R.id.compressed_size);
actualImageView.setBackgroundColor(getRandomColor());
clearImage();
}
public void chooseImage(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
public void compressImage(View view) {
if (actualImage == null) {
showError("Please choose an image!");
} else {
// Compress image in main thread
//compressedImage = new Compressor(this).compressToFile(actualImage);
//setCompressedImage();
// Compress image to bitmap in main thread
//compressedImageView.setImageBitmap(new Compressor(this).compressToBitmap(actualImage));
// Compress image using RxJava in background thread
new Compressor(this)
.compressToFileAsFlowable(actualImage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
#Override
public void accept(File file) {
compressedImage = file;
setCompressedImage();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) {
throwable.printStackTrace();
showError(throwable.getMessage());
}
});
}
}
public void customCompressImage(View view) {
if (actualImage == null) {
showError("Please choose an image!");
} else {
// Compress image in main thread using custom Compressor
try {
compressedImage = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(actualImage);
setCompressedImage();
} catch (IOException e) {
e.printStackTrace();
showError(e.getMessage());
}
// Compress image using RxJava in background thread with custom Compressor
/*new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFileAsFlowable(actualImage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
#Override
public void accept(File file) {
compressedImage = file;
setCompressedImage();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) {
throwable.printStackTrace();
showError(throwable.getMessage());
}
});*/
}
}
private void setCompressedImage() {
compressedImageView.setImageBitmap(BitmapFactory.decodeFile(compressedImage.getAbsolutePath()));
compressedSizeTextView.setText(String.format("Size : %s", getReadableFileSize(compressedImage.length())));
Toast.makeText(this, "Compressed image save in " + compressedImage.getPath(), Toast.LENGTH_LONG).show();
Log.d("Compressor", "Compressed image save in " + compressedImage.getPath());
}
private void clearImage() {
actualImageView.setBackgroundColor(getRandomColor());
compressedImageView.setImageDrawable(null);
compressedImageView.setBackgroundColor(getRandomColor());
compressedSizeTextView.setText("Size : -");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
if (data == null) {
showError("Failed to open picture!");
return;
}
try {
actualImage = FileUtil.from(this, data.getData());
actualImageView.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
actualSizeTextView.setText(String.format("Size : %s", getReadableFileSize(actualImage.length())));
clearImage();
} catch (IOException e) {
showError("Failed to read picture data!");
e.printStackTrace();
}
}
}
public void showError(String errorMessage) {
Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
}
private int getRandomColor() {
Random rand = new Random();
return Color.argb(100, rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}
public String getReadableFileSize(long size) {
if (size <= 0) {
return "0";
}
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
Thanks seriously need this to be solved
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
to this
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
this will work
why when i trying to upload image with size 1.5 mb it's said error while uploading, but actually the image is successfully upload? and if i trying to upload with size 100 kb it's said Image Uploaded Successfully
WC_Activity.java
package com.emergency.e_place;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.HashMap;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAGS = "DEBUG";
String Latitude;
String Longitude;
private final String TAG = this.getClass().getName();
ImageView ivCamera, ivGallery, ivUpload, ivImage;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST = 13323;
final int GALLERY_REQUEST = 22131;
String selectedPhoto;
EditText etIpAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAGS, "onLocationChanged: " + Longitude);
etIpAddress = (EditText)findViewById(R.id.etIpAddress);
cameraPhoto = new CameraPhoto(getApplicationContext());
galleryPhoto = new GalleryPhoto(getApplicationContext());
ivImage = (ImageView)findViewById(R.id.ivImage);
ivCamera = (ImageView)findViewById(R.id.ivCamera);
ivGallery = (ImageView)findViewById(R.id.ivGallery);
ivUpload = (ImageView)findViewById(R.id.ivUpload);
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
cameraPhoto.addToGallery();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while taking photos", Toast.LENGTH_SHORT).show();
}
}
});
ivGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(galleryPhoto.openGalleryIntent(), GALLERY_REQUEST);
}
});
ivUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedPhoto == null || selectedPhoto.equals("")){
Toast.makeText(getApplicationContext(), "No Image Selected.", Toast.LENGTH_SHORT).show();
return;
}
try {
Bitmap bitmap = ImageLoader.init().from(selectedPhoto).requestSize(1024, 1024).getBitmap();
String encodedImage = ImageBase64.encode(bitmap);
Log.d(TAG, encodedImage);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("image", encodedImage);
PostResponseAsyncTask task = new PostResponseAsyncTask(WC_Activity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if(s.contains("uploaded_success")){
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully.",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error while uploading.",
Toast.LENGTH_SHORT).show();
}
}
});
String ip = etIpAddress.getText().toString();
task.execute("http://" +ip + "/AndroidUpload/upload.php");
task.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error.",
Toast.LENGTH_SHORT).show();
}
});
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while encoding photos", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST){
String photoPath = cameraPhoto.getPhotoPath();
selectedPhoto = photoPath;
Bitmap bitmap = null;
try {
bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(getRotatedBitmap(bitmap, 90));
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
}
}
else if(requestCode == GALLERY_REQUEST){
Uri uri = data.getData();
galleryPhoto.setPhotoUri(uri);
String photoPath = galleryPhoto.getPath();
selectedPhoto = photoPath;
try {
Bitmap bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
}
}
}
}
private Bitmap getRotatedBitmap(Bitmap source, float angle){
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap bitmap1 = Bitmap.createBitmap(source,
0, 0, source.getWidth(), source.getHeight(), matrix, true);
return bitmap1;
}
}
package com.camerafileupload;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Changing action bar background color
// These two lines are not needed
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new 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 get this code from android hive, I didn't know where the code to upload the image to server. I already build this code into .apk it working when taking photo and video to local storage but not to server.
and this is uploadactivity
package com.camerafileupload;
import com.camerafileupload.AndroidMultiPartEntity.ProgressListener;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
public class UploadActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressBar progressBar;
private String filePath = null;
private TextView txtPercentage;
private ImageView imgPreview;
private VideoView vidPreview;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
btnUpload = (Button) findViewById(R.id.btnUpload);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
vidPreview = (VideoView) findViewById(R.id.videoPreview);
// Changing action bar background color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor(getResources().getString(
R.color.action_bar))));
// Receiving the data from previous activity
Intent i = getIntent();
// image or video path that is captured in previous activity
filePath = i.getStringExtra("filePath");
// boolean flag to identify the media type, image or video
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
/**
* Displaying captured image/video on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image or video
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
vidPreview.setVisibility(View.GONE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
vidPreview.setVisibility(View.VISIBLE);
vidPreview.setVideoPath(filePath);
// start playing
vidPreview.start();
}
}
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.fintech-dev.com/cpeco"));
entity.addPart("email", new StringBody("i117dr4#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
/**
* Method to show alert dialog
* */
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
and this is androidmultipartentity
package com.camerafileupload;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
#SuppressWarnings("deprecation")
public class AndroidMultiPartEntity extends MultipartEntity
{
private final ProgressListener listener;
public AndroidMultiPartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}
public AndroidMultiPartEntity(final HttpMultipartMode mode,
final ProgressListener listener) {
super(mode);
this.listener = listener;
}
public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener {
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
This is config
package com.camerafileupload;
public class Config {
public static final String FILE_UPLOAD_URL = "url.com/android_upload/file_upload.php";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "android_upload";
DataHolder.FILE_UPLOAD_URL containing the url to upload.
onclick write
new UploadFileToServer().execute();
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
pDialog.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
pDialog.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(DataHolder.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("username", new StringBody("xyz"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
/**
* Method to show alert dialog
* */
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
I am making a camera app that takes an image when the camera is first initiated, I have got it working, however the only problem I am getting is that when a picture is taken, it stores the first image in the folder. EG. I install the app, the camera takes a photo, then the next time the camera takes another photo, it is the same as the first one. I have tried to make the data = null after, however this is still not working.
Any suggestions?
package com.example.charlie;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PService2 extends Service {
//private myPreview mPreview;
Camera mCamera;
byte[] data;
private void PictureCallback()
{
}
private final class TakePhotoReceiver extends BroadcastReceiver {
public final Camera mCamera;
private TakePhotoReceiver(Camera mCamera) {
this.mCamera = mCamera;
}
#Override
public void onReceive(Context context, Intent intent) {
try {// TODO Auto-generated method stub
Log.v("test", "Got here");
mCamera.takePicture(null, null, mPicture);
//releaseCamera();
} finally {
releaseCamera();
}
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data2,Camera camera) {
Log.v("test", "image taken");
data = data2;
createExternalStoragePublicPicture(data);
data = null;
data2 = null;
//releaseCamera();
}
};
}
}
*/
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
String mCurrentPhotoPath;
void createExternalStoragePublicPicture(byte[] data) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + ".jpg";
File image = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(image, imageFileName);
try {
image.mkdirs();
OutputStream os = new FileOutputStream(file);
os.write(data);
os.close();
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + file, e);
}
data = null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("Service Started");
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
try {
//releaseCamera();
final Camera mCamera = Camera.open(0);
//myPreview mPreview = new myPreview(this, mCamera);
//FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
// preview.addView(mPreview);
this.registerReceiver(new TakePhotoReceiver(mCamera),
new IntentFilter(Intent.ACTION_SCREEN_ON));
//releaseCamera();
//mCamera.stopPreview();
//mCamera.stopPreview();
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return START_STICKY;
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
private FrameLayout findViewById(int cameraPreview) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
System.out.println("Service Stopped");
super.onDestroy();
mCamera.release();
//unregisterReceiver(this.TakePhotoReceiver);
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
public class PictureService extends Service
{
private static final String TAG = PictureService.class.getSimpleName();
private TakePhotoReceiver mReceiver;
#Override
public void onCreate()
{
super.onCreate();
Log.d(TAG, "onCreate");
mReceiver = new TakePhotoReceiver(0);
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.d(TAG, "onDestroy");
unregisterReceiver(mReceiver);
}
private final class TakePhotoReceiver extends BroadcastReceiver
implements Camera.PictureCallback
{
public final int mCameraId;
private TakePhotoReceiver(int cameraId)
{
mCameraId = cameraId;
}
#Override
public void onReceive(Context context, Intent intent)
{
try{
Camera camera = Camera.open(mCameraId);
try{
Log.d(TAG, "onReceive: Taking picture");
camera.takePicture(null, null, this);
}
finally{
camera.release();
camera = null;
}
}
catch(Exception e){
Log.w(TAG, "onReceive: error with camera " + mCameraId, e);
}
}
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d(TAG, "onPictureTaken");
File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
savePictureTo(picturesDir, data);
}
}
private void savePictureTo(File directory, byte[] data)
{
String fileName = new SimpleDateFormat("'JPEG_'yyyyMMdd_HHmmss'.jpg'")
.format(System.currentTimeMillis());
File file = new File(directory, fileName);
try{
directory.mkdirs();
OutputStream os = new FileOutputStream(file);
os.write(data);
os.close();
MediaScannerConnection.scanFile(this, new String[ ] { file.toString() },
null, new MediaScannerConnection.OnScanCompletedListener()
{
#Override
public void onScanCompleted(String path, Uri uri)
{
Log.d(TAG, "savePictureTo: scanned path=" + path + ", uri=" + uri);
}
});
}
catch(IOException e){
Log.w(TAG, "savePictureTo: error writing " + file, e);
}
}
}