Hi all when i try to select an image profile if i try to upload a photo from camera all works good, but if i upload a photo from gallery i not show anything. The function for opening the gallery and select the photo works but after selected the photo she should appear but not appear anything.
Hope you help me. Thank you.
Here is the code :
public class UpdateProfileActivity extends AppCompatActivity {
Toolbar toolbar;
ImageView imgProfile;
Button btnSaveProfile,btnMyadd;
EditText edtName,edtEmail,edtNumber,edtWebsite;
TextView txtname,txtEmail,txtNumber,txtWebsite;
ProgressDialog progressBar;
String name,email,number,website;
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
File file;
boolean isphotoselected = false;
private SharedPreferences pref;
Typeface typeface;
String advertId,advertUserName,advertPassword,advertEmail,advertPhone,advertSite,advertImage;
boolean AddFlag= false;
MarshMallowPermission marshMallowPermission;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_updateprofile);
toolbar = (Toolbar) findViewById(R.id.toolbar);
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
if (toolbar != null) {
toolbar.setTitle("Profile Update");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
marshMallowPermission = new MarshMallowPermission(this);
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
}
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
}
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
}
imgProfile = (ImageView)findViewById(R.id.imgProfile);
btnMyadd = (Button)findViewById(R.id.btnMyadd);
btnSaveProfile=(Button)findViewById(R.id.btnSaveprofile);
edtEmail = (EditText)findViewById(R.id.edtEmailid);
edtName = (EditText)findViewById(R.id.edtName);
edtNumber = (EditText)findViewById(R.id.edtphone);
edtWebsite= (EditText)findViewById(R.id.edtwebsite);
txtEmail = (TextView)findViewById(R.id.txtEmail);
txtname = (TextView)findViewById(R.id.txtName);
txtNumber = (TextView)findViewById(R.id.txtPhone);
txtWebsite= (TextView)findViewById(R.id.txtWeb);
btnMyadd.setTypeface(typeface);
btnSaveProfile.setTypeface(typeface);
edtEmail.setTypeface(typeface);
edtName.setTypeface(typeface);
edtNumber.setTypeface(typeface);
edtWebsite.setTypeface(typeface);
txtEmail.setTypeface(typeface);
txtname.setTypeface(typeface);
txtNumber.setTypeface(typeface);
txtWebsite.setTypeface(typeface);
pref = getSharedPreferences("loginpreference", MODE_PRIVATE);
imgProfile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startDialog();
}
});
btnSaveProfile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
name = edtName.getText().toString();
number = edtNumber.getText().toString();
email = edtEmail.getText().toString();
website= edtWebsite.getText().toString();
boolean flag = emailValidator(email);
if(name.equalsIgnoreCase("")){
edtName.setError("Please Enter Name");
}else if(number.equalsIgnoreCase("")){
edtNumber.setError("Please Enter Contact Number");
}else if(flag == false){
edtEmail.setError("Please Enter Email");
}else if(website.equalsIgnoreCase("")){
edtWebsite.setError("Please Enter Website");
}else if(selectedImagePath.equalsIgnoreCase("") || selectedImagePath==null){
Toast.makeText(getApplicationContext(), "Please Select Profile Picture", Toast.LENGTH_SHORT).show();
}else {
new UpdateProfileTask().execute();
}
}
});
btnMyadd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(!AddFlag){
Toast.makeText(UpdateProfileActivity.this, "Please Update Your Profile", Toast.LENGTH_SHORT).show();
}else{
AddFlag = true;
Intent intent =new Intent(UpdateProfileActivity.this, MyAdsActivity.class);
intent.putExtra("advertId", advertId);
startActivity(intent);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
public boolean emailValidator(String s)
{
return Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$").matcher(s).matches();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class UpdateProfileTask extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd= new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(UpdateProfileActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
jsonStr = uploadFile();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
cd.dismissdialog();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String responce = jsonObj.getString(Constants.LOGIN_TAG);
String msg = jsonObj.getString(Constants.REG_TAG);
if(responce.equalsIgnoreCase("success")){
JSONArray jArray = jsonObj.getJSONArray("data");
if(jArray.length()>0){
JSONObject j1 = jArray.getJSONObject(0);
advertId = j1.getString("advertId");
advertUserName = j1.getString("advertUserName");
advertPassword = j1.getString("advertPassword");
advertEmail = j1.getString("advertEmail");
advertPhone = j1.getString("advertPhone");
advertSite = j1.getString("advertSite");
advertImage = j1.getString("advertImage");
AddFlag = true;
}
Toast.makeText(UpdateProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(UpdateProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
}
edtEmail.setText("");
edtName.setText("");
edtNumber.setText("");
edtWebsite.setText("");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.WEBURL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
}
});
if(isphotoselected){
file = new File(selectedImagePath);
//entity.addPart("userfile",selectedImagePath.toString();
entity.addPart("avtar", new FileBody(file));
//entity.addPart("filesArray[]",new FileBody(file));
isphotoselected = false;
}
String advartid = pref.getString("advertId", "");
entity.addPart("action", new StringBody("updateAccount"));
entity.addPart("advertId", new StringBody(advartid));
entity.addPart("username", new StringBody(name));
entity.addPart("email", new StringBody(email));
entity.addPart("phone", new StringBody(number));
entity.addPart("site", new StringBody(website));
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
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE)
onSelectFromGalleryResult(data);
else if (requestCode == CAPTURE_IMAGE)
onCaptureImageResult(data);
else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
}
//onCaptureFromCamera
private void onCaptureImageResult(Intent data) {
beginCrop(data.getData());
}
//onSelectFromGalleryResult()
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
beginCrop(selectedImageUri);
}
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = handleSamplingAndRotationBitmap(this, Crop.getOutput(result));
saveToInternalStorage(bitmap);
mUserProfilePhoto.setImageBitmap(readFromInternalStorage("profile.png"));
}catch (IOException e){ /* do nothing here */}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
Handle cropping in this method:
private static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage) throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
private static 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) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
//save to internal storage
private boolean saveToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("profile.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
//read from storage
private Bitmap readFromInternalStorage(String filename){
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
return BitmapFactory.decodeStream(fi);
} catch (Exception ex) { /* do nothing here */}
return null;
}
//inside onResume
#Override
public void onResume(){
super.onResume();
Bitmap savedProfilePhoto = readFromInternalStorage("profile.png");
if (savedProfilePhoto != null){
mUserProfilePhoto.setImageBitmap(savedProfilePhoto);
}
}
private void startDialog()
{
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Upload Pictures Option");
builder.setMessage("How do you want to set your picture?");
builder.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""),PICK_IMAGE);
}
});
builder.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
builder.show();
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
Add this to build.gradle dependencies:
dependencies{
compile 'com.soundcloud.android:android-crop:1.0.1#aar'
}
Then add this to your AndroidManifest file:
<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>
Try this:
Since you have already done the selecting from your Gallery:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
}
Now, the method onSelectFromGalleryResult(data):
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
beginCrop(selectedImageUri);
}
If you are going to crop your images;
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = handleSamplingAndRotationBitmap(this, Crop.getOutput(result));
saveToInternalStorage(bitmap);
mUserProfilePhoto.setImageBitmap(readFromInternalStorage("profile.png"));
}catch (IOException e){ /* do nothing here */}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
Then if you need to rotate it automatically,
private static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage) throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
private static 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) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
To save your image in your device internal storage:
private boolean saveToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("profile.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
To read from storage:
private Bitmap readFromInternalStorage(String filename){
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
return BitmapFactory.decodeStream(fi);
} catch (Exception ex) { /* do nothing here */}
return null;
}
To set on ImageView:
#Override
public void onResume(){
super.onResume();
Bitmap savedProfilePhoto = readFromInternalStorage("profile.png");
if (savedProfilePhoto != null){
mUserProfilePhoto.setImageBitmap(savedProfilePhoto);
}
}
To finish things up, if you want to add cropping,
Almost done here:
Add this to your dependencies (build.gradle)
dependencies{
compile 'com.soundcloud.android:android-crop:1.0.1#aar'
}
Finally, in your android manifest file, for cropping library to work, add this:
<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>
That is all you need to enable selecting image from gallery or taking photo using your camera inside your app!
Related
I have a project and i am using airlocation library for one activity to fetch the location. App is working fine at my end but the playstore reports show some frequent crashes and i am trying to debug it.
Here is my activity code
public class Selfie extends AppCompatActivity {
private AirLocation airLocation;
public static final String TAG = "SelfieAct";
private static final int REQUEST = 1856;
private TextView Time, location;
Button time_stamp, lcn_btn, Atten_btn;
private static final String TIME_STAMP = null;
NetworkController networkController;
private Button cptrm_btn;
private ImageView imgview;
private static final int CAMERA_REQUEST = 1888;
SharedPreferences prefs;
Gson gson = new Gson();
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
private SharedPreferences.Editor editor;
CheckBox checkBox;
Bitmap lesimg;
private LocationManager locationManager;
private String locationText;
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
File photoFile;
boolean facelocationset = false;
TextView textView;
Uri photoUri;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selfie_activity);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
swipeRefreshLayout = findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
networkController = RetrofitClientInstance.getRetrofitInstance().create(NetworkController.class);if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};
if (!hasPermissions(Selfie.this, PERMISSIONS)) {
Toast.makeText(this, "Please allow location permission", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(Selfie.this, PERMISSIONS, REQUEST );
} else {
//do here
}
} else {
//do here
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(this, "Cannot Continue Without Location Permission", Toast.LENGTH_SHORT).show();
finish();
return;
}
Time = findViewById(R.id.time);
prefs = getSharedPreferences(getResources().getString(R.string.prefs), MODE_PRIVATE);
editor = getSharedPreferences(getResources().getString(R.string.prefs), MODE_PRIVATE).edit();
Atten_btn = findViewById(R.id.mark_Attendence);
cptrm_btn = findViewById(R.id.cptr_btn);
imgview = findViewById(R.id.imageView10);
textView=findViewById(R.id.Waitmsg);
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationText = addresses.get(0).getAddressLine(0);
textView.setText(locationText);
facelocationset = true;
}
#Override
public void onFailed(#NotNull AirLocation.LocationFailedEnum locationFailedEnum) {
// do something
}
});
cptrm_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
ex.printStackTrace();
Log.d(TAG, "onClick: " + ex.getMessage());
Log.d(TAG, "onClick: " + ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoUri = FileProvider.getUriForFile(Selfie.this, BuildConfig.APPLICATION_ID + ".provider", photoFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Atten_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(facelocationset && mImageBitmap != null) {
Date dt = new Date(System.currentTimeMillis());
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
RequestBody requestFile = RequestBody.create(
MediaType.parse(getContentResolver().getType(FileProvider.getUriForFile(Selfie.this, BuildConfig.APPLICATION_ID + ".provider", photoFile))),
photoFile
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", photoFile.getName(), requestFile);
MultipartBody.Part io_time =
MultipartBody.Part.createFormData("io_time", df.format(dt));
MultipartBody.Part user_id =
MultipartBody.Part.createFormData("user_id", prefs.getString("uid", null));
MultipartBody.Part loc =
MultipartBody.Part.createFormData("loc", locationText);
RequestBody enctype = RequestBody.create(
okhttp3.MultipartBody.FORM, "multipart/form-data");
networkController.mark_attendance("Bearer " + prefs.getString("token", null), enctype, body, io_time, user_id, loc).enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.code() == 200) {
if(response.body().get("ok").getAsString().equals("true")){
Log.d(TAG, "onResponse: " + "Done");
Toast.makeText(Selfie.this, "Punch Success", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d(TAG, "onFailure: "+ Log.getStackTraceString(t));
}
});
}
else{
Toast.makeText(Selfie.this, "Waiting for Location or Image" , Toast.LENGTH_SHORT).show();
}
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
airLocation.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
InputStream ims = getContentResolver().openInputStream(photoUri);
mImageBitmap = BitmapFactory.decodeStream(ims);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
Bitmap mImageDisplayBitmap = handleSamplingAndRotationBitmap(getApplicationContext(), photoUri);
imgview.setImageBitmap(mImageDisplayBitmap);
}
catch (IOException io){}
File file = new File (String.valueOf(photoFile));
try {
mImageBitmap = new Compressor(this)
.setMaxHeight(200) //Set height and width
.setMaxWidth(200)
.setQuality(100) // Set Quality
.compressToBitmap(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
OutputStream fOut = new FileOutputStream(file);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
}
catch(FileNotFoundException f){}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
airLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do here
} else {
Toast.makeText(Selfie.this, "The app was not allowed to read your store.", Toast.LENGTH_LONG).show();
}
}
}
}
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(context, img, selectedImage);
return img;
}
private static 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) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
}
The playstore reports show NullPointerException in this block of code
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationText = addresses.get(0).getAddressLine(0);
textView.setText(locationText);
facelocationset = true;
}
Can anyone please find out which line of code can be the cause this issue and how do i resolve it.
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
// ***** Changes *****
if (addresses != null) {
locationText = addresses.get(0).getAddressLine(0);
if (locationText != null) {
textView.setText(locationText);
}
facelocationset = true;
}
}
}
I am working on an Android project in which I have the functionality where user can click on the a button and it will open the camera to upload the image. The upload button is hidden until there is image taken and shown in preview.
What I would like to do is to use the same upload button, which I have set to visible by default now and on clicking it, I would like to open a gallery, which the user can then use to select an image, and it would be shown in preview.
I have a boolean flag to manage this, where if the flag is false, then gallery is opened, else the image in the preview is uploaded.
I have this, but I don't know how to open a gallery and then send the image to preview, to upload. I am new to Android programming, so kindly take that into consideration.
I searched for similar functionality, but the problem is, I have not found, where such features are integrated.
Java code :
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private static boolean galleryFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if(!galleryFlag){
// I think the gallery open code should come here.
}
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
}else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if(!(reducedSizeBitmap == null)){
if(reducedSizeBitmap == null){
Log.d("Image bitmap"," Is null");
}
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
}
}
}
I hope this much information is enough. Can anyone point me which functions I should put and where. Thanks a lot. :-)
Edit with Answer
Finally the integration works. I had to combine answers from the one I received and here on SO.
Final Code
public class AddPhotosForRestaurant extends RestaurantDrawerActivity {
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
private Uri imageToUploadUri = null;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private boolean galleryFlag = false;
private boolean uploadNow = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
set(null, null);
final RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox) findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if (uploadNow) {
uploadNow = false;
galleryFlag = true;
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
}
if (!galleryFlag) {
galleryFlag = true;
uploadNow = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GALLERY_INTENT_REQUEST_CODE);
} else {
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
return b;
} catch (IOException e) {
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if (imageToUploadUri != null) {
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if (reducedSizeBitmap != null) {
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
}
if (requestCode == GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
Uri selectedImage = Uri.parse(data.getDataString());
reducedSizeBitmap = MediaStore.Images.Media.getBitmap(
getApplicationContext().getContentResolver(),
selectedImage);
ImgPhoto.setImageBitmap(reducedSizeBitmap);
} catch (Exception e) {
Toast.makeText(this, "Error while selecting Image", Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if (!(reducedSizeBitmap == null)) {
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray, profilePhoto);
}
}
}
Thanks a lot for all your help.. :-)
In Constant file write in my case(ActivityConstantUtils.java)
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
To open Gallery & get path of selected image use following code :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
After that you get path in onActivityResult() method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
String imagePath = getFilePath(data);
// TODO: Here you set data to preview screen
}catch(Exception e){}
}
}
private String getFilePath(Intent data) {
String imagePath;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
I need help in improving my code .
What I am doing : There is a button in main activity, when clicked , user choose the image , after that, the image is passed through an intent to another activity(add_image.java) and displayed in an image view , after that I send the image to the server.
My problems:1) I want the best way to send the path image to second intent then convert it into image
2) then compress it as much as I can without loosing a lot of its quality.
the image size now is 376kb . so in my my app Ill displaying several images so in such size it will consume time and internet to load.( I am using picasso and fit() didnt decrease the size.)
here is my code :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
//file name
filePath = data.getData();
try {
// Bundle extras2 = data.getExtras();
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[] = stream.toByteArray();
Intent i = new Intent(this, AddImage.class);
i.putExtra("image", imageInByte);
startActivity(i);
} catch (IOException e) {
e.printStackTrace(); } } }
And here I am receiving the image
byte[] byteArray = getIntent().getByteArrayExtra("image");
encodedImage = Base64.encodeToString(byteArray, Base64);
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView imageview = (ImageView) findViewById(R.id.imageView);
imageview.setImageBitmap(bmp);
Try following code, you might need to modify some of the parameters as per your requirement :
Create MainActivity as following :
public class MainActivity extends Activity implements OnClickListener {
private final int REQUEST_IMAGE_GALLERY = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
pickImageFromGallery();
break;
default:
break;
}
}
private void pickImageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"),
REQUEST_IMAGE_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_IMAGE_GALLERY) {
Uri selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Log.e("PATH", "" + picturePath);
Intent intent = new Intent(this, AddImage.class);
intent.putExtra("PATH", picturePath);
startActivity(intent);
}
}
}
Now create activity_main.xml as follows :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ChooseButton" />
</LinearLayout>
Then we need to create AddImage activity as follows :
public class AddImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_image);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
if (getIntent() != null) {
String path = getIntent().getStringExtra("PATH");
Log.e("PATHR", "" + path);
new BitmapWorkerTask(imageView).execute(path);
}
}
private boolean isNeedToBeScaled(String path) {
File file = new File(path);
if (file.length() > (1024 * 1024) && isExist(path)) {
Log.e("SCALEIMAGE", "SACLE");
return true;
}
return false;
}
private boolean isExist(String path) {
File file = new File(path);
return file.exists();
}
private Bitmap getScaledImage(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int srcWidth = options.outWidth;
int srcHeight = options.outHeight;
int[] newWH = new int[2];
newWH[0] = srcWidth / 2;
newWH[1] = (newWH[0] * srcHeight) / srcWidth;
int inSampleSize = 2;
while (srcWidth / 2 >= newWH[0]) {
srcWidth /= 2;
srcHeight /= 2;
inSampleSize *= 2;
options.inJustDecodeBounds = false;
options.inDither = false;
options.inSampleSize = inSampleSize;
options.inScaled = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
}
Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(path, options);
return sampledSrcBitmap;
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView mImageView) {
imageViewReference = new WeakReference<ImageView>(mImageView);
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap scaled = null;
if (isNeedToBeScaled(params[0])) {
Bitmap d;
d = getScaledImage(params[0]);
int nh = (int) (d.getHeight() * (512.0 / d.getWidth()));
scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
} else {
scaled = BitmapFactory.decodeFile(params[0], null);
}
return scaled;
}
#Override
protected void onPostExecute(Bitmap result) {
if (imageViewReference != null && result != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(result);
imageView.setVisibility(View.VISIBLE);
}
}
}
}
}
In my app I take picture from camera and preview it. My app takes picture in landscape mode so that I changed it to portrait mode using exifInterface but I get stretched image.
How can I redraw my Image with out stretched image from the bitmap. if I take picture in landscape mode, it looks good.
this is my code for camera part:
public class TakePic extends Fragment {
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.add_spot_2, container, false);
....
upload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String path = Environment.getExternalStorageDirectory()
+ "/pic";
File photopath = new File(path);
if (!photopath.exists()) {
photopath.mkdir();
}
imagePath = new File(photopath, "pic"
+ System.currentTimeMillis() + ".png");
DataPassing.imagePath = imagePath;
if(imageUri==null){
Log.e("Image uri is null", "Image uri is null 1");
}
else{
Log.e("Image uri is NOT null", "Image uri is NOT null 1");
}
Log.e("file path ", imagePath.getAbsolutePath());
imageUri = Uri.fromFile(imagePath);
DataPassing.imageUri = imageUri;
if(imageUri==null){
Log.e("Image uri is null ", "Image uri is null 2");
}
else{
Log.e("Image uri is NOT null", "Image uri is NOT null 2");
}
Log.e("uri file path ", imageUri.getPath());
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(imagePath));
startActivityForResult(intent, 100);
}
});
........
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#SuppressWarnings({ "deprecation" })
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
if (DataPassing.imageUri == null) {
Toast.makeText(getActivity(), "Please retry",
Toast.LENGTH_SHORT).show();
} else {
Bitmap bm = readBitmap(DataPassing.imageUri);
int or = 0;
try {
or = resolveBitmapOrientation(DataPassing.imagePath);
Log.e("int", String.valueOf(or));
} catch (IOException e) {
e.printStackTrace();
}
if(or==1){
image.setBackgroundDrawable(new BitmapDrawable(bm));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] array = stream.toByteArray();
AddNewSpotValues.comm_2_picture_path = array;
DataPassing.addspot2_bm = bm;
}
else{
int w = bm.getWidth();
int h = bm.getHeight();
Log.e("w & h", ""+w + " & " + h);
Matrix mtx = new Matrix();
mtx.postRotate(90);
Bitmap rbm = Bitmap.createBitmap(bm, 0, 0, w, h, mtx, true);
// Bitmap rbm = Bitmap.createBitmap(bm, 0, 0, 200,150, mtx, true);
image.setBackgroundDrawable(new BitmapDrawable(rbm));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
rbm.compress(Bitmap.CompressFormat.PNG, 100, stream);
DataPassing.addspot2_bm = rbm;
byte[] array = stream.toByteArray();
AddNewSpotValues.comm_2_picture_path = array;
}
}
}
}
#Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
private Bitmap readBitmap(Uri selectedImage) {
try {
File f = new File(selectedImage.getPath());
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 100;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
private int resolveBitmapOrientation(File bitmapFile) throws IOException {
ExifInterface exif = null;
exif = new ExifInterface(bitmapFile.getAbsolutePath());
return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
}
}
You might need to open your camera in portrait mode instead of manipulating the image itself accepted answer here show you how to do it
currently I'm working with the image capture using some devices. Well now I'm testing it using an Optimus G and Samsung Galaxy tab to be specific on the device. Now I already managed to capture an image, save it then preview it on an ImageView. It works just fine anyways but whenever I tried to capture an image on portrait mode then save it in landscape mode the intent then changes layout fast from landscape to portrait then landscape then goes back to my app in portrait but the app then stops working. I don't know why does this happen and I can't get the logs from the phone since I don't have the drivers to run the adb logcat. This happens most on the optimus G device anyways. Though if I capture it on landscape then save it on landscape it works just fine. really weird.
As for my code for capture here it is:
public void captureImage() {
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getActivity().startActivityForResult(cameraIntent, capture_image);
} catch (Exception e){
e.printStackTrace();
Toast.makeText(getActivity(),"Something went wrong",Toast.LENGTH_SHORT).show();
}
}
Okay I tried to use force portrait mode but nothing happens.
and here's on my onActivityResult:
if(requestCode == capture_image){
if(resultCode == Activity.RESULT_OK){
//Get the path of the captured image
Uri image_uri = data.getData();
String path = getPath(image_uri);
//send path to FragmentCamera
FragmentCamera.file_path = path;
//create thumbnail for display
File file = new File(FragmentCamera.file_path );
try {
Bitmap thumbnail;
thumbnail = applyOrientation(decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250), resolveBitmapOrientation(file));
FragmentCamera.thumb_receipt.setImageBitmap(thumbnail);
} catch (IOException e) {
e.printStackTrace();
}
}
}
and here's the fixers for the image captured I added:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private int resolveBitmapOrientation(File bitmapFile) throws IOException {
ExifInterface exif = null;
exif = new ExifInterface(bitmapFile.getAbsolutePath());
return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
private Bitmap applyOrientation(Bitmap bitmap, int orientation) {
int rotate = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
default:
return bitmap;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
Hope someone can help me why does this problem happens.
UPDATES:
I got the logs now and here's the error I got:
E/WindowManager: Activity com.mark.exercise.TabMainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42cdfff0 that was originally added here
android.view.WindowLeaked: Activity com.mark.exercise.TabMainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42cdfff0 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:378)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:324)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:256)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:153)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:282)
at com.mark.exercise.TabMainActivity$GetListTask.onPreExecute(TabMainActivity.java:372)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.mark.exercise.TabMainActivity.getShoppingList(TabMainActivity.java:330)
at com.mark.exercise.TabMainActivity.onCreate(TabMainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:5236)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2037)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2098)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3576)
at android.app.ActivityThread.access$700(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4911)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
11-13 17:55:34.228 747-747/? D/StatusBar.NetworkController: refreshViews connected={ wifi } level=5 combinedSignalIconId=0x7f02039b/com.android.systemui:drawable/stat_sys_wifi_signal_3_fully combinedActivityIconId=0x7f020393 mobileLabel=Globe wifiLabel=WiFixxxxXXXXxxxxXXXX emergencyOnly=false combinedLabel=WiFixxxxXXXXxxxxXXXX mAirplaneMode=false mDataActivity=0 mPhoneSignalIconId=0x7f020366 mDataDirectionIconId=0x0 mDataSignalIconId=0x7f020366 mDataTypeIconId=0x0 mNoSimIconId=0x0 mThirdTypeIconId=0x0 mWifiIconId=0x7f02039b mBluetoothTetherIconId=0x108054f
11-13 17:55:34.418 12444-12444/? E/CameraApp: [SoundController.java:483:onDestroy()] onDestroy-start, sound_pool release 1/2
11-13 17:55:34.428 12444-12444/? E/CameraApp: [SoundController.java:525:onDestroy()] onDestroy-end, sound_pool release 2/2
11-13 17:55:34.628 13627-13627/com.mark.exercise E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalArgumentException: View not attached to window manager
at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:685)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:381)
at android.view.WindowManagerImpl$CompatModeWrapper.removeView(WindowManagerImpl.java:164)
at android.app.Dialog.dismissDialog(Dialog.java:347)
at android.app.Dialog.dismiss(Dialog.java:330)
at com.mark.exercise.TabMainActivity$GetListTask.onPostExecute(TabMainActivity.java:379)
at com.mark.exercise.TabMainActivity$GetListTask.onPostExecute(TabMainActivity.java:337)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4911)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
11-13 17:55:34.628 536-547/? W/ActivityManager: Force finishing activity com.mark.exercise/.TabMainActivity
11-13 17:55:35.159 536-550/? W/ActivityManager: Activity pause timeout for ActivityRecord{42b81c88 com.mark.exercise/.TabMainActivity}
11-13 17:55:35.349 1298-1342/? E/ThermalDaemon: [GPU_MON] 0 percent. Current Sampling Time is 4 sec
Okay for what I see in here, the app goes back in creating the activity after the camera intent. since the part of the getList method was only fired onCreate. This is getting weird for me.
Added:
TabMainActivity.java
public class TabMainActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
ArrayList<String> ids = new ArrayList<String>();
private Map hash_values = new HashMap();
String uid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bottom_tabs);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("uid",getIntent().getStringExtra("user_id"));
editor.commit();
uid = getIntent().getStringExtra("user_id");
getShoppingList(uid);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle b = new Bundle();
b.putString("0", "Me");
mTabHost.addTab(mTabHost.newTabSpec("me").setIndicator(null,getResources().getDrawable(R.drawable.selector_me)),
FragmentMe.class, b);
b = new Bundle();
b.putString("1", "Social");
mTabHost.addTab(mTabHost.newTabSpec("social").setIndicator(null, getResources().getDrawable(R.drawable.selector_social)),
FragmentSocial.class, b);
b.putString("2", "Promo");
mTabHost.addTab(mTabHost.newTabSpec("promo").setIndicator(null,getResources().getDrawable(R.drawable.selector_promo)),
FragmentPromo.class, b);
b = new Bundle();
b.putString("3", "Camera");
mTabHost.addTab(mTabHost.newTabSpec("camera").setIndicator(null,getResources().getDrawable(R.drawable.selector_capture)),
FragmentCamera.class, b);
b.putString("4", "List");
mTabHost.addTab(mTabHost.newTabSpec("shopping_list").setIndicator(null,getResources().getDrawable(R.drawable.selector_shopping_list)),
FragmentViewPager.class, b);
}
private static final int capture_image = 1;
private static final int select_image = 2;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == capture_image){
if(resultCode == Activity.RESULT_OK){
//Get the path of the captured image
Uri image_uri = data.getData();
String path = getPath(image_uri);
//send path to FragmentCamera
FragmentCamera.file_path = path;
//create thumbnail for display
File file = new File(FragmentCamera.file_path );
try {
Bitmap thumbnail;
thumbnail = applyOrientation(decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250), resolveBitmapOrientation(file));
FragmentCamera.thumb_receipt.setImageBitmap(thumbnail);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(requestCode == select_image){
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
//Get the path of the selected image
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String path = cursor.getString(columnIndex);
cursor.close();
//send path to FragmentCamera
FragmentCamera.file_path = path;
//create thumbnail for display
FragmentCamera.file_path = path;
//create thumbnail for display
File file = new File(FragmentCamera.file_path );
try {
Bitmap thumbnail;
thumbnail = applyOrientation(decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250), resolveBitmapOrientation(file));
FragmentCamera.thumb_receipt.setImageBitmap(thumbnail);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
Cursor cursor = null;
int column_index = 0;
try {
String[] projection = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(uri, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
} catch (Exception e) {
Log.d("Error", "Exception Occured", e);
}
return cursor.getString(column_index);
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private int resolveBitmapOrientation(File bitmapFile) throws IOException {
ExifInterface exif = null;
exif = new ExifInterface(bitmapFile.getAbsolutePath());
return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
private Bitmap applyOrientation(Bitmap bitmap, int orientation) {
int rotate = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
default:
return bitmap;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
private Bitmap createThumbnail(String image_path){
Bitmap thumb=null;
Bitmap get_image = BitmapFactory.decodeFile(image_path);
int h = 500;
int w = 500;
thumb = Bitmap.createScaledBitmap(get_image,h, w, true);
return thumb;
}
public void getShoppingList(String user_id){
try{
HashMap params = new HashMap<String,String>();
params.put("uid", user_id);
params.put("url", "http://ec2-54-254-129-196.ap-southeast-1.compute.amazonaws.com/get_shoplist.php");
//pass parameters
hash_values.putAll(params);
//start async task
new GetListTask().execute(hash_values);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
public class GetListTask extends AsyncTask<Map, Integer, Void> {
ProgressDialog progressDialog;
String json_response = null;
#Override
protected Void doInBackground(Map... maps) {
json_response = getShoppingListResponse(maps[0]);
int i = 0;
while (i <= 10) {
try {
Thread.sleep(50);
publishProgress(i);
i++;
}
catch (Exception e) {
Log.i("The progress", e.getMessage());
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
progressDialog.setProgress(progress[0]*10);
}
#Override
protected void onPreExecute() {
/*Do something before the async task starts*/
progressDialog = new ProgressDialog(TabMainActivity.this);
progressDialog.setMessage("Getting your shopping list");
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
//progressDialog = ProgressDialog.show(getActivity(), "Loading", "Getting the updated list, please wait a moment");
}
protected void onPostExecute(Void v) {
setJSONtoList(json_response);
progressDialog.dismiss();
}
}
private void setJSONtoList(String response){
try{
JSONArray jArray = new JSONArray(response);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
DatabasePrefs dbPref = new DatabasePrefs(getBaseContext());
dbPref.insertShoppingList(Integer.parseInt(json_data.getString("idlist")),Integer.parseInt(uid),json_data.getString("list_name"));
//TODO check
ids.add(json_data.getString("idlist"));
}
}catch(JSONException e){
Log.v("Problem", "Error parsing data " + e.toString());
}
new getListThread().execute();
}
int ctr = 0;
public class getListThread extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try{
getListContent(ids.get(ctr));
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
ctr++;
if(ctr < ids.size()){
new getListThread().execute();
}
}
}
public void getListContent(String id){
try{
HashMap params = new HashMap<String,String>();
params.put("idlist", id);
params.put("url", "http://ec2-54-254-129-196.ap-southeast-1.compute.amazonaws.com/get_list_items.php");
//pass parameters
hash_values.putAll(params);
//start async task
new CreateNewList().execute(hash_values);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(TabMainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
public class CreateNewList extends AsyncTask<Map, Void, Void> {
FragmentShoppingList fsl = new FragmentShoppingList();
String response;
#Override
protected Void doInBackground(Map... maps) {
//reused method
response = fsl.getShoppingListResponse(maps[0]);
return null;
}
protected void onPostExecute(Void v) {
setJSONtoListItems(response);
Log.v("The id of the list", response);
}
}
private void setJSONtoListItems(String response){
try{
JSONArray jArray = new JSONArray(response);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String id = json_data.getString("id_list_content");
String list_id = json_data.getString("idlist");
String item_id = json_data.getString("iditem");
String item_name = json_data.getString("name");
String item_price = json_data.getString("price");
String was_price = json_data.getString("was_price");
DatabasePrefs db = new DatabasePrefs(TabMainActivity.this);
db.insertItem(Long.parseLong(id), Integer.parseInt(list_id), Integer.parseInt(item_id), item_name, item_price, was_price);
Log.v("The result",id+","+list_id+","+item_id+","+item_name+","+item_price+","+was_price);
}
}catch(JSONException e){
Log.v("Problem", "Error parsing data " + e.toString());
}
}
public String getShoppingListResponse(Map hash_values){
String response = "";
InputStream is = null;
StringBuilder string_builder = null;
String url = hash_values.get("url").toString().replace(" ", "%20"); //get the URL replacing the space with %20
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
/*This will convert the hashMap sent into individual part per key per value*/
Set set = hash_values.entrySet();
Iterator iterator = set.iterator();
/*do a loop passing all the data on a string*/
while(iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry)iterator.next();
String keyword = String.valueOf(mapEntry.getKey());
String value = String.valueOf(mapEntry.getValue());
/*this will check if the passed data is a URL, file or a simple value*/
if(!keyword.equals("url")){
if(value.matches("(.*)/(.*)")){
File file = new File(value);
Log.v("Does this exists?", String.valueOf(file.exists()));
if(file.exists()){
FileBody upload_file;
upload_file = new FileBody(file);
/*not url but file*/
mpEntity.addPart(keyword, upload_file);
}else{
/*not url and not file*/
mpEntity.addPart(keyword, new StringBody(value));
}
}else{
/*not URL and not file*/
mpEntity.addPart(keyword, new StringBody(value));
}
}
}
post.setEntity(mpEntity);
HttpResponse http_res = client.execute(post);
HttpEntity resEntity = http_res.getEntity();
is = resEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
response = "";
}
/*convert JSON to string*/
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
string_builder = new StringBuilder();
String line = "0";
while ((line = reader.readLine()) != null) {
string_builder.append(line + "\n");
}
is.close();
response = string_builder.toString();
}catch(Exception e){
e.printStackTrace();
}
return response;
}
}
Your analysis is correct. On some devices, especially with smaller RAM, camera capture activity (invoked via intent) may cause the calling activity to be destroyed. Threfore, onCreate() should be written with this scenario in mind. Note also that onActivityResult() is usually called before onResume().
It's hard to tell more becaise you have not disclosed the code for onCreate() or other relevant methods of your TabMainActivity class.