I have 3 menu buttons (add_image,save_meme and share_meme) on my action bar, which are declared in Mainactivity.java. The buttons are responsible for calling the corresponding methods in another fragment. The connection is established with LocalBroadcastManager.
public class MainActivity extends AppCompatActivity{
Intent saveIntent, shareIntent, addImageIntent;
LocalBroadcastManager localBroadcastManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
addImageIntent = new Intent("ADD_ACTION");
saveIntent = new Intent("SAVE_ACTION");
shareIntent = new Intent("SHARE_ACTION");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
default:
return super.onOptionsItemSelected(item);
}
}
}
As mentioned above, the corresponding methods are in the TopImageFragment.java class. The add_image button calls the method that allows the user to upload an image to the ImageView from the device:
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
The save_meme button calls the method that saves the bitmap to the device:
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
The share_meme button calls the method that allows the user to share the meme on a variety of social media apps and email clients:
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
But what's happening now is that whenever I select whichever of the 3 menu buttons, all 3 methods get called. This is my full fragment:
public class TopImageFragment extends Fragment {
ImageView imageView;
TextView topTextView, bottomTextView;
RelativeLayout topImageRelativeLayout;
public static final int PICK_IMAGE = 1;
Uri imageUri;
int counter = 0;
String timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.CANADA).format(new Date());
float textSize, x, imageViewArea, canvasArea;
double val;
MemeViewModel memeViewModel;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_image, container, false);
imageView = view.findViewById(R.id.meme_image_view);
topTextView = view.findViewById(R.id.top_text_view);
bottomTextView = view.findViewById(R.id.bottom_text_view);
topImageRelativeLayout = view.findViewById(R.id.top_image_relative_layout);
if (savedInstanceState != null) {
imageUri = savedInstanceState.getParcelable("imageUri");
imageView.setImageURI(imageUri);
}
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("imageUri", imageUri);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
memeViewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(MemeViewModel.class);
memeViewModel.getTopText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
topTextView.setText(charSequence);
}
});
memeViewModel.getBottomText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
bottomTextView.setText(charSequence);
}
});
}
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
public Bitmap getBitmap(ImageView img) {
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
return bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap screenshotMeme() {
Bitmap image = Bitmap.createBitmap(topImageRelativeLayout.getWidth(), topImageRelativeLayout.getHeight(), Bitmap.Config.RGB_565);
topImageRelativeLayout.draw(new Canvas(image));
return image.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap drawMeme(Bitmap mutableBitmap) {
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
topText = topText.toUpperCase();
bottomText = bottomText.toUpperCase();
Canvas canvas = new Canvas(mutableBitmap);
TextPaint topFillPaint = new TextPaint();
TextPaint bottomFillPaint = new TextPaint();
TextPaint topStrokePaint = new TextPaint();
TextPaint bottomStrokePaint = new TextPaint();
Typeface typeface = getResources().getFont(R.font.impact);
textSize = topTextView.getTextSize();
imageViewArea = (imageView.getWidth()) * (imageView.getHeight());
canvasArea = (canvas.getWidth()) * (canvas.getHeight());
val = textSize * sqrt(canvasArea / imageViewArea);
x = (float) val;
topFillPaint.setColor(Color.WHITE);
topFillPaint.setTextSize(x);
topFillPaint.setTypeface(typeface);
topFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
topStrokePaint.setStyle(Paint.Style.STROKE);
topStrokePaint.setStrokeWidth(4);
topStrokePaint.setTextSize(x);
topStrokePaint.setColor(Color.BLACK);
topStrokePaint.setTypeface(typeface);
bottomFillPaint.setColor(Color.WHITE);
bottomFillPaint.setTextSize(x);
bottomFillPaint.setTypeface(typeface);
bottomFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
bottomStrokePaint.setStyle(Paint.Style.STROKE);
bottomStrokePaint.setStrokeWidth(4);
bottomStrokePaint.setColor(Color.BLACK);
bottomStrokePaint.setTextSize(x);
bottomStrokePaint.setTypeface(typeface);
StaticLayout topFillLayout = new StaticLayout(topText, topFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout topStrokeLayout = new StaticLayout(topText, topStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomFillLayout = new StaticLayout(bottomText, bottomFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomStrokeLayout = new StaticLayout(bottomText, bottomStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
topFillLayout.draw(canvas);
topStrokeLayout.draw(canvas);
canvas.translate(0, canvas.getHeight() - bottomFillLayout.getHeight());
bottomFillLayout.draw(canvas);
bottomStrokeLayout.draw(canvas);
return mutableBitmap;
}
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = Objects.requireNonNull(data).getData();
imageView.setImageURI(imageUri);
memeViewModel.setSharedId(imageUri.getLastPathSegment());
}
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(addListener, new IntentFilter("ADD_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(saveListener, new IntentFilter("SAVE_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(shareListener, new IntentFilter("SHARE_ACTION"));
}
private BroadcastReceiver addListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
selectedImage();
}
};
private BroadcastReceiver saveListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
saveMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
saveMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
private BroadcastReceiver shareListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
shareMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
shareMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(addListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(saveListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(shareListener);
}
}
Problem: Because in switch-case block, you do not return or put a break statement, then whenever a menu item is clicked, it will executes all statements in the switch-case.
Solution: Put a return true on each case to indicate you want consume the event when a menu item is clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
return true;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
return true;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
or using a break statement on each case, then returning true at the end of method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
break;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
break;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
Related
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
Button facedetect;
GraphicOverlay graphicOverlay;
CameraView cameraView;
AlertDialog alertDialog;
Bitmap captureImage, saveImage;
Bitmap b1,b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facedetect = findViewById(R.id.detect_face_btn);
graphicOverlay = findViewById(R.id.graphic_overlay);
cameraView = findViewById(R.id.camera_view);
facedetect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.start();
cameraView.captureImage();
graphicOverlay.clear();
}
});
cameraView.addCameraKitListener(new CameraKitEventListenerAdapter() {
#Override
public void onEvent(CameraKitEvent event) {
super.onEvent(event);
}
#Override
public void onError(CameraKitError error) {
super.onError(error);
}
#Override
public void onImage(CameraKitImage image) {
super.onImage(image);
alertDialog.show();
b1 = image.getBitmap();
b1 = Bitmap.createScaledBitmap(b1, cameraView.getWidth(), cameraView.getHeight(), false);
cameraView.stop();
getImageFromLocal();`enter code here`
// if ( compareImages(b1,b2)==true) {
// Toast.makeText(getApplicationContext(),"True",Toast.LENGTH_SHORT).show();
// }
// Toast.makeText(getApplicationContext(),"False",Toast.LENGTH_SHORT).show();
processFaceDetaection(b1);
}
#Override
public void onVideo(CameraKitVideo video) {
super.onVideo(video);
}
});
}
private void processFaceDetaection(Bitmap bitmap) {
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionFaceDetectorOptions firebaseVisionFaceDetectorOptions = new FirebaseVisionFaceDetectorOptions.Builder().build();
// High-accuracy landmark detection and face classification
FirebaseVisionFaceDetectorOptions landmarkdetectionfacedetection =
new FirebaseVisionFaceDetectorOptions.Builder()
.setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
.setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
.setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
.build();
// Real-time contour detection of multiple faces
FirebaseVisionFaceDetectorOptions contourdetectionfacedetection =
new FirebaseVisionFaceDetectorOptions.Builder()
.setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
.build();
FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(firebaseVisionFaceDetectorOptions);
// FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(contourdetectionfacedetection);
firebaseVisionFaceDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() {
#Override
public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) {
getFaceResult(firebaseVisionFaces);
compareFaceFromLocal();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
alertDialog.dismiss();
Toast.makeText(MainActivity.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void compareFaceFromLocal() {
if (compareImages(b1, b2) == true) {
Toast.makeText(getApplicationContext(), "True", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "False", Toast.LENGTH_SHORT).show();
}
private void getFaceResult(List<FirebaseVisionFace> firebaseVisionFaces) {
int counter = 0;
for (FirebaseVisionFace face : firebaseVisionFaces) {
Rect rect = face.getBoundingBox();
ReactOverlay reactOverlay = new ReactOverlay(graphicOverlay, rect);
graphicOverlay.add(reactOverlay);
counter = counter + 1;
}
Toast.makeText(MainActivity.this, "No. of faces detected : " + counter, Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
/**
* Get the angle by which an image must be rotated given the device's current
* orientation.
*/
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int getRotationCompensation(String cameraId, Activity activity, Context context)
throws CameraAccessException {
// Get the device's current rotation relative to its "native" orientation.
// Then, from the ORIENTATIONS table, look up the angle the image must be
// rotated to compensate for the device's rotation.
int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int rotationCompensation = ORIENTATIONS.get(deviceRotation);
// On most devices, the sensor orientation is 90 degrees, but for some
// devices it is 270 degrees. For devices with a sensor orientation of
// 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
int sensorOrientation = cameraManager
.getCameraCharacteristics(cameraId)
.get(CameraCharacteristics.SENSOR_ORIENTATION);
rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360;
// Return the corresponding FirebaseVisionImageMetadata rotation value.
int result;
switch (rotationCompensation) {
case 0:
result = FirebaseVisionImageMetadata.ROTATION_0;
break;
case 90:
result = FirebaseVisionImageMetadata.ROTATION_90;
break;
case 180:
result = FirebaseVisionImageMetadata.ROTATION_180;
break;
case 270:
result = FirebaseVisionImageMetadata.ROTATION_270;
break;
default:
result = FirebaseVisionImageMetadata.ROTATION_0;
Log.e(TAG, "Bad rotation value: " + rotationCompensation);
}
return result;
}
#Override
protected void onPause() {
super.onPause();
cameraView.stop();
}
#Override
protected void onResume() {
super.onResume();
cameraView.start();
}
private void getImageFromLocal() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
/*Compare two images.
* #param bitmap1
* #param bitmap2
* #return true iff both images have the same dimensions and pixel values.*/
public static boolean compareImages(Bitmap bitmap1, Bitmap bitmap2) {
if (bitmap1.getWidth() != bitmap2.getWidth() ||
bitmap1.getHeight() != bitmap2.getHeight()) {
return false;
}
for (int y = 0; y < bitmap1.getHeight(); y++) {
for (int x = 0; x < bitmap1.getWidth(); x++) {
if (bitmap1.getPixel(x, y) != bitmap2.getPixel(x, y)) {
return false;
}
}
}
return true;
}
public static Uri imageURI;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 0) {
if (data != null) {
try {
b2 = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
System.exit(0);
Log.e("result", "BAD");
}
}
}
i try to open the result on ResultActivity class but it cant be why?
**i try to scan qr code from image from the gallery **
any solution
here is the code
case R.id.scn_img:
Intent pickIntent = new Intent(Intent.ACTION_PICK);
pickIntent.setDataAndType( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(pickIntent, 111);
break;
this is onActivityResult code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//the case is because you might be handling multiple request codes here
case 111:
if(data == null || data.getData()==null) {
Log.e("TAG", "The uri is null, probably the user cancelled the image selection process using the back button.");
return;
}
Uri uri = data.getData();
try
{
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap == null)
{
Log.e("TAG", "uri is not a bitmap," + uri.toString());
return;
}
int width = bitmap.getWidth(), height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
bitmap = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
try
{
Result result = reader.decode(bBitmap);
//here i want to do the code but this not working
// here is the problem
//********************************
ResultActivity.startResultActivity(BaseActivity.this, result);
//********************************
// toast message it is work good
Toast.makeText(this, "The content of the QR image is: "
+ result.getText(), Toast.LENGTH_SHORT).show();
}
catch (NotFoundException e)
{
Log.e("TAG", "decode exception", e);
}
}
catch (FileNotFoundException e)
{
Log.e("TAG", "can not open file" + uri.toString(), e);
}
break;
}
}
here is my ResultActivity class code
public class ResultActivity extends AppCompatActivity {
private static final String HISTORY_DATA = "ResultActivity.HISTORY_DATA";
private static final int REQUEST_WRITE_PERMISSION = 200;
private static BarcodeResult barcodeResult = null;
private static HistoryItem historyItem = null;
private ResultViewModel viewModel;
private ResultFragment currentResultFragment;
public static void startResultActivity(#NonNull Context context, #NonNull BarcodeResult barcodeResult) {
ResultActivity.barcodeResult = barcodeResult;
ResultActivity.historyItem = null;
Intent resultIntent = new Intent(context, ResultActivity.class);
context.startActivity(resultIntent);
}
public static void startResultActivity(#NonNull Context context, #NonNull HistoryItem historyItem) {
ResultActivity.barcodeResult = null;
ResultActivity.historyItem = historyItem;
Intent resultIntent = new Intent(context, ResultActivity.class);
resultIntent.putExtra(HISTORY_DATA, true);
context.startActivity(resultIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
viewModel = ViewModelProviders.of(this).get(ResultViewModel.class);
initStateIfNecessary(savedInstanceState);
ActionBar ab = getSupportActionBar();
if(ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
if(isFinishing()) {
return;
}
loadFragment(viewModel.mParsedResult);
displayGeneralData();
}
private void initStateIfNecessary(Bundle savedInstanceState) {
boolean hasHistoryItem = getIntent().getBooleanExtra(HISTORY_DATA, false);
if(savedInstanceState == null) {
if(hasHistoryItem && historyItem != null) {
viewModel.initFromHistoryItem(historyItem);
} else if(barcodeResult != null) {
viewModel.initFromScan(barcodeResult);
} else {
// no data to display -> exit
Toast.makeText(this, R.string.activity_result_toast_error_cant_load, Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.share,menu);
getMenuInflater().inflate(R.menu.copy,menu);
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(menu != null) {
MenuItem saveMi = menu.findItem(R.id.save);
if(saveMi != null) {
saveMi.setVisible(!viewModel.mSavedToHistory);
}
}
return true;
}
public void onClick(View view) {
if (view.getId() == R.id.btnProceed) {
if(currentResultFragment != null) {
currentResultFragment.onProceedPressed(this);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.share:
Intent sharingIntent= new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_TEXT, viewModel.mParsedResult.getDisplayResult());
startActivity(Intent.createChooser(sharingIntent,getString(R.string.share_via)));
return true;
case R.id.save:
viewModel.saveHistoryItem(viewModel.currentHistoryItem);
invalidateOptionsMenu();
Toast.makeText(this, R.string.activity_result_toast_saved, Toast.LENGTH_SHORT).show();
return true;
case R.id.copy:
ClipboardManager clipboardManager =(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Text", viewModel.mParsedResult.getDisplayResult());
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(getApplicationContext(), R.string.content_copied, Toast.LENGTH_SHORT).show();
return true;
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void loadFragment(#NonNull ParsedResult parsedResult) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ResultFragment resultFragment;
switch (parsedResult.getType()) {
case ADDRESSBOOK:
resultFragment = new ContactResultFragment();
break;
case EMAIL_ADDRESS:
resultFragment = new EmailResultFragment();
break;
case PRODUCT:
resultFragment = new ProductResultFragment();
break;
case URI:
resultFragment = new URLResultFragment();
break;
case GEO:
resultFragment = new GeoResultFragment();
break;
case TEL:
resultFragment = new TelResultFragment();
break;
case SMS:
resultFragment = new SMSResultFragment();
break;
case WIFI:
resultFragment = new WifiResultFragment();
break;
case TEXT:
default:
resultFragment = new TextResultFragment();
break;
}
currentResultFragment = resultFragment;
resultFragment.putQRCode(parsedResult);
ft.replace(R.id.activity_result_frame_layout, resultFragment);
ft.commit();
}
}
error message it is
cannot resolve method startResultActivity com.google.zxing.Result
I want to answer with an example
Thank you
There is no static method by the name of startResultActivity in ResultActivity that takes Context and Result as arguments
BarcodeResult is not the same as Result
You need to create a method with the signature public static void startResultActivity(#NonNull Context context, #NonNull Result result) {
I'm trying to add a set wallpaper button to my app that will set the wallpaper when I pull my image from firebase database. This is what I have so far. I've set the button up to automatically show up on every wallpaper snap shot. I've set a wallpaper in the past when the picture was stored on the phone but cant seem to figure out how to set it when pulling an image from firebase.
public class WallpapersAdapter extends RecyclerView.Adapter<WallpapersAdapter.WallpaperViewHolder> {
private Context mCtx;
private List<Wallpaper> wallpaperList;
public WallpapersAdapter(Context mCtx, List<Wallpaper> wallpaperList) {
this.mCtx = mCtx;
this.wallpaperList = wallpaperList;
}
#NonNull
#Override
public WallpaperViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_wallpapers, parent, false);
return new WallpaperViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WallpaperViewHolder holder, int position) {
Wallpaper w = wallpaperList.get(position);
holder.textView.setText(w.title);
Glide.with(mCtx)
.load(w.url)
.into(holder.imageView);
if(w.isFavorite){
holder.checkBoxFav.setChecked(true);
}
}
#Override
public int getItemCount() {
return wallpaperList.size();
}
class WallpaperViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, CompoundButton.OnCheckedChangeListener{
TextView textView;
ImageView imageView;
CheckBox checkBoxFav;
ImageButton buttonShare, buttonDownload;
Button setWallpaper;
public WallpaperViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view_title);
imageView = itemView.findViewById(R.id.image_view);
checkBoxFav = itemView.findViewById(R.id.checkbox_favorite);
buttonShare = itemView.findViewById(R.id.button_share);
buttonDownload = itemView.findViewById(R.id.button_download);
setWallpaper = itemView.findViewById(R.id.set_wallpaper);
setWallpaper.setOnClickListener(this);
checkBoxFav.setOnCheckedChangeListener(this);
/*buttonShare.setOnClickListener(this);*/
/*buttonDownload.setOnClickListener(this);*/
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_share:
shareWallpaper(wallpaperList.get(getAdapterPosition()));
break;
case R.id.button_download:
downloadWallpaper(wallpaperList.get(getAdapterPosition()));
break;
case R.id.set_wallpaper:
setWallpaper(wallpaperList.get(getAdapterPosition()));
break;
}
}
private void shareWallpaper(Wallpaper w){
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
Glide.with(mCtx)
.asBitmap()
.load(w.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(resource));
mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
}
});
}
private Uri getLocalBitmapUri(Bitmap bmp){
Uri bmpUri = null;
try {
File file = new File(mCtx.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"the_wallpaper_app_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
private void downloadWallpaper(final Wallpaper wallpaper){
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
Glide.with(mCtx)
.asBitmap()
.load(wallpaper.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = saveWallpaperAndGetUri(resource, wallpaper.id);
if(uri != null){
intent.setDataAndType(uri, "image/*");
mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
}
}
});
}
private Uri saveWallpaperAndGetUri(Bitmap bitmap, String id){
if(ContextCompat.checkSelfPermission(mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", mCtx.getPackageName(), null);
intent.setData(uri);
mCtx.startActivity(intent);
}else{
ActivityCompat.requestPermissions((Activity) mCtx, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100 );
}
return null;
}
File folder = new File(Environment.getExternalStorageDirectory().toString() + "/the_wallpaper_app" );
folder.mkdirs();
File file = new File(folder, id + ".jpg" );
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
return Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(FirebaseAuth.getInstance().getCurrentUser() == null){
Toast.makeText(mCtx, "Please login first", Toast.LENGTH_LONG).show();
compoundButton.setChecked(false);
return;
}
int position = getAdapterPosition();
Wallpaper w = wallpaperList.get(position);
DatabaseReference dbFavs = FirebaseDatabase.getInstance().getReference("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child("favorites")
.child(w.category);
if(b){
dbFavs.child(w.id).setValue(w);
}else{
dbFavs.child(w.id).setValue(null);
}
}
}
private void setWallpaper(Wallpaper set) {
};
}
}
You can not directly set the image from database as wallpaper on your android device, for that first you have to download the image to your device and then you can set it as the background wallpaper.
You can use createTempFile(String prefix, String suffix) which creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
Read more about this here.
If you'd rather want to store the file in your app directory, you can use a code like this:
File dir = new File(Environment.getExternalStorageDirectory(), "dir_name");
// Create dir if not exists
if(!dir.exists()) dir.mkdirs();
File mFile = new File(dir, "file_name");
Also to get bitmap from the file and use it to set as wallpaper, you may use a code similar to this:
Bitmap bitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath());
//after converting it to bitmapDrawable you can set it as background using this
getWindow().setBackgroundDrawable
You may also use WallpaperManager for this like:
WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
Another class calls the GridView class below that is populated with images from a parse server, if a user clicks on a grid item, it starts the same GridView class with different bundled strings so it can pull from a different parse database class. Now at this point, when a user clicks an GridView item (from the 2nd gridview that was set up), I want it to start a different activity class.
I tried doing an if/else if statement in the onItemClick that takes the "PARSE_CLASS" bundled string but I can't seem to get that to work. I'm relatively new to android programming so I don't know the best way to do this.
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
gridView = (GridView) findViewById(R.id.gridView);
itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(itemGridAdapter);
new RemoteDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
}
});
}//end onCreate method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
gridView = (GridView) findViewById(R.id.gridView);
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
This is what I tried. When I tried this, the second GridView wouldn't load. So I'm guessing I'm unable to retrieve the "PARSE_CLASS" bundled string the second time around.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
if (parseClass == "Categories") {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
} else if(parseClass == "Items"){
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
ANSWER
Someone on reddit's learn programming was nice enough to point out that I had an issue with string comparisons. had to use
if(parseClass.equals("Categories")){}
instead of
if(parseClass == "Categories"){}
I feel like an idiot, hopefully someone else benefits from this long disastrous effort.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent t = getIntent();
Bundle itemExtras = t.getExtras();
String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = itemExtras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Log.i("AppInfo", parseClass);
if (parseClass.equals("Categories")) {
Log.i("AppInfo", parseClass);
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
String categoryName = categoryNameArrayList.get(position);
itemExtras.putString("SUPPLIER", activeSupplier);
itemExtras.putString("PARSE_CLASS", "Items");
itemExtras.putString("CATEGORY_NAME", categoryName);
t.putExtras(itemExtras);
startActivity(t);
} else if (parseClass.equals("Items")) {
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
String activeSupplier;
String parseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
Intent i = getIntent();
if (null != i) {
Bundle itemExtras = i.getExtras();
activeSupplier = itemExtras.getString("SUPPLIER");
parseClass = itemExtras.getString("PARSE_CLASS");
}
RemoteDataTask remoteDataAsync = new RemoteDataTask();
remoteDataAsync.execute();
if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", parseClass);
t.putExtras(extras);
startActivity(t);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}//end onCreate method
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
Currently I am using this code in my application to allow users to capture photos.But how do i change the code so that after the users capture the photo, it will be renamed to name such as "xxxx01.jpg"?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
_image = (ImageView) findViewById(R.id.image);
_field = (TextView) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = Environment.getExternalStorageDirectory()
+ "/images/make_machine_example.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
#Override
public void onClick(View view) {
Log.i("MakeMachine", "ButtonClickHandler.onClick()");
startCameraActivity();
}
}
protected void startCameraActivity() {
Log.i("MakeMachine", "startCameraActivity()");
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("MakeMachine", "resultCode: " + resultCode);
switch (resultCode) {
case 0:
Log.i("MakeMachine", "User cancelled");
break;
case -1:
onPhotoTaken();
break;
}
}
protected void onPhotoTaken() {
Log.i("MakeMachine", "onPhotoTaken");
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
_image.setImageBitmap(bitmap);
_field.setVisibility(View.GONE);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i("MakeMachine", "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(PhotoCaptureExample.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(PhotoCaptureExample.PHOTO_TAKEN, _taken);
}
}
Try this.
//camera stuff
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//folder stuff
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
filePath = "/MyImages/QR_" + timeStamp + ".png" ;
File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Taken From Here.