我正在构建一个 Android 应用程序,其中包括在不同的屏幕(活动)中收集不同类别的客户数据。用户输入的数据(所有输入字段)存储在全局变量(静态)中。在最后一个屏幕或活动中,我试图在保存所有详细信息之前捕获与客户相关的多个图像。捕获图像时,应用程序崩溃并且全局静态变量变为空,因此我丢失了在先前其他屏幕中输入的所有数据,从而使我无法保存数据。该代码在其他设备上运行得非常好,而且这个问题只发生在少数设备中,其中之一是 One Plus 6T。这个问题的原因是什么,我该如何解决?
这是我捕获图像并将其添加到全局变量的活动:
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;
}
}
}