I am building an Android app that includes collecting customer data in different categories ,in different screeens(Activities). The data entered by the user(all input fields) are stored in Global variables(which are static). In the last screen or activity I am trying to capture multiple images related to customer before saving all the details. when the image is captured, the app crashes and the Global static variables become empty, due to which I am losing all the data entered in the previous other screens thereby, making me unable to save the data. The code works absolutely fine with other devices and this issue is occuring only in few devices and one of those is One Plus 6T. What is the cause for this issue and How do I solve this?
This is my Activity for Capturing Image and adding it to Global variables :
public class AddPicturesActivity extends AppCompatActivity {
public static final int CAMERA_PERM_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
Button Choosefromgallery, TakePicture, Save;
static final int REQUEST_TAKE_PHOTO = 1;
private static String imageStoragePath;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
//`HashMap<String,String> imagedata = new HashMap<String,String>();
public static List<String> imagedata = new ArrayList<>();
List<String> imagefiles = new ArrayList<>();
List<Bitmap> bitmaps = new ArrayList<>();
Context thisContext;
List<HashMap<String, String>> imagedatalist = new ArrayList<HashMap<String, String>>();
List<String> imagePaths;
public static GridView gridview;
ImageView imageg;
TextView text;
int ACTION_REQUEST_CAMERA = 200;
int ACTION_REQUEST_CAMERA1 = 100;
public static final int BITMAP_SAMPLE_SIZE = 8;
public static final String KEY_IMAGE_STORAGE_PATH = "image_path";
public static GridViewAdapter gridAdapter;
String currentPhotoPath;
public static final int GALLERY_REQUEST_CODE = 105;
String imagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_pictures);
thisContext = AddPicturesActivity.this;
Choosefromgallery = findViewById(R.id.Choosefromgallery);
TakePicture = findViewById(R.id.TakePicture);
Save = findViewById(R.id.SAVE);
imageg = findViewById(R.id.imageg);
gridview = (GridView) findViewById(R.id.gridview);
gridAdapter = new GridViewAdapter(this, R.layout.gridviewlayout, imagedata);
gridview.setAdapter(gridAdapter);
gridAdapter.notifyDataSetChanged();
Choosefromgallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, GALLERY_REQUEST_CODE);
}
});
TakePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
askCameraPermissions();
}
});
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
// Send intent to SingleViewActivity
imagePath = ((TextView) v.findViewById(R.id.text)).getText().toString();
Intent intent = new Intent(AddPicturesActivity.this, AdditionalImageDetailView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("imagePath", imagePath);
intent.putExtra("position", position);
startActivity(intent);
}
});
gridview.setAdapter(gridAdapter);
Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goprev();
}
});
}
private void askCameraPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERM_CODE);
} else {
dispatchTakePictureIntent();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == CAMERA_PERM_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "Camera Permission is Required to Use camera.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putString(KEY_IMAGE_STORAGE_PATH, imageStoragePath);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"app.evenforce.com.getafix.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
@Override
protected void onResume() {
super.onResume();
gridAdapter.notifyDataSetChanged();
if (gridAdapter.getCount() >= 4) {
// if (imagedata.size() >= 4) {
TakePicture.setVisibility(View.GONE);
//Save.setVisibility(View.VISIBLE);
} else {
TakePicture.setVisibility(View.VISIBLE);
//Save.setVisibility(View.GONE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
try {
File f = new File(currentPhotoPath);
imagefiles.add(f.getPath());
imagedata.add(Uri.fromFile(f).toString());
}else {
gridAdapter = new GridViewAdapter(this, R.layout.gridviewlayout, imagedata);
gridview.setAdapter(gridAdapter);
//selectedImage.setImageURI(Uri.fromFile(f));
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(thisContext, "Something went wrong, Please try again", Toast.LENGTH_SHORT);
}
// }
}
}
}
private String getFileExt(Uri contentUri) {
ContentResolver c = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(c.getType(contentUri));
}
private File createImageFile() throws IOException {
// Create an image file name
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(FILEPATH, "/");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(thisContext, "Something went wrong, Please try again", Toast.LENGTH_SHORT);
return null;
}
}
private List<String> getImages() {
// new File(imagePath ).mkdirs();
File fileTarget = new File(imageStoragePath);
File[] files = fileTarget.listFiles();
imagedata.clear();
if (files != null) {
for (File file : files) {
String name = file.getName();
if (file.getName().contains(Global.CustomerCode)) {
imagedata.add(file.getAbsolutePath());
}
}
}
return imagedata;
}
void goprev() {
try {
if (StringToBitMap(imagefiles.get(0)) != null) {
Lib.Debug("1 is Not same");
Global.AdditionalImage1 = StringToBitMap(imagefiles.get(0));
text.setText(imagefiles.get(0));
} else {
Global.AdditionalImage1 = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (StringToBitMap(imagefiles.get(1)) != null) {
Lib.Debug("2 is Not same");
Global.AdditionalImage2 = StringToBitMap(imagefiles.get(1));
text.setText(imagefiles.get(1));
} else {
Global.AdditionalImage2 = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (StringToBitMap(imagefiles.get(2)) != null) {
Lib.Debug("3 is Not same");
Global.AdditionalImage3 = StringToBitMap(imagefiles.get(2));
text.setText(imagefiles.get(2));
} else {
Global.AdditionalImage3 = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (StringToBitMap(imagefiles.get(3)) != null) {
Lib.Debug("4 is Not same");
Global.AdditionalImage4 = StringToBitMap(imagefiles.get(3));
text.setText(imagefiles.get(3));
} else {
Global.AdditionalImage4 = null;
}
} catch (Exception e) {
e.printStackTrace();
}
imagedata.clear();
Lib.Debug("Assigining to global during PREV button");
finish();
}
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
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 Bitmap StringToBitMap(String encodedString) {
try {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(encodedString, bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
//imageView.setImageBitmap(bitmap);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}