Draw sketch over a captured image in imageView on class extends AppCompactActivity - java

Hi am trying to draw a sketch using Canvas over an ImageView in my activity where image is filled by taking picture on activity. I have specified Ontouchlistner to sketch over the image on touch position but am not getting my touch listener accurate. ie when i touch over the display the sketch is created over another place not at my touched position.
public class MainActivity extends AppCompatActivity implements SaveAction, View.OnTouchListener {
private ImageView image;
private static final int CAMERA_REQUEST = 1888;
final Context context = this;
Bitmap alterdbitmap;
Internet_checking mconnectionchecking;
AlertDialog ald;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "View Share";
private Uri fileUri;
FloatingActionButton fab,fab1;
Canvas canvas;
Paint paint;
Matrix matrix;
float downx = 0;
float downy = 0;
float upx = 0;
float upy = 0;
RelativeLayout rlayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.img);
rlayout = (RelativeLayout)findViewById(R.id.rltive1);
camera();
}
#Override
protected void onResume() {
super.onResume();
functionality();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
// Bitmap photo = (Bitmap) data.getExtras().get("data");
// image.setImageBitmap(photo);
previewimage();
} else if (resultCode == RESULT_CANCELED) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage("NO IMAGE FOUND");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
ald = alert.create();
ald.show();
} else {
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_LONG)
.show();
}
}
}
#TargetApi(23)
private void previewimage() {
try {
image.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
alterdbitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
canvas = new Canvas(alterdbitmap);
paint = new Paint();
paint.setColor(Color.parseColor("#FF5722"));
paint.setStrokeWidth(5);
matrix = new Matrix();
canvas.drawBitmap(bitmap, matrix, paint);
image.setImageBitmap(alterdbitmap);
image.setOnTouchListener(this);
// rlayout.setOnTouchListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// #Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
private void functionality() {
fab1=(FloatingActionButton)findViewById(R.id.fab1);
fab = (FloatingActionButton)findViewById(R.id.fab);
// mbtn = (Button) findViewById(R.id.btn1);
mconnectionchecking = new Internet_checking(this);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mconnectionchecking.isNetworkAvailable() == true) {
final File photoFile = new File(getFilesDir(), String.valueOf(image));
Intent nt = new Intent(Intent.ACTION_SEND, Uri.fromFile(photoFile));
String title = getResources().getString(R.string.Share_Via);
Intent chooser = Intent.createChooser(nt, title);
startActivity(chooser);
} else {
AlertDialog.Builder at = new AlertDialog.Builder(context);
at.setTitle("Connection Error");
at.setCancelable(true);
at.setMessage("Internet connection required");
at.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_SETTINGS));
}
});
ald = at.create();
ald.show();
}
}
});
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
camera();
}
});
}
private void camera(){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
public void autosave() {
}
#Override
public boolean onTouch(View view, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
image.invalidate();
downx = upx;
downy = upy;
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
image.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e0080809"
tools:context="mypckage name.MainActivity">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/rltive1">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/img"
android:scaleType="fitXY"
android:layout_alignParentTop="true" />
<!--<Button-->
<!--android:layout_width="50dp"-->
<!--android:layout_height="50dp"-->
<!--android:id="#+id/btn1"-->
<!--android:layout_alignParentTop="true"-->
<!--android:layout_alignParentRight="true"-->
<!--android:layout_alignParentEnd="true"-->
<!--android:background="#drawable/share"/>-->
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
app:elevation="6dp"
app:backgroundTint="#color/colorAccent"
app:pressedTranslationZ="12dp"
android:src="#drawable/ic_share_white_24dp" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:elevation="6dp"
app:backgroundTint="#color/colorAccent"
app:pressedTranslationZ="12dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="4dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="#drawable/ic_add_a_photo_white_24dp"
android:id="#+id/fab1"/>
</RelativeLayout>
</RelativeLayout>

In your activity class use custom imageview like this:
public class DrawImageView extends LinearLayout {
Paint paint = new Paint();
Point point = new Point();
Uri uri;
Context myContext;
public DrawImageView(Context context, Uri imageUri) {
super(context);
uri = imageUri;
myContext = context;
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
try {
InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
this.setBackground(Drawable.createFromStream(inputStream, imageUri.toString()));
} catch (FileNotFoundException ignored) {
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(point.x - 10, point.y - 10, point.x + 10, point.y + 10, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
point.x = event.getX();
point.y = event.getY();
}
invalidate();
return true;
}
class Point {
float x, y;
}
}
this is just an example. in onDraw method realize your logic.

Related

Open Cv face detection Attendance by locally stored images Android

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");
}
}
}

How to fix this problem cannot resolve method startResultActivity com.google.zxing.Result?

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) {

How to call different methods with LocalBroadcastManager

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;
}

Take picture and Save picture after button is pressed

Need help on creating a method that will capture a picture, and a method that will save it if a button is pressed.
Currently, the camera is being displayed inside a TextureView as soon as the app starts and I am struggling to find a way to capture and save pictures.
It doesn't really matter if it captures from screen or from the actual phone camera.
Github: https://github.com/Chalikov/group26/tree/experimental
Thank you.
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CAMERA_PERMISSION = 200;
public static final int CAMERA_REQUEST = 1888;
private static final String TAG = "AndroidCameraApi";
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
protected CameraDevice cameraDevice;
protected CameraCaptureSession cameraCaptureSessions;
protected CaptureRequest.Builder captureRequestBuilder;
private Button takePictureButton;
private Button retryButton;
private Button acceptButton;
private TextureView textureView;
private String cameraId;
private Size imageDimension;
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//open your camera here
openCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Transform you image captured size according to the surface width and height
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
};
private ImageReader imageReader;
private Uri file;
private boolean mFlashSupported;
private Handler mBackgroundHandler;
private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
//This is called when the camera is open
Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
#Override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
#Override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
private HandlerThread mBackgroundThread;
private View view;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
textureView = (TextureView) findViewById(R.id.texture);
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
takePictureButton = (Button) findViewById(R.id.btn_takepicture);
assert takePictureButton != null;
takePictureButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
takePicture();
takePictureButton.setVisibility(View.INVISIBLE);
retryButton = (Button) findViewById(R.id.btn_retry);
acceptButton = (Button) findViewById(R.id.btn_analyze);
retryButton.setVisibility(View.VISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
retryButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
createCameraPreview();
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
}
});
retryButton.setVisibility(View.VISIBLE); //SHOW the button
acceptButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
createCameraPreview();
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
}
});
acceptButton.setVisibility(View.VISIBLE); //SHOW the button
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void takePicture() {
}
protected void savePicture() {
}
// private static File getOutputMediaFile(){
// File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES), "CameraDemo");
//
// if (!mediaStorageDir.exists()){
// if (!mediaStorageDir.mkdirs()){
// return null;
// }
// }
//
// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// return new File(mediaStorageDir.getPath() + File.separator +
// "IMG_"+ timeStamp + ".jpg");
// }
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
texture.setDefaultBufferSize(height, width);
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Log.e(TAG, "openCamera X");
}
protected void updatePreview() {
if(null == cameraDevice) {
Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// close the app
Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onResume() {
takePictureButton.setVisibility(View.VISIBLE);
super.onResume();
Log.e(TAG, "onResume");
startBackgroundThread();
if (textureView.isAvailable()) {
openCamera();
} else {
textureView.setSurfaceTextureListener(textureListener);
}
}
#Override
protected void onPause() {
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
Log.e(TAG, "onPause");
stopBackgroundThread();
super.onPause();
closeCamera();
}
}
The XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.project26.MainActivity">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextureView
android:id="#+id/texture"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/btn_takepicture"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="80dp"
android:background="#drawable/camera_button"
android:visibility="visible"/>
<Button
android:id="#+id/btn_retry"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="left|bottom"
android:layout_marginBottom="80dp"
android:layout_marginLeft="60dp"
android:background="#drawable/retry"
android:visibility="invisible" />
<Button
android:id="#+id/btn_analyze"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="right|bottom"
android:layout_marginBottom="80dp"
android:layout_marginRight="60dp"
android:background="#drawable/analyze"
android:visibility="invisible" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical|bottom"
android:background="#4D000000"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#00ffffff"
android:text="Gallery"
android:textColor="#fff"
android:textSize="12sp"/>
<Button
android:id="#+id/camera_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#00ffffff"
android:text="Camera"
android:textColor="#fff"
android:textSize="12sp"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
//Modify Id and names according to your project.
//below onclick listener takes pic
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
//override onPictureTaken method, write the below code that saves it to a file.
File pictureFile = PATHOFYOURLOCATION;
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
Log.d(TAG, "written");
Toast.makeText(getApplicationContext(), "image saved in "+pictureFile, Toast.LENGTH_SHORT).show();
fos.close();

Layout doesn't show up when I run the app

When I run the app it doesn't show up any layout just a blank page
This is my Java code:
public class MainActivity extends AppCompatActivity {
private boolean zoomOut = false;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
Button btnSelect;
LinearLayout root ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
Point point = null;
getWindowManager().getDefaultDisplay().getSize(point);
int width = point.x;
int height = point.y;
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.getLayoutParams().width = 20;
ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.MATCH_PARENT,
GridLayout.LayoutParams.WRAP_CONTENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut =false;
}else{
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
}
This is my xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp" >
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/SelectPhoto" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I've been advised that is was because onCreate wasn't placed properly but the I resolved that it's still not showing anything at all.
Please check your .Xml file name is matches with
setContentView(R.layout.activity_main);

Categories