Delay saving picture on gallery - java

Wassup Guys, i'm doing a college project, and my app is a meme generator. After the text plotted, i'm trying to save the image pushing the button. The toast appears, but, it takes more than an hour to the pic show on the gallery. How can i make this thing save immediately?
So there are my codes to create the button listener and the store function
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
View content = findViewById(R.id.lay);
Bitmap bitmap = getScreenShot(content);
currentImage = "meme" + System.currentTimeMillis() + ".png";
store(bitmap, currentImage);
share.setEnabled(true);
}
});
public void store(Bitmap bm, String fileName){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Memes";
File dir = new File(dirPath);
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dirPath, fileName);
try{
FileOutputStream fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(this, "SALVOU ARROMBADO", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(this, "DEU RUIM VACILÃO", Toast.LENGTH_SHORT).show();
}
}

You have to use MediaScannerConnection like below .Create a method refreshMedia() -
public void refreshMedia(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
//gallery refreshed.
Log.i(TAG, "Scanned " + path);
}
});
}
}, 1500); //this is to refresh media after 1.5 second delay
}
Here imageFile.getPath() is path for your image.
Use it as below-
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
store(bitmap, currentImage);
//after saving image call refreshmedia()
refreshMedia();
}

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.

Media Player does not play audio

I am developing an application that contains a RecyclerView with some audio players. The app will download the .3gp files if they have not been downloaded.
When I click the playAudio button, the audio is not being played.
Here is my adapter code:
else if( item.getTipo().equals(AUDIO)){
MediaPlayer mediaPlayer = new MediaPlayer();
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "Audios");
File file = new File(folder.getPath() + File.separator
+ item.getNomeArquivo());
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl( item.getAudio());
File localFile = null;
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
localFile = new File(folder.getPath() + File.separator
+ item.getNomeArquivo());
File finalLocalFile = localFile;
httpsReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(context,"Baixado",Toast.LENGTH_SHORT);
holder.progressAudio.setVisibility(View.GONE);
holder.playAudio.setVisibility(View.VISIBLE);
holder.playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer != null){
String path = Environment.getExternalStorageDirectory() +
File.separator + "Audios" + File.separator
+ item.getNomeArquivo();
Log.i("PATHA",path);
mediaPlayer.create(context,Uri.parse(path));
mediaPlayer.setVolume(50,50);
mediaPlayer.start();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeText(context,"Erro ao fazer download",Toast.LENGTH_SHORT);
}
});
} else {
Toast.makeText(context, "Erro ao criar arquivo", Toast.LENGTH_SHORT).show();
}
}
How can I fix this?
Try replacing:
mediaPlayer.create(context,Uri.parse(path));
with:
mediaPlayer.create(context, Uri.fromFile(new File(path)));

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

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