Bundle is always null no matter what I do - java

Everytime I try to go between activities, I save the editText texts because user experience and all that, but for some reason, while intents get through no problem, the savedinstanceState just won't ever be not null. I've added the onSave and onRestore methods, overrided them, did what had to be done inside, yet it is always null. What am I missing here?
package com.gmproxy.pastilarma;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import com.gmproxy.DAO.PathologyUserRepository;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import com.gmproxy.Util.ImageConverter;
import com.gmproxy.ViewModels.UserViewModel;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserAddScreen extends AppCompatActivity {
Button gotoBack, addObservation, saveUser, addPathologies;
EditText addUsername, addSurname, addAge, addRoomNumber;
Spinner addGender;
ImageView selectImage;
String obs;
Pathology paths;
Context context;
UserViewModel userViewModel;
int pathAct = 0;
int obsAct = 0;
PathologyUserRepository paUsRe;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
context = this.getApplicationContext();
pathAct = getIntent().getIntExtra("path-record", 0);
obsAct = getIntent().getIntExtra("obs-record", 0);
paUsRe = new PathologyUserRepository(this.getApplication());
setContentView(R.layout.activity_user_add_screen);
gotoBack = findViewById(R.id.GotoBack);
addObservation = findViewById(R.id.AddObservation);
saveUser = findViewById(R.id.SaveUser);
addPathologies = findViewById(R.id.AddPathologies);
addUsername = findViewById(R.id.AddUsername);
addSurname = findViewById(R.id.AddSurname);
addAge = findViewById(R.id.AddAge);
addRoomNumber = findViewById(R.id.AddRoomNumber);
addGender = findViewById(R.id.AddGender);
selectImage = findViewById(R.id.SelectImage);
if (pathAct == 1 || obsAct == 1 && savedInstanceState!=null) {
onRestoreInstanceState(savedInstanceState);
}
if (savedInstanceState == null){
Log.println(Log.INFO,"Test","El bundle está vacio");
}
userViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(UserViewModel.class);
/*
From this line to 94, we create the spinner, since there's only two options there really is no need of poblating the list from the database.
*/
List<String> genderList = new ArrayList<>();
genderList.add("M");
genderList.add("F");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner, genderList);
adapter.setDropDownViewResource(R.layout.spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addGender.setAdapter(adapter);
addGender.setSelection(0);
if (savedInstanceState == null){
obs = intent.getStringExtra("observation");
} else {
obs = savedInstanceState.getString("Observacion-usuario");
}
if (obs != null){
Log.println(Log.INFO,"test obs", obs);
}
paths = (Pathology) intent.getSerializableExtra("paths");
}
public void gotoBack(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
}
public void addObservation(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserObservationScreen.class);
startActivity(mainAct);
finish();
}
public void addPathology(View view) {
Intent mainAct = new Intent(UserAddScreen.this, PathologiesSearchScreen.class);
startActivity(mainAct);
finish();
}
/**
* This saves all recorded data for when we come back to the activity
* #param savedInstanceState
*/
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
if (!addUsername.getText().toString().equals("")) {
savedInstanceState.putString("Nombre_usuario", addUsername.getText().toString());
}
if (!addSurname.getText().toString().equals("")) {
savedInstanceState.putString("Apellido_usuario", addSurname.getText().toString());
}
if (!addAge.getText().toString().equals("")) {
savedInstanceState.putString("Edad_usuario", addAge.getText().toString());
}
if (!addRoomNumber.getText().toString().equals("")) {
savedInstanceState.putString("Habitacion_usuario", addRoomNumber.getText().toString());
}
savedInstanceState.putInt("Sexo_usuario", addGender.getSelectedItemPosition());
if (obs != null){
savedInstanceState.putString("Observacion-usuario", obs);
}
if (paths != null){
savedInstanceState.putSerializable("Patologia-usuario", paths);
}
super.onSaveInstanceState(savedInstanceState);
Log.println(Log.INFO,"Guardado","guardado");
}
/**
* This loads up all recorded things in the view
* #param savedInstanceState
*/
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
addUsername.setText(savedInstanceState.getString("Nombre_usuario"));
addSurname.setText(savedInstanceState.getString("Apellido_usuario"));
addAge.setText(savedInstanceState.getString("Edad_usuario"));
addRoomNumber.setText(savedInstanceState.getString("Habitacion_usuario"));
addGender.setSelection(savedInstanceState.getInt("Sexo_usuario"));
obs = savedInstanceState.getString("Observacion-usuario");
paths = (Pathology) savedInstanceState.getSerializable("Patologia-usuario");
}
/*
The next two methods are for
A: Opening either the camera, gallery, or getting a picture from assets
B: Actually selecting the image and making it show in the imageButton
*/
public void selectImageAction(View view) {
final CharSequence[] options = {"Hacer una foto", "Elegir de la galería", "Usar una genérica", "Cancelar"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserAddScreen.this);
builder.setTitle("¡Añade una foto!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Hacer una foto")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivity(intent);
finish();
} else if (options[item].equals("Elegir de la galería")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivity(intent);
finish();
} else if (options[item].equals("Cancelar")) {
dialog.dismiss();
} else if (options[item].equals("Usar una genérica")) {
selectImage.setImageResource(R.drawable.ic_user_generic_foreground);
selectImage.setBackgroundResource(R.drawable.ic_user_generic_foreground);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
selectImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, System.currentTimeMillis() + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("..******************...", picturePath + "");
ImageView viewImage;
selectImage.setImageBitmap(thumbnail);
}
}
}
/**
* Actually creates the user in the database
* #param view
*/
public void saveUser(View view) {
//Just this to turn the image into a blob
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.id.SelectImage);
ImageConverter imgCon = new ImageConverter();
byte[] bytearray = imgCon.bitmapToBiteArray(bitmap);
if (addUsername.getText().toString() != null || addSurname.getText().toString() != null
|| addAge.getText().toString() != null || addRoomNumber.getText().toString() != null){
Toast.makeText(this, "Usuario creado.", Toast.LENGTH_SHORT).show();
User user = new User(addUsername.getText().toString(), addSurname.getText().toString(), addAge.getText().toString(),
Integer.parseInt(addRoomNumber.getText().toString()), addGender.getSelectedItem().toString(), obs, bytearray);
userViewModel.insert(user);
paUsRe.insertObject(userViewModel.getIdByNameAndSurname(user.getUser_name(), user.getUser_surname()), paths.getId_pathology());
Toast.makeText(this, "Patología " + paths.getPathologyName() + " añadida", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
} else {
Toast.makeText(this, "Por favor, introduce todos los parámetros necesarios.", Toast.LENGTH_SHORT).show();
}
}
}

onSaveInstanceState() is called right before your activity is about to be killed or restarted because of memory pressure or screen orientation change. Since you are just switching between activities, onSaveInstance() is not called thus the null instance. Wound suggest SharedPreference instead

Related

android version 10 its work but android version 12 camera and gallery not working when download playstore

Android version 12 camera and gallery not working solution
I am working on a camera application with camera API. I am able to save the image to the picture directory and set it to the image view till android version 11 but on android 12, the image is getting saved to the picture directory but not getting set to the image view I am getting an error
My Code is
Profile.java
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.cocosw.bottomsheet.BottomSheet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xxx.xx.view.MainFragment;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Profile extends AppCompatActivity implements View.OnClickListener {
private ActivityProfileBinding binding;
private String TAG = Profile.class.getSimpleName();
private Context mContext;
private ArrayList<ImageDTO> imageDatalist = new ArrayList<>();
private SharedPrefrence prefrence;
private LoginDTO loginDTO;
private HashMap<String, String> parms = new HashMap<>();
String dob = "";
String[] arrOfStr;
BottomSheet.Builder builder;
Uri picUri;
int PICK_FROM_CAMERA = 1, PICK_FROM_GALLERY = 2;
int CROP_CAMERA_IMAGE = 3, CROP_GALLERY_IMAGE = 4;
String imageName;
String pathOfImage;
Bitmap bm;
int flag = 1;
ImageCompression imageCompression;
byte[] resultByteArray;
File file;
Bitmap bitmap = null;
private HashMap<String, File> paramsFile = new HashMap<>();
HashMap<String, String> values = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
mContext = Profile.this;
prefrence = SharedPrefrence.getInstance(mContext);
loginDTO = prefrence.getLoginResponse(Consts.LOGIN_DTO);
parms.put(Consts.USER_ID, loginDTO.getUser_id());
values.put(Consts.USER_ID, loginDTO.getUser_id());
setUiaction();
}
public void setUiaction() {
binding.collapsingToolbar.setExpandedTitleColor(Color.TRANSPARENT);
binding.collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
binding.collapsingToolbar.setTitle("Profile");
binding.rlBio.setOnClickListener(this);
binding.ivCamera.setOnClickListener(this);
binding.rlGallaryClick.setOnClickListener(this);
binding.back.setOnClickListener(this);
binding.ivEditSelf.setOnClickListener(this);
binding.ivEditAbout.setOnClickListener(this);
binding.ivEditAppearance.setOnClickListener(this);
binding.ivEditImportant.setOnClickListener(this);
binding.ivEditCritical.setOnClickListener(this);
binding.ivEditLifestyle.setOnClickListener(this);
binding.ivEditFamily.setOnClickListener(this);
builder = new BottomSheet.Builder(Profile.this).sheet(R.menu.menu_cards);
builder.title(getResources().getString(R.string.select_img));
builder.listener(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case R.id.camera_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
ProjectUtils.pauseProgressDialog();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);
picUri = FileProvider.getUriForFile(Profile.this.getApplicationContext(), Profile.this.getApplicationContext().getPackageName() + ".fileprovider", file);
} else {
picUri = Uri.fromFile(file); // create
}
prefrence.setValue(Consts.IMAGE_URI_CAMERA, picUri.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri); // set the image file
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case R.id.gallery_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
picUri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_pic)), PICK_FROM_GALLERY);
}
}
break;
case R.id.cancel_cards:
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
});
break;
}
}
});
}
private File getOutputMediaFile(int type) {
String root = Environment.getExternalStorageDirectory().toString();
File mediaStorageDir = new File(root, Consts.APP_NAME);
/**Create the storage directory if it does not exist*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
Consts.APP_NAME + timeStamp + ".png");
imageName = Consts.APP_NAME + timeStamp + ".png";
} else {
return null;
}
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CROP_CAMERA_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
//bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
// bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
Log.e("image", imagePath);
changeImage();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == CROP_GALLERY_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
bm = MediaStore.Images.Media.getBitmap(Profile.this.getContentResolver(), picUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
changeImage();
Log.e("image", imagePath);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == PICK_FROM_CAMERA && resultCode == RESULT_OK) {
if (picUri != null) {
picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
} else {
picUri = Uri.parse(prefrence
.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
}
}
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
try {
Uri tempUri = data.getData();
Log.e("front tempUri", "" + tempUri);
if (tempUri != null) {
startCropping(tempUri, CROP_GALLERY_IMAGE);
} else {
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public void startCropping(Uri uri, int requestCode) {
Intent intent = new Intent(Profile.this, MainFragment.class);
intent.putExtra("imageUri", uri.toString());
intent.putExtra("requestCode", requestCode);
startActivityForResult(intent, requestCode);
}
#Override
protected void onResume() {
super.onResume();
if (NetworkManager.isConnectToInternet(mContext)) {
getImages();
} else {
ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_concation));
}
}
public void getImages() {
new HttpsRequest(Consts.GET_GALLARY_API, parms, mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
getMyProfile();
if (flag) {
try {
imageDatalist = new ArrayList<>();
Type getpetDTO = new TypeToken<List<ImageDTO>>() {
}.getType();
imageDatalist = (ArrayList<ImageDTO>) new Gson().fromJson(response.getJSONArray("data").toString(), getpetDTO);
if (imageDatalist.size() > 0) {
} else {
imageDatalist = new ArrayList<>();
}
} catch (JSONException e) {
e.printStackTrace();
imageDatalist = new ArrayList<>();
}
} else {
imageDatalist = new ArrayList<>();
}
}
});
}
#Override
public void onBackPressed() {
//super.onBackPressed();
finish();
overridePendingTransition(R.anim.anim_slide_in_right,
R.anim.anim_slide_out_right);
}
public void getMyProfile() {
ProjectUtils.showProgressDialog(mContext, true, getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.MY_PROFILE_API, getparmProfile(), mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
try {
loginDTO = new Gson().fromJson(response.getJSONObject("data").toString(), LoginDTO.class);
prefrence.setLoginResponse(loginDTO, Consts.LOGIN_DTO);
showData();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ProjectUtils.showToast(mContext, msg);
}
}
});
}
public HashMap<String, String> getparmProfile() {
HashMap<String, String> parms = new HashMap<>();
parms.put(Consts.USER_ID, loginDTO.getUser_id());
Log.e(TAG + " My Profile", parms.toString());
return parms;
}
public void changeImage() {
new HttpsRequest(Consts.SET_PROFILE_IMAGE_API, values,paramsFile, mContext).imagePost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
getMyProfile();
} else {
}
}
});
}
}
MainFragment.java
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import com.xxx.xx.R;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.CropCallback;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.isseiaoki.simplecropview.callback.SaveCallback;
import com.isseiaoki.simplecropview.util.Utils;
import java.io.File;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
#RuntimePermissions
public class MainFragment extends FragmentActivity {
private static final int REQUEST_PICK_IMAGE = 10011;
private static final int REQUEST_SAF_PICK_IMAGE = 10012;
private static final String PROGRESS_DIALOG = "ProgressDialog";
Uri myUri;
int requestCode;
private CropImageView mCropView;
private LinearLayout mRootLayout;
public MainFragment() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
myUri = Uri.parse(getIntent().getExtras().getString("imageUri"));
requestCode = getIntent().getExtras().getInt("requestCode");
bindViews();
FontUtils.setFont(mRootLayout);
mCropView.startLoad(myUri, mLoadCallback);
mCropView.setCropMode(CropImageView.CropMode.FREE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = result.getData().toString();
mCropView.startLoad(result.getData(), mLoadCallback);
} else if (requestCode == REQUEST_SAF_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = Utils.ensureUriPermission(this, result).toString();
mCropView.startLoad(Utils.ensureUriPermission(this, result), mLoadCallback);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
MainFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
private void bindViews() {
mCropView = (CropImageView) findViewById(R.id.cropImageView);
findViewById(R.id.buttonDone).setOnClickListener(btnListener);
findViewById(R.id.buttonFitImage).setOnClickListener(btnListener);
findViewById(R.id.button1_1).setOnClickListener(btnListener);
findViewById(R.id.button3_4).setOnClickListener(btnListener);
findViewById(R.id.button4_3).setOnClickListener(btnListener);
findViewById(R.id.button9_16).setOnClickListener(btnListener);
findViewById(R.id.button16_9).setOnClickListener(btnListener);
findViewById(R.id.buttonFree).setOnClickListener(btnListener);
findViewById(R.id.buttonPickImage).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateLeft).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateRight).setOnClickListener(btnListener);
findViewById(R.id.buttonCustom).setOnClickListener(btnListener);
findViewById(R.id.buttonCircle).setOnClickListener(btnListener);
findViewById(R.id.buttonShowCircleButCropAsSquare).setOnClickListener(btnListener);
mRootLayout = (LinearLayout) findViewById(R.id.layout_root);
}
#NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
public void pickImage() {
if (Build.VERSION.SDK_INT >= 33) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), REQUEST_PICK_IMAGE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_SAF_PICK_IMAGE);
}
}
#NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void cropImage() {
showProgress();
Log.e("cropImage", "called");
mCropView.startCrop(createSaveUri(), mCropCallback, mSaveCallback);
}
#OnShowRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
public void showRationaleForPick(PermissionRequest request) {
showRationaleDialog(R.string.permission_pick_rationale, request);
}
#OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void showRationaleForCrop(PermissionRequest request) {
showRationaleDialog(R.string.permission_crop_rationale, request);
}
public void showProgress() {
ProgressDialogFragment f = ProgressDialogFragment.getInstance();
getSupportFragmentManager()
.beginTransaction()
.add(f, PROGRESS_DIALOG)
.commitAllowingStateLoss();
}
public void dismissProgress() {
// if (!isAdded()) return;
FragmentManager manager = getSupportFragmentManager();
if (manager == null) return;
ProgressDialogFragment f = (ProgressDialogFragment) manager.findFragmentByTag(PROGRESS_DIALOG);
if (f != null) {
getSupportFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public Uri createSaveUri() {
return Uri.fromFile(new File(this.getCacheDir(), "cropped"));
}
private void showRationaleDialog(#StringRes int messageResId, final PermissionRequest request) {
new AlertDialog.Builder(this)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.proceed();
}
})
.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.cancel();
}
})
.setCancelable(false)
.setMessage(messageResId)
.show();
}
// Handle button event /////////////////////////////////////////////////////////////////////////
private final View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonDone:
MainFragmentPermissionsDispatcher.cropImageWithCheck(MainFragment.this);
break;
case R.id.buttonFitImage:
mCropView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
break;
case R.id.button1_1:
mCropView.setCropMode(CropImageView.CropMode.SQUARE);
break;
case R.id.button3_4:
mCropView.setCropMode(CropImageView.CropMode.RATIO_3_4);
break;
case R.id.button4_3:
mCropView.setCropMode(CropImageView.CropMode.RATIO_4_3);
break;
case R.id.button9_16:
mCropView.setCropMode(CropImageView.CropMode.RATIO_9_16);
break;
case R.id.button16_9:
mCropView.setCropMode(CropImageView.CropMode.RATIO_16_9);
break;
case R.id.buttonCustom:
mCropView.setCustomRatio(7, 5);
break;
case R.id.buttonFree:
mCropView.setCropMode(CropImageView.CropMode.FREE);
break;
case R.id.buttonCircle:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE);
break;
case R.id.buttonShowCircleButCropAsSquare:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE_SQUARE);
break;
case R.id.buttonRotateLeft:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
break;
case R.id.buttonRotateRight:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
break;
case R.id.buttonPickImage:
MainFragmentPermissionsDispatcher.pickImageWithCheck(MainFragment.this);
break;
}
}
};
// Callbacks ///////////////////////////////////////////////////////////////////////////////////
private final LoadCallback mLoadCallback = new LoadCallback() {
#Override
public void onSuccess() {
dismissProgress();
Log.e("", "success");
}
#Override
public void onError() {
dismissProgress();
Log.e("", "error");
}
};
private final CropCallback mCropCallback = new CropCallback() {
#Override
public void onSuccess(Bitmap cropped) {
}
#Override
public void onError() {
}
};
private final SaveCallback mSaveCallback = new SaveCallback() {
#Override
public void onSuccess(Uri outputUri) {
dismissProgress();
//addPicture.startResultActivity(outputUri);
Intent i = getIntent();
i.putExtra("resultUri", outputUri.toString());
setResult(requestCode, i);
finish();
}
#Override
public void onError() {
dismissProgress();
}
};
}
ProjectUtils.java
public static boolean hasPermissionInManifest(Context context, int requestCode, String permissionName) {
if (Build.VERSION.SDK_INT >= 29) {
Log.w(TAG, "hasPermissions: API version >= 29, returning true by default");
// DANGER ZONE!!! Changing this will break the library.
return true;
}
if (context == null) {
throw new IllegalArgumentException("Can't check permissions for null context");
}
if (ContextCompat.checkSelfPermission(context,
permissionName)
!= PackageManager.PERMISSION_GRANTED) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions((Activity) context,
new String[]{permissionName},
requestCode);
} else {
return true;
}
return false;
}
AndroidManifest.java
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"
tools:ignore="ScopedStorage" />
<!--Permission for the Android 11 and above-->
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android:requestLegacyExternalStorage="true"
've also added requestLegacyExternalStorage="true" to the application tag in the manifest to get it to work for the APIs below Android 12. Stuck with this issue since yesterday, Please help.
Android version 12 camera and gallery not working solution

Android Compress image and upload it to server using below code

Hello greetings and salutation.
i have two different Android codes that almost work the same way. The first code Capture image from gallery and upload it with title to php server while the second code capture image from gallery and when resize button is pressed the image is compressed both size and memory is reduced but also maintaining the same picture Quality. Let me Upload / paste the two codes.
But my question is
how will i make the second code upload to server after it have compressed the image memory? or how will i make the first code before uploading to server let it compress it like code two ?
The first code
package net.simplifiedcoding.androiduploadimage;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
private EditText editText;
private ImageView imageView;
public static final String KEY_IMAGE = "image";
public static final String KEY_TEXT = "name";
public static final String UPLOAD_URL = "http://simplifiedcoding.16mb.com/PhotoUploadWithText/upload.php";
private int PICK_IMAGE_REQUEST = 1;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editText = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String text = editText.getText().toString().trim();
final String image = getStringImage(bitmap);
class UploadImage extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TEXT,text);
param.put(KEY_IMAGE,image);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
}
if(v == buttonUpload){
uploadImage();
}
}
}
The second Code
package id.zelory.compressor.sample;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;
import id.zelory.compressor.Compressor;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private ImageView actualImageView;
private ImageView compressedImageView;
private TextView actualSizeTextView;
private TextView compressedSizeTextView;
private File actualImage;
private File compressedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actualImageView = (ImageView) findViewById(R.id.actual_image);
compressedImageView = (ImageView) findViewById(R.id.compressed_image);
actualSizeTextView = (TextView) findViewById(R.id.actual_size);
compressedSizeTextView = (TextView) findViewById(R.id.compressed_size);
actualImageView.setBackgroundColor(getRandomColor());
clearImage();
}
public void chooseImage(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
public void compressImage(View view) {
if (actualImage == null) {
showError("Please choose an image!");
} else {
// Compress image in main thread
//compressedImage = new Compressor(this).compressToFile(actualImage);
//setCompressedImage();
// Compress image to bitmap in main thread
//compressedImageView.setImageBitmap(new Compressor(this).compressToBitmap(actualImage));
// Compress image using RxJava in background thread
new Compressor(this)
.compressToFileAsFlowable(actualImage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
#Override
public void accept(File file) {
compressedImage = file;
setCompressedImage();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) {
throwable.printStackTrace();
showError(throwable.getMessage());
}
});
}
}
public void customCompressImage(View view) {
if (actualImage == null) {
showError("Please choose an image!");
} else {
// Compress image in main thread using custom Compressor
try {
compressedImage = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(actualImage);
setCompressedImage();
} catch (IOException e) {
e.printStackTrace();
showError(e.getMessage());
}
// Compress image using RxJava in background thread with custom Compressor
/*new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFileAsFlowable(actualImage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
#Override
public void accept(File file) {
compressedImage = file;
setCompressedImage();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) {
throwable.printStackTrace();
showError(throwable.getMessage());
}
});*/
}
}
private void setCompressedImage() {
compressedImageView.setImageBitmap(BitmapFactory.decodeFile(compressedImage.getAbsolutePath()));
compressedSizeTextView.setText(String.format("Size : %s", getReadableFileSize(compressedImage.length())));
Toast.makeText(this, "Compressed image save in " + compressedImage.getPath(), Toast.LENGTH_LONG).show();
Log.d("Compressor", "Compressed image save in " + compressedImage.getPath());
}
private void clearImage() {
actualImageView.setBackgroundColor(getRandomColor());
compressedImageView.setImageDrawable(null);
compressedImageView.setBackgroundColor(getRandomColor());
compressedSizeTextView.setText("Size : -");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
if (data == null) {
showError("Failed to open picture!");
return;
}
try {
actualImage = FileUtil.from(this, data.getData());
actualImageView.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
actualSizeTextView.setText(String.format("Size : %s", getReadableFileSize(actualImage.length())));
clearImage();
} catch (IOException e) {
showError("Failed to read picture data!");
e.printStackTrace();
}
}
}
public void showError(String errorMessage) {
Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
}
private int getRandomColor() {
Random rand = new Random();
return Color.argb(100, rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}
public String getReadableFileSize(long size) {
if (size <= 0) {
return "0";
}
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
Thanks seriously need this to be solved
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
to this
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
this will work

why when i trying to upload image with size 1.5mb it's said error while uploading, but actually the image is successfully upload?

why when i trying to upload image with size 1.5 mb it's said error while uploading, but actually the image is successfully upload? and if i trying to upload with size 100 kb it's said Image Uploaded Successfully
WC_Activity.java
package com.emergency.e_place;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.HashMap;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAGS = "DEBUG";
String Latitude;
String Longitude;
private final String TAG = this.getClass().getName();
ImageView ivCamera, ivGallery, ivUpload, ivImage;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST = 13323;
final int GALLERY_REQUEST = 22131;
String selectedPhoto;
EditText etIpAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAGS, "onLocationChanged: " + Longitude);
etIpAddress = (EditText)findViewById(R.id.etIpAddress);
cameraPhoto = new CameraPhoto(getApplicationContext());
galleryPhoto = new GalleryPhoto(getApplicationContext());
ivImage = (ImageView)findViewById(R.id.ivImage);
ivCamera = (ImageView)findViewById(R.id.ivCamera);
ivGallery = (ImageView)findViewById(R.id.ivGallery);
ivUpload = (ImageView)findViewById(R.id.ivUpload);
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
cameraPhoto.addToGallery();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while taking photos", Toast.LENGTH_SHORT).show();
}
}
});
ivGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(galleryPhoto.openGalleryIntent(), GALLERY_REQUEST);
}
});
ivUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedPhoto == null || selectedPhoto.equals("")){
Toast.makeText(getApplicationContext(), "No Image Selected.", Toast.LENGTH_SHORT).show();
return;
}
try {
Bitmap bitmap = ImageLoader.init().from(selectedPhoto).requestSize(1024, 1024).getBitmap();
String encodedImage = ImageBase64.encode(bitmap);
Log.d(TAG, encodedImage);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("image", encodedImage);
PostResponseAsyncTask task = new PostResponseAsyncTask(WC_Activity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if(s.contains("uploaded_success")){
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully.",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error while uploading.",
Toast.LENGTH_SHORT).show();
}
}
});
String ip = etIpAddress.getText().toString();
task.execute("http://" +ip + "/AndroidUpload/upload.php");
task.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error.",
Toast.LENGTH_SHORT).show();
}
});
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while encoding photos", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST){
String photoPath = cameraPhoto.getPhotoPath();
selectedPhoto = photoPath;
Bitmap bitmap = null;
try {
bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(getRotatedBitmap(bitmap, 90));
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
}
}
else if(requestCode == GALLERY_REQUEST){
Uri uri = data.getData();
galleryPhoto.setPhotoUri(uri);
String photoPath = galleryPhoto.getPath();
selectedPhoto = photoPath;
try {
Bitmap bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
}
}
}
}
private Bitmap getRotatedBitmap(Bitmap source, float angle){
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap bitmap1 = Bitmap.createBitmap(source,
0, 0, source.getWidth(), source.getHeight(), matrix, true);
return bitmap1;
}
}

How to process retrieved scan result such as loading URLs?

I devloped an android app for barcode scanner,now in that i want to carry out further processing on the retrieved scan results, such as loading URLs or looking the data up in a third party data source.So how can i do this.I am using android studio for devloping app.
Here is my code for MAinActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanBtn = (Button) findViewById(R.id.scan_button);
formatTxt = (TextView) findViewById(R.id.scan_format);
contentTxt = (TextView) findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
And i am using zxing library.
Here is my edited code:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("url");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
It is the correct way or not?
Start your scanner Activity with startActivityForResult and override onActivityResult for processing the retrieved data.
Take a look at the examples here.
You have to start new Activity to open your URL.
private void openUrl(String url) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
Call this method inside your onActivityResult method. Probably scanContent variable is your URL.

How to Get Image URI from Image selected From gallery. Android 5.0.2?

I aam new to android. Kindly provide me some help. I need the Image URI, before this i tried data.getData(); and pass it to getContentResolver().query() but data.getData(); always returned null
Error is at thes lines:
Uri SelectedImageURI = getImageUri(getApplicationContext(), SelectedImage);
return Uri.parse(path);
My android version is 5.0.2
05-10 01:55:10.712 24424-24424/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.donateblood.blooddonation, PID: 24424
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=com.htc.HTCAlbum.action.ITEM_PICKER_FROM_COLLECTIONS (has extras) }} to activity {com.donateblood.blooddonation/com.donateblood.blooddonation.UploadImage}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3881)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:473)
at android.net.Uri$StringUri.<init>(Uri.java:463)
at android.net.Uri.parse(Uri.java:435)
at com.donateblood.blooddonation.UploadImage.getImageUri(UploadImage.java:156)
at com.donateblood.blooddonation.UploadImage.onActivityResult(UploadImage.java:102)
at android.app.Activity.dispatchActivityResult(Activity.java:6160)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3877)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
package com.donateblood.blooddonation;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by YouCaf Iqbal on 4/26/2016.
*/
public class UploadImage extends AppCompatActivity {
public static final int RESULT_LOAD = 1;
#InjectView(R.id.imageView) ImageView ImageUpload;
#InjectView(R.id.upload) Button Btn_Upload;
#InjectView(R.id.proceed) Button Btn_Proceed;
public String bloodgroup,name,password,number,email,picturePath,encodedPhotoString;
Database dbobj = new Database();
GPSTracker gps; private DB db;
public double latitude=0;
public double longitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadimage);
ButterKnife.inject(this);
getCurrentLatLong();
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent upload = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//Adding Croping
upload.putExtra("crop","true");
upload.putExtra("aspectX",1);
upload.putExtra("aspectY",1);
upload.putExtra("outputX",300);
upload.putExtra("outputY",300);
upload.putExtra("return-data",true);
startActivityForResult(upload,RESULT_LOAD);
} catch (ActivityNotFoundException E) {
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(UploadImage.this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Prcoess();
}
});
}
// When image is selected from Gallery
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_LOAD && resultCode==RESULT_OK && data!=null){
Bundle extras = data.getExtras();
//Uri SelectedImageURI = (Uri)extras.get(Intent.EXTRA_STREAM);
Bitmap SelectedImage = extras.getParcelable("data");
//Make Image rounded
//Bitmap RoundedImage = getRoundedShape(SelectedImage);
// Uri SelectedImageURI = data.getData();
Uri SelectedImageURI = getImageUri(getApplicationContext(), SelectedImage);
picturePath = getRealPathFromURI(SelectedImageURI);
ImageUpload.setImageBitmap(SelectedImage);
// retrieve image path
String[] projection = {MediaStore.Images.Media.DATA};
try {
// Cursor cursor = getContentResolver().query(SelectedImageURI, projection, null, null, null);
//cursor.moveToFirst();
// int columnIndex = cursor.getColumnIndex(projection[0]);
// picturePath = cursor.getString(columnIndex);
// cursor.close();
////////////////////////////////////////////////////
String fileNameSegments[] = picturePath.split("/");
String fileName = fileNameSegments[fileNameSegments.length - 1];
try {
File f = new File(picturePath);
Bitmap myImg = decodeFile(f,720);
//myImg = getResizedBitmap(myImg,100); // Compress it
// Bitmap myImg = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
// myImg = getResizedBitmap(myImg, 720);
myImg.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
// ImageUpload.setImageBitmap(myImg);
}catch (Exception e){
Toast.makeText(UploadImage.this,"Unable to Set Image Try Again",Toast.LENGTH_SHORT).show();
}
//Log.d("Picture Path", picturePath);
// Toast.makeText(getBaseContext(), ""+picturePath+"", Toast.LENGTH_LONG).show();
}
catch(Exception e) {
// Log.e("Path Error", e.toString());
Toast.makeText(getBaseContext(), "Error finding path", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
//
}
}
public void Prcoess(){
dbAsync signupThread = new dbAsync();
signupThread.execute();
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public class dbAsync extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
dbobj.insertUser(name,email,password,number,bloodgroup,latitude,longitude,encodedPhotoString);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), ""+encodedPhotoString+"", Toast.LENGTH_LONG).show();
onSignupSuccess();
}
}
public void onSignupSuccess() {
// btn_signup.setEnabled(true);
//setResult(RESULT_OK, null);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
public void GetUserDetails(){
//mySpinner=(Spinner) findViewById(R.id.spinner);
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
}
public void getCurrentLatLong(){
gps = new GPSTracker(UploadImage.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
}
public Bitmap decodeFile(File f,int IMAGE_MAX_SIZE){
Bitmap b = null;
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE /
(double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
return b;
}
}
ACTION_PICK returns its result in the Uri in the Intent delivered to onActivityResult(). You call getData() to get this Uri. That's it. Hence, pretty much everything in your if(requestCode==RESULT_LOAD && resultCode==RESULT_OK && data!=null) block is not only wrong, but it is useless.
Beyond that, get rid of all the undocumented extras that you are placing on that ACTION_PICK Intent. Use an image cropping library.

Categories