How to call a button from another button in another class? - java

I have a button in my MainActivity I wanna call it in my SecondActivity inside another button basically both button does the same thing
MainActivity
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
});
SecondActivity
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Calling button from MainActivity
}
});

create a static method in a utils class for exemple that return a OnClickListener
public static View.OnClickListener getShareButtonClickListener(Activity activity) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(activity, "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
activity.startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(activity, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
};
}
and in both activities
share.setOnCLickListener(MyUtilsClass.getShareButtonClickListener(this))
but i agree with #Abbas it's better to separate your view (activity/fragments) and your business logic

Related

Android Studio bitmap save not saving properly

I am currently making an Adroid Studio app for school, and in the sign up form I have an image upload feature. It was working up until recently until I fixed my validation, and now it always returns an error (unrelated to the validation file) instead of properly saving the image on the device.
The code of the camera launcher:
//Inside OnCreate
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!CheckPermission(RegisterActivity.this))
RequestPermission(RegisterActivity.this);
else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
cameraUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
StartCamera.launch(cameraIntent);
}
}
});
//Outside of OnCreate
ActivityResultLauncher<Intent> StartCamera = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == RESULT_OK){
try {
cameraBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), cameraUri);
photo.setImageBitmap(cameraBitmap);
photoError.setError(null);
}catch (IOException e){
e.printStackTrace();
}
}
}
});
The code of the gallery launcher:
//Inside OnCreate
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!CheckPermission(RegisterActivity.this))
RequestPermission(RegisterActivity.this);
else
StartGallery.launch("image/*");
}
});
//Outside of OnCreate
ActivityResultLauncher<String> StartGallery = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
try{
if(result!=null) {
cameraBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result);
photo.setImageBitmap(cameraBitmap);
photoError.setError(null);
}
}catch (IOException e){
e.printStackTrace();
}
}
});
The code of the bitmap saving function:
//Outside of OnCreate
public boolean SaveBitmapInFolder(Bitmap bitmap){
photoName = new SimpleDateFormat("yyMMdd-HHmmss").format(new Date()) + ".jpg";
File dir = new File(Environment.getExternalStorageDirectory(), "/MyPhoto");
if(!dir.exists())
dir.mkdirs();
File dest = new File(dir, photoName);
try{
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
return true;
}catch (Exception e){
photoError.setError("An unexpected error has occurred.");
e.printStackTrace();
}
return false;
}
I have tried to rebuild the project in the build tab (It solves some issues occasionally) and clean up the code of the launchers and saving functions. In the case that the SaveBitmapInFolder function returns a false value, I have a toast that shows that an error has occurred, and this is always the result, no matter if the picture was uploaded from the gallery or taken by the camera.
Does anyone know a fix to this issue? There aren't any errors in the project logs, it just immediately goes to the catch and returns false.

its taking the screenshot but not showing in gallery

It's taking the screenshot but not showing in gallery when I check the device storage there are screenshot files but when I try to click them it says unable to find app to open this file.
I have to share the ui of my application as an image
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
store(bitmap,"share_image");
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public void store(Bitmap bm, String fileName){
dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
shareImage(file);
} catch (Exception e) {
e.printStackTrace();
}
}
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No App Available", Toast.LENGTH_SHORT).show();
}
}
You are calling your file share_image. It has no extension, so the system will treat it as a blank, basic file.
As you are using png compression, add ".png" to the file name.
store(bitmap,"share_image.png");

Get image from gallery or camepa. Crop it(android)

I'm trying to create something like this: I display 2 buttons, one is called "open gallery", the other "open camera". If I click on the gallery button we open the gallery and choose an image, then crop the image and output the cropped image. If I click camera, we create an image then crop the image and output it.
Now I have: If I first choose gallery always in imgview output crop image from gallery. Even if I choose camera and crop this image. And just same if I choose the camera in imgview always set image only from camera.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgview = (ImageView) findViewById(R.id.imageView1);
Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
buttonCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
saveFullImage();
} catch (Exception e) {
Log.e("error", e.toString());
}
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
}
public void saveFullImage() {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File create_dir=new File(Environment.getExternalStorageDirectory()+"/Vsenseloop");
if(!create_dir.exists()){
create_dir.mkdir();
}
File file=new File(Environment.getExternalStorageDirectory()+"/Vsenseloop", "ssasdasdss.jpg");
outputFileUri=Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==TAKE_PICTURE){
performCrop();
// Check if the result includes a thumbnail Bitmap
if(data!=null){
if(data.hasExtra("data")){
bitmap=data.getParcelableExtra("data");
imgview.setImageBitmap(bitmap);
}
}
}else if(requestCode==PIC_CROP){
// get the returned data
Uri imageUri=data.getData();
if(imageUri==null){
}else{
try{
bitmap=MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
}catch(FileNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
// display the returned cropped image
imgview.setImageBitmap(bitmap);
}
} else if (requestCode == PICK_FROM_GALLERY) {
bitmap = data.getParcelableExtra("data");
imgview.setImageBitmap(bitmap);
}
}
private void performCrop() {
try{
Intent cropIntent=new Intent("com.android.camera.action.CROP", null).setDataAndType(outputFileUri, "image/*").putExtra("crop", "true")
.putExtra("aspectX", 1).putExtra("aspectY", 1).putExtra("outputX", 256).putExtra("outputY", 256).putExtra("scale", true)
.putExtra("return-data", false).putExtra("scaleUpIfNeeded", true).putExtra(MediaStore.EXTRA_OUTPUT, picUri)
.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(cropIntent, PIC_CROP);
}catch(ActivityNotFoundException anfe){
// display an error message
String errorMessage="Ваше устройство не поддерживает обрезку фото!";
Toast toast=Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}

Store the taken picture from ImageView to the phone storage

After I take a picture I store the picture into ImageView, So if anyone has an idea or suggestion in how to store the picture after it shown on the ImageView into phone stage without user interaction
Thanks in advance
public class MainActivity extends Activity {
ImageView viewpict;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpict=(ImageView) findViewById(R.id.pict_result);
Button btn= (Button)findViewById(R.id.camera);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Intent intent = new Intent (getApplicationContext(),MainActivity2.class);
//startActivity(intent);
startActivityForResult(intent,0);
}
});
}
protected void onActivityResult( int requestCode, int resultCode,Intent data)
{
if (requestCode==0)
{
Bitmap theimage = (Bitmap) data.getExtras().get("data");
viewpict.setImageBitmap(theimage);
}
}
}
Try:
viewpict.buildDrawingCache();
Bitmap bm=viewpict.getDrawingCache();
And save:
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
And permission in AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android - Why won't my Toast message show?

My toast doesn't show up and I am confused because I think I made it correctly, I don't understand. As you can see its a program that shows three buttons, the first one activates a download which is supposed to open the PDFs file automatically - if there is no pdf reader a toast should pop up saying there isn't a reader. the other buttons take to a new screen and operate as a back button.
public class myactivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mProgressDialog = new ProgressDialog(myactivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Button Section = (Button) findViewById(R.id.Section);
Section.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent Section = new Intent(view.getContext(),
Section.class);
startActivity(Section);
}
});
Button Back = (Button) findViewById(R.id.Back);
Back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_OK);
finish();
}
});
startBtn = (Button) findViewById(R.id.Search);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/document.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
}
private void showPdf() {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
}
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
The above code show toast only if you have not declared the activity in your manifeast file but not when the pdf is not present. You must use FileNotFoundException for your requirement.
Updated:::
try{
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}

Categories

Resources