below is my code, can anyone help me, where can i put crop image code when asked to select image from gallery or camera. thanks in advance.
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
//public static final String UPLOAD_URL = "http://192.168.0.137/image_json /upload.php";
public static final String URL_ADD = "http://192.168.0.104/image_json/addEmp.php";
public static final String URL_GET_ALL = "http://192.168.0.137/image_json/getAllEmp.php";
public static final String URL_GET_EMP = "http://192.168.0.137/image_json/getEmp.php?id=";
public static final String URL_UPDATE_EMP = "http://192.168.0.137/image_json/updateEmp.php";
public static final String URL_DELETE_EMP = "http://192.168.0.137/image_json/deleteEmp.php?id=";
// Keys that will be used to send the request to php scripts
public static final String KEY_EMP_ID = "id";
public static final String KEY_EMP_NAME = "name";
public static final String KEY_EMP_DESG = "desg";
public static final String KEY_EMP_SAL = "salary";
// JSON Tags
public static final String TAG_JSON_ARRAY = "result";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_DESG = "desg";
public static final String TAG_SAL = "salary";
// employee id to pass with intent
public static final String EMP_ID = "emp_id";
public static final String UPLOAD_KEY = "image";
private int PICK_IMAGE_REQUEST = 1;
int REQUEST_CAMERA = 0;
private Button buttonChoose;
private Button buttonUpload;
// private Button buttonView;
private EditText editTextName;
private EditText editTextDesg;
private EditText editTextSal;
private Button buttonAdd;
private Button buttonView;
private ImageView imageView;
private Bitmap bitmap;
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextDesg = (EditText) findViewById(R.id.editTextDesg);
editTextSal = (EditText) findViewById(R.id.editTextSalary);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonView = (Button) findViewById(R.id.buttonView);
// Setting listeners to button
buttonAdd.setOnClickListener(this);
buttonView.setOnClickListener(this);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
// buttonView = (Button) findViewById(R.id.buttonViewImage);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
// buttonView.setOnClickListener(this);
}
private void addEmployee() {
final String name = editTextName.getText().toString().trim();
final String desg = editTextDesg.getText().toString().trim();
final String sal = editTextSal.getText().toString().trim();
class AddEmployee extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Adding...",
"Wait...", 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... v)
{
String uploadImage = getStringImage(bitmap);
HashMap<String, String> params = new HashMap<String, String>();
params.put(KEY_EMP_NAME, name);
params.put(KEY_EMP_DESG, desg);
params.put(KEY_EMP_SAL, sal);
params.put(UPLOAD_KEY, uploadImage);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(URL_ADD, params);
Log.i("result",""+res);
return res;
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
}
#SuppressLint("NewApi")
#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) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(
getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
/*
* Bundle extras = data.getExtras(); Bitmap photo = (Bitmap)
* extras.get("data");
*/
bitmap = getImageFileFromSDCard("abc.jpg");
imageView.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "bundal is null",
Toast.LENGTH_LONG).show();
}
}
private Bitmap getImageFileFromSDCard(String filename) {
Bitmap bitmap = null;
File outputFile = Environment.getExternalStorageDirectory();
File file = new File(outputFile, filename);
Log.i("pathstore", "" + file);
try {
FileInputStream fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
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;
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
selectImage();
// showFileChooser();
}
if (v == buttonAdd) {
addEmployee();
}
}
private void viewImage() {
// startActivity(new Intent(this, ImageListView.class));
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
String userChoosenTask = "Take Photo";
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
String userChoosenTask = "Choose from Library";
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, "abc.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),
PICK_IMAGE_REQUEST);
}
}
You can do cropping part in onActivityResult method as it is called just after you select photo from gallery or camera.
I hope this answer will help you.
Use your Intent like this.
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC_REQUEST_CODE);
Good Luck!
Related
I created a program to capture a photo but when i look at it in the Photo Gallery it does not appear immediately.
I Already used the command provided in the other questions in this site which is similar to this Code:
"sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));"
this is my entire code:
enter code here
public class PicturesActivity extends AppCompatActivity {
public static final int REQUEST_TAKE_PHOTO = 1;
public static final String ACCOUNTNUM = "AccountNum";
public static final String METERNO = "MeterNo";
public static final int CAMERA_PERMISSION_REQUEST_CODE = 4192;
private static final String ALBUM_NAME = "DailySelfie";
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
public static final String FILE_PATH_EXTRA = "image_currentPath";
private static final long INITIAL_ALARM_DELAY = 2 * 60 * 1000L;
public static final int REQUEST_CODE = 228;
private static final int CAMERA_REQUEST_CODE = REQUEST_CODE;
private ImageAdapter imageAdapter = null;
private String mCurrentPhotoPath = null;
private File capturedImage;
private AlarmManager alarmManager;
private Intent notificationReceiverIntent;
private PendingIntent notificationReceiverPendingIntent;
private ListView pictureList;
private SearchView searchText;
private File pictureFile;
private int pictureCounter = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pictures);
this.pictureList = (ListView) findViewById(R.id.picture_list);
this.searchText = (SearchView) findViewById(R.id.edit_image_search);
this.alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
this.imageAdapter = new ImageAdapter(getApplicationContext());
notificationReceiverIntent = new Intent(PicturesActivity.this, SelfieBroadCastReceiver.class);
notificationReceiverPendingIntent = PendingIntent.getBroadcast(PicturesActivity.this, 0, notificationReceiverIntent, 0);
getSupportActionBar();
this.pictureList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageRecord imageRecord = imageAdapter.getItem(position);
Intent picDetailIntent = new Intent(getApplicationContext(), PictureDetailActivity.class);
picDetailIntent.putExtra(FILE_PATH_EXTRA, imageRecord.getFullPath());
startActivity(picDetailIntent);
}
});
this.searchText.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//imageAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
imageAdapter.getFilter().filter(newText);
return false;
}
});
try {
this.pictureList.setAdapter(imageAdapter);
}catch (Exception e){
Toast.makeText(getApplication(),e.toString(),Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
renameFile(this.capturedImage);
}
}
#Override
protected void onResume() {
super.onResume();
this.setUpPicList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pictures_menu, menu);
return true;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.show_camera:
if(checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED){
try {
dispatchTakePictureIntent();
}catch (IOException e){}
}else{
String[] permissionRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
return true;
case R.id.set_alarm:
setAlarm();
return true;
case R.id.cancel_alarm:
cancelAlarm();
return true;
default:
return false;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==CAMERA_PERMISSION_REQUEST_CODE){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED & grantResults[1]== PackageManager.PERMISSION_GRANTED){
try {
dispatchTakePictureIntent();
}catch(IOException e){}
}else{
viewSnackBar(getString(R.string.camera_needed_permission));
}
}
}
private void dispatchTakePictureIntent() throws IOException{
pictureFile = createImageFiles();
Uri uriFile = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+ ".provider", pictureFile);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,uriFile);
takePictureIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(pictureFile)));
scanMedia(pictureFile.toString());
}
private File createImageFiles() {
SharedPreferences prefs = getSharedPreferences(ACCOUNTNUM, MODE_PRIVATE);
SharedPreferences meterNum = getSharedPreferences(METERNO, MODE_PRIVATE);
final String accountNumber = prefs.getString("accountNum", null);
final String MeterNumber = meterNum.getString("MeterNo", null);
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = new File(picturesDirectory, accountNumber + "-" + MeterNumber.trim() + "-"+ pictureCounter + ".JPG");
pictureCounter++;
return imageFile;
}
private void scanMedia(String path) {
File file = new File(path);
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);
}
public void viewSnackBar(String message){
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, message, Snackbar.LENGTH_LONG).show();
}
private void renameFile(File file) {
SharedPreferences prefs = getSharedPreferences(ACCOUNTNUM, MODE_PRIVATE);
final String accountNumber = prefs.getString("accountNum", null);
final Dialog dialog = new Dialog(PicturesActivity.this);
dialog.setContentView(R.layout.file_prompt);
final EditText editText = (EditText) dialog.findViewById(R.id.editTextDialogUserInput);
final Button button = (Button) dialog.findViewById(R.id.saveButton);
final File oldFile = file;
try {
editText.setText(accountNumber);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(editText.getText().toString())) {
String fileName = editText.getText().toString().toLowerCase() + "-";
try {
File newFile = File.createTempFile(fileName, JPEG_FILE_SUFFIX, getAlbumDir());
oldFile.renameTo(newFile);
setUpPicList();
dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
dialog.show();
}catch (Exception e){
Toast.makeText(getApplication(), e.toString(),Toast.LENGTH_SHORT).show();
}
}
private File getAlbumDir(){
File storageDir = null;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
storageDir = getAlbumStorageDir();
if(storageDir != null){
if(!storageDir.mkdirs()){
if(!storageDir.exists()){
Log.d("DailySelfie", "Failed to create directory");
return null;
}
}
}
} else {
Log.v("DailySelfie", "External Storage is not mounted READ/WRITE");
}
return storageDir;
}
///*************************
private File getAlbumStorageDir(){
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return picturesDirectory;
//return new File(Environment.getExternalStorageDirectory() + CAMERA_DIR + ALBUM_NAME);
}
private void galleryAddPic(){
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File file = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setUpPicList(){
imageAdapter.removeAllViews();
File albumFile = getAlbumDir();
if(albumFile.isDirectory() && albumFile.exists()){
File[] files = albumFile.listFiles();
for(File file : files){
ImageRecord imageRecord = new ImageRecord(file);
imageAdapter.add(imageRecord);
}
}
}
}
I have tried many different approaches but none of them seem to help, so the problem is the following:
Image isn't uploading to imageButton. I have the path and I have checked it via debugger, added some Toasts to that the fragment gets to the onActivityResult and it does, but the image isn't uploading. Any ideas?
public class AddProductFragment extends Fragment {
private static final String TAG = "AddProductFragment";
private static final int GALLERY_INTENT = 2;
private Uri imageUri;
private ImageButton imageButton;
private EditText productName,produtPrice,productDescription;
private Button btnCancel,btnAdd;
private FirebaseDatabase mDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDb = FirebaseDatabase.getInstance();
}
private void onClickEvents() {
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i,"Select Picture"),GALLERY_INTENT);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: Edit this;
String name = productName.getText().toString();
String price = produtPrice.getText().toString();
String description = productDescription.getText().toString();
DatabaseOperation dbOps = new DatabaseOperation(mDb,getContext());
dbOps.AddProduct(imageUri,name,price,description);
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: exit fragment
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_product, container, false);
imageButton = (ImageButton) v.findViewById(R.id.imageButton2);
productName = (EditText)v.findViewById(R.id.addProduct_productName);
produtPrice = (EditText)v.findViewById(R.id.addProduct_productPrice);
productDescription = (EditText)v.findViewById(R.id.addProduct_productDescription);
btnAdd = (Button) v.findViewById(R.id.addProduct_addBtn);
btnCancel = (Button) v.findViewById(R.id.addProduct_cancelBtn);
onClickEvents();
return v;
}
public Bitmap getBitmap(String path) {
Bitmap bitmap = null;
try {
File f = new File(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
imageButton.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 1", Toast.LENGTH_SHORT).show();
if(requestCode == GALLERY_INTENT){
Toast.makeText(AddProductFragment.this.getActivity(), "Number 2", Toast.LENGTH_SHORT).show();
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 3", Toast.LENGTH_SHORT).show();
String path = getPathFromCameraData(data, this.getActivity());
Toast.makeText(AddProductFragment.this.getActivity(), "Uploading", Toast.LENGTH_SHORT).show();
if (path != null) {
setFullImageFromFilePath( path);
Toast.makeText(AddProductFragment.this.getActivity(), "Uploaded", Toast.LENGTH_SHORT).show();
}
}
}
}
public void setFullImageFromFilePath( String imgPath) {
// btn.setImageBitmap(BitmapFactory.decodeFile(imgPath));
getBitmap(imgPath);
}
public static String getPathFromCameraData(Intent data, Context ctx) {
Uri selectedImage = data.getData();
String[] pathToFile = {MediaStore.Images.Media.DATA};
Cursor cursor = ctx.getContentResolver().query(selectedImage, pathToFile, null,
null, null);
if(cursor == null) return null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(pathToFile[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
}
case GALLERY_INTENT:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageURI(selectedImage);// To display selected image in image view
}
Below is my Camera Handler:
public class CameraHandler {
public static int IMAGE_PIC_CODE = 1000, CROP_CAMERA_REQUEST = 1001,
CROP_GALLARY_REQUEST = 1002;
private Intent imageCaptureintent;
private boolean isActivityAvailable;
Context context;
private List<ResolveInfo> cameraList;
List<Intent> cameraIntents;
Uri outputFileUri;
Intent galleryIntent;
Uri selectedImageUri;
private String cameraImageFilePath, absoluteCameraImagePath;
Bitmap bitmap;
ImageView ivPicture;
String ivPicture1 = String.valueOf(ivPicture);
public CameraHandler(Context context) {
this.context = context;
setFileUriForCameraImage();
}
public void setIvPicture(ImageView ivPicture) {
this.ivPicture = ivPicture;
}
private void setFileUriForCameraImage() {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "image.jpg";
final File sdImageMainDirectory = new File(root, fname);
absoluteCameraImagePath = sdImageMainDirectory.getAbsolutePath();
outputFileUri = Uri.fromFile(sdImageMainDirectory);
}
public String getCameraImagePath() {
return cameraImageFilePath;
}
private void getActivities() {
imageCaptureintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = ((Activity) context)
.getPackageManager();
this.cameraList = packageManager.queryIntentActivities(
imageCaptureintent, 0);
if (cameraList.size() > 0) {
isActivityAvailable = true;
} else {
isActivityAvailable = false;
}
}
private void fillCameraActivities() {
getActivities();
if (!isActivityAvailable) {
return;
}
cameraIntents = new ArrayList<Intent>();
for (ResolveInfo resolveInfo : cameraList) {
Intent intent = new Intent(imageCaptureintent);
intent.setPackage(resolveInfo.activityInfo.packageName);
intent.setComponent(new ComponentName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name));
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
}
private void fillGallaryIntent() {
galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
}
public void showView() {
fillCameraActivities();
fillGallaryIntent();
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent,
"Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
((Activity) context).startActivityForResult(chooserIntent,
IMAGE_PIC_CODE);
}
private Bitmap getBitmapFromURL(String src) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(src, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 192, 256);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(src, options);
}
private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2
// and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void onResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == IMAGE_PIC_CODE) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Log.v("", "ics");
} else {
Log.v("", " not ics");
}
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action
.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH
&& action != null) {
Log.v("", "action = null");
isCamera = true;
} else {
Log.v("", "action is not null");
}
}
if (isCamera) {
selectedImageUri = outputFileUri;
onResultCameraOK();
} else {
selectedImageUri = data == null ? null : data.getData();
onResultGalleryOK();
}
}
}
if (requestCode == CROP_CAMERA_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfCamera(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
if (requestCode == CROP_GALLARY_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfGallary(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
}
private void doCropping(int code) {
Log.v("", this.cameraImageFilePath);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(selectedImageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
try {
((Activity) context).startActivityForResult(cropIntent, code);
} catch (Exception e) {
}
}
private void onResultCameraOK() {
this.cameraImageFilePath = absoluteCameraImagePath;
this.bitmap = getBitmapFromURL(cameraImageFilePath);
doCropping(CROP_CAMERA_REQUEST);
}
private void onResultGalleryOK() {
this.cameraImageFilePath = selectedImageUri.toString();
this.bitmap = getBitmapFromURL(getRealPathFromURI(context,
selectedImageUri));
doCropping(CROP_GALLARY_REQUEST);
}
private void resultOnCropOkOfCamera(Intent data) {
this.bitmap = data.getExtras().getParcelable("data");
Log.v("", "cameraImageFilePath on crop camera ok => "
+ cameraImageFilePath);
setImageProfile();
}
private void resultOnCropOkOfGallary(Intent data) {
Bundle extras2 = data.getExtras();
this.bitmap = extras2.getParcelable("data");
setImageProfile();
}
private void resultOnCroppingCancel() {
Log.v("", "do cropping cancel" + cameraImageFilePath);
setImageProfile();
}
private void setImageProfile() {
Log.v("", "cameraImagePath = > " + cameraImageFilePath);
if (ivPicture != null) {
if (bitmap != null) {
ivPicture.setImageBitmap(bitmap);
String ivPicture =ConDetTenthFragment.getStringImage(bitmap);
Log.d("byte code -", ivPicture);
/*Intent i = new Intent(context, ImageUpload.class);
String getrec = ivPicture;
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("moin", getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
context.startActivity(i);*/
} else {
Log.v("", "bitmap is null");
}
}
}
public String getVar1() {
return ivPicture1;
}
/*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;
}*/
}
Below is my Fragment Code:
public class ConDetTenthFragment extends Fragment {
static String FileByte;
String FileName;
String resultlog;
ImageView ivProfile;
Context context = getActivity();
Button btnUpload, send;
CameraHandler cameraHandler;
private ProgressDialog pDialog;
static String abc;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.con_det_tenth_fragment, container, false);
/*TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));*/
ivProfile = (ImageView) rootView.findViewById(R.id.iv_upload);
btnUpload = (Button) rootView.findViewById(R.id.btn_upload_image);
send = (Button) rootView.findViewById(R.id.btnsend);
cameraHandler = new CameraHandler(context);
cameraHandler.setIvPicture(ivProfile);
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait");
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraHandler.showView();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new async().execute();
}
});
return rootView;
}
public static ConDetTenthFragment newInstance(String text) {
ConDetTenthFragment f = new ConDetTenthFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
public static 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);
abc = encodedImage;
//encodedImage = FileByte.setText().toString();
return encodedImage;
}
// Async task to perform login operation
class async extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Get the bundle
/*Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString("moin");*/
SoapObject request = new SoapObject(namespace, method_name);
request.addProperty(parameter, abc);//add the parameters
request.addProperty(parameter2, "moin.jpeg");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//set soap version
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
// this is the actual part that will call the webservice
androidHttpTransport.call(soap_action, envelope);
// SoapPrimitive prim = (SoapPrimitive) envelope.getResponse(); // Get the SoapResult from the envelope body.
SoapObject response = (SoapObject) envelope.bodyIn;
// resultlog=prim.toString();
hideDialog();
} catch (Exception e) {
e.printStackTrace();
}
return resultlog;
}
}
/*#Override
public void onClick(View view) {
if (view == btnUpload) {
cameraHandler.showView();
}
if (view == send) {
new async().execute();
}
}*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
cameraHandler.onResult(requestCode, resultCode, data);
Log.v("", "code = > " + requestCode);
}
// this is used to show diologue
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
// this is used to hide diologue
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Below is my Log Cat:
FATAL EXCEPTION: main
Process: code.meter.securemeter.com.securemeter, PID: 10492
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.app.Activity.getPackageManager()' on a null object reference
at code.meter.securemeter.com.securemeter.helper.CameraHandler.getActivities(CameraHandler.java:72)
at code.meter.securemeter.com.securemeter.helper.CameraHandler.fillCameraActivities(CameraHandler.java:83)
at code.meter.securemeter.com.securemeter.helper.CameraHandler.showView(CameraHandler.java:106)
at code.meter.securemeter.com.securemeter.fragment.ConDetTenthFragment$1.onClick(ConDetTenthFragment.java:76)
at android.view.View.performClick(View.java:5242)
at android.widget.TextView.performClick(TextView.java:10540)
at android.view.View$PerformClick.run(View.java:21185)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6856)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Problem is happening because you are passing a null context to CameraHandler
Change your ConDetTenthFragment as follows:
public class ConDetTenthFragment extends Fragment {
Context context;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getAcitivity();
cameraHandler = new CameraHandler(context);
....
}
}
Also, I think you don't need to Cast a context to Activity.
Just call (in CameraHandler):
PackageManager packageManager = context.getPackageManager();
Issue
Basically, the issue happened because you are creating your context as follows:
public class ConDetTenthFragment extends Fragment {
Context context = getActivity();
...
}
When your Fragment is created, context = getActivity() is created also. However, at this time, your fragment is not attached yet and this way, getActivity() returns null.
I can capture an image, either through camera or gallery. I also have two imageviews to set the captured images to it. But I always get the failed binder transaction when I try to start an intent with the passed two compressed bitmaps:
public class PostFragment extends Fragment implements OnClickListener {
View post_view;
Button button1, button0;
ActionBar actionBar;
private Uri mImageCaptureUri;
private ImageView mImageView, mImageView2;
private AlertDialog dialog;
private String imagepath = null;
Bitmap bitmap, bitmap1, bitmap2, bitmap_image1, bitmap_image2;
String krt, krt1, krt2;
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
post_view = inflater.inflate(R.layout.postoffer_fragment_layout,
container, false);
getActivity().getActionBar().setIcon(R.drawable.ic_offer);
button1 = (Button) post_view.findViewById(R.id.button1);
button1.setOnClickListener(this);
button0 = (Button) post_view.findViewById(R.id.button0);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
captureImageInitialization();
mImageView = (ImageView) post_view.findViewById(R.id.imageView1);
mImageView2 = (ImageView) post_view.findViewById(R.id.imageView2);
return post_view;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
// setText() sets the string value of the TextView
Intent intent = new Intent(getActivity(), OfferInformation.class);
if (krt1 != "" && krt2 != "") {
intent.putExtra("image", krt1);
intent.putExtra("image2", krt2);
startActivity(intent);
}
}
private void captureImageInitialization() {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
/*tbd
*/
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
mImageView.setTag("2");
/*tbd
*/
}
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap1);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
byte[] imageBytes1 = baos1.toByteArray();
krt1 = Base64.encodeToString(imageBytes1, Base64.DEFAULT);
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
bitmap2 = BitmapFactory.decodeFile(imagepath);
mImageView2.setImageBitmap(bitmap2);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt2 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
}
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, proj,
null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
}
My app is set to only display in portrait mode. The problem is that I need to use a camera and a gallery intent and you can't specify those apps to be the same orientation so some funky stuff happens in between those orientation changes which makes my image data null.
This code works fine when the phone isn't tilted sideways (in portrait mode) how would I improve it to handle data after an orientation change?
public class PostPhotosActivity extends Activity {
public static final String TAG = "PostPhotosActivity";
String title, price, description, maincat, subcat, pname, pemail, pphone, pmeet, imageUri;
public static final String TEMP_PHOTO_FILE_NAME = "temp_photo.jpg";
public static final int REQUEST_CODE_GALLERY = 0x1;
public static final int REQUEST_CODE_TAKE_PICTURE = 0x2;
public static final int REQUEST_CODE_CROP_IMAGE = 0x3;
private ImageView mImageView;
private File mFileTemp;
ParseFile file;
double latitude, longitude;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //To change body of overridden methods use File | Settings | File Templates.
setContentView(R.layout.activity_post_photos);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
title = extras.getString("TITLE"); // get the value based on the key
price = extras.getString("PRICE"); // get the value based on the key
description = extras.getString("DESCRIPTION"); // get the value based on the key
maincat = extras.getString("MAINCAT"); // get the value based on the key
subcat = extras.getString("SUBCAT"); // get the value based on the key
pname = extras.getString("PNAME"); // get the value based on the key
pemail = extras.getString("PEMAIL"); // get the value based on the key
pphone = extras.getString("PPHONE"); // get the value based on the key
pmeet = extras.getString("PMEET"); // get the value based on the key
}
button = (Button) findViewById(R.id.post_data);
button.setVisibility(View.INVISIBLE);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(PostPhotosActivity.this);
/**
* Set GPS Location fetched address
*/
if (mGpsLocationTracker.canGetLocation())
{
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
Log.i(TAG, String.format("latitude: %s", latitude));
Log.i(TAG, String.format("longitude: %s", longitude));
}
else
{
mGpsLocationTracker.showSettingsAlert();
}
ParseGeoPoint point = new ParseGeoPoint(latitude, longitude);
ParseObject setPost = new ParseObject("testData");
// Create an author relationship with the current user
setPost.put("author", ParseUser.getCurrentUser());
// Get location
setPost.put("location", point);
setPost.put("Title", title);
setPost.put("Price", price);
setPost.put("Description", description);
setPost.put("MainCat", maincat);
setPost.put("SubCat", subcat);
setPost.put("PName", pname);
setPost.put("PEmail", pemail);
setPost.put("PPhone", pphone);
setPost.put("PMeet", pmeet);
setPost.put("Photo", file);
setPost.saveInBackground();
Intent intent = new Intent(PostPhotosActivity.this, Flow.class);
startActivity(intent);
}
});
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
takePicture();
} else { // pick from file
openGallery();
}
}
});
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.iv_photo);
mImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE_NAME);
}
else {
mFileTemp = new File(getFilesDir(), TEMP_PHOTO_FILE_NAME);
}
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
}
else {
/*
* The solution is taken from here: http://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder
*/
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "cannot take picture", e);
}
}
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
private void startCropImage() {
Intent intent = new Intent(this, CropImage.class);
intent.putExtra(CropImage.IMAGE_PATH, mFileTemp.getPath());
intent.putExtra(CropImage.SCALE, true);
intent.putExtra(CropImage.ASPECT_X, 1);
intent.putExtra(CropImage.ASPECT_Y, 1);
startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Bitmap bitmap;
switch (requestCode) {
case REQUEST_CODE_GALLERY:
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
startCropImage();
} catch (Exception e) {
Log.e(TAG, "Error while creating temp file", e);
}
break;
case REQUEST_CODE_TAKE_PICTURE:
startCropImage();
break;
case REQUEST_CODE_CROP_IMAGE:
String path = data.getStringExtra(CropImage.IMAGE_PATH);
if (path == null) {
return;
}
//byte[] idata = path.getBytes();
Bitmap picture = BitmapFactory.decodeFile(path);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.JPEG, 100, stream);
// get byte array here
byte[] idata= stream.toByteArray();
file = new ParseFile("photo.jpg", idata);
file.saveInBackground();
bitmap = BitmapFactory.decodeFile(mFileTemp.getPath());
mImageView.setImageBitmap(bitmap);
button.setVisibility(View.VISIBLE);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public static void copyStream(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
]
You could use fragments to retain the information that is being lost by the orientation change.
http://www.vogella.com/articles/AndroidFragments/article.html#headlessfragments2