I'm setting download manager to download PDF file for server URL.
file is download completely but Broadcast Receiver doesn't call to open file .
I use AsyncTask and doInBackground class for downloading and set permission.INTERNET,permission.WRITE_EXTERNAL_STORAGE,permission.WRITE_INTERNAL_STORAGE ,permission.READ_EXTERNAL_STORAGE in manifest.
i checked my directory in real device and PDF file is completely download without any crash .
in OnCreate
registerReceiver(onComplete, filter);
in onClick Button
downloadPdf(v);
} else {
requestStoragePermission(v);
}
and also set onDestroy
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onComplete);
}
and downloading file
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0];
String fileName = strings[1];
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, DIRECTORY_PDF_NAME);
if (!folder.exists()) {
folder.mkdir();
}
// File pdfFile = new File(folder, fileName);
file_download(fileUrl);
return null;
}
public void file_download(String fileUrl) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DIRECTORY_PDF_NAME + "/" + "au.pdf");
if (file.exists()) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "انتخاب برنامه");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(LoginActivity.this, "عدم موفقیت در نمایش فایل", Toast.LENGTH_SHORT).show();
}
} else {
mgr = (DownloadManager) LoginActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(fileUrl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("راهنمای ثبت نام")
.setDescription(" در حال دانلود..." + "فایل راهنمای ثبت نام")
.setDestinationInExternalPublicDir("/" + DIRECTORY_PDF_NAME + "/", "au.pdf");
try {
refid = mgr.enqueue(request);
Log.d(TAG, "Checking download status for id: " + refid);
} catch (ActivityNotFoundException e) {
Toast.makeText(LoginActivity.this, "عدم موفقیت در دانلود فایل", Toast.LENGTH_SHORT).show();
}
}
}
}
and at the end
public void onReceive(Context ctxt, Intent intent) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DIRECTORY_PDF_NAME + "/" + "au.pdf");
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intentPdf = Intent.createChooser(target, "انتخاب برنامه");
try {
startActivity(intentPdf);
} catch (ActivityNotFoundException e) {
}
}
I solve this problem with this solution
I create a a PDF Class and transfer my downloading code in it.
public Pdf(Context context, String url, String fileName) {
this.context = context;
this.url = url;
this.fileName = fileName;
init();
}
private void init() {
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Download_Uri = Uri.parse(url);
}
public void checkAndDownload() {
if (isStoragePermissionGranted()) {
if (isExistPdfFile()) {
openGeneratedPDF();
}else{
downloadPdf();
}
}
}
public void permissionGranted(int[] grantResults) {
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
downloadPdf();
}
}
private boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else {
return true;
}
}
public BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
isCompeleted = true;
openGeneratedPDF();
}
};
private boolean isExistPdfFile() {
File target = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File(target, DIRECTORY_PDF_NAME + "/" + fileName + ".pdf");
if (file.exists()) {
return true;
}else{
return false;
}
}
private void openGeneratedPDF() {
if (isExistPdfFile()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
Log.e("uri is",uri.toString());
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "برنامهای برای نمایش فایل PDF وجود ندارد", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(context,"فایل مورد نظر یافت نشد",Toast.LENGTH_LONG).show();
}
}
private void downloadPdf() {
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(true);
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, Constant.DIRECTORY_PDF_NAME + "/" + fileName + ".pdf");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
}
public boolean getIsCompeleted() {
return isCompeleted;
}
and call it in my requirement Activity ,also i use file provider such as
Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
Related
I've been learning Android Studio (I'm not an expert). However, I managed to code my WebView app from a website and I can't make it download the files as their original file names... For some reason I'm getting an "admin-ajax.php" file in return.
This is the code on MainActivity.java:
mywebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long l) {
//file name
String fileName = URLUtil.guessFileName(url,contentDisposition,getFileType(url));
sFileName = fileName.substring(fileName.lastIndexOf('/')+1);
sURL = url;
sUserAgent = userAgent;
//check android version
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission( MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
==PackageManager.PERMISSION_GRANTED){
downloadFile(fileName,url,userAgent);
}else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1001);
}
}else{
downloadFile(fileName,url,userAgent);
}
}
public void onPageStarted(WebView view,String url, Bitmap favicon){
onPageStarted (view,url, favicon);
}
});
}
#Override
public void onBackPressed() {
if (webView.canGoBack())
webView.goBack();
else
super.onBackPressed();
}
public String getFileType(String url){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(Uri.parse(url)));
}
private void downloadFile(String fileName, String url, String userAgent){
try {
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request (Uri.parse(url));
String cookie = CookieManager.getInstance().getCookie(url);
request.setTitle(fileName)
.setDescription("is being downloaded")
.addRequestHeader("cookie",cookie)
.addRequestHeader("User - Agent", userAgent)
.setMimeType(getFileType(url))
.setAllowedOverMetered(true)
.setAllowedOverRoaming(true)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE
|DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
sURL = "";
sUserAgent = "";
sFileName = "";
Toast.makeText( this, "Download Started", Toast.LENGTH_SHORT).show();
}catch (Exception ignored){
Toast.makeText( this, "error"+ignored, Toast.LENGTH_SHORT).show();
}
}
public void onRequestPermissionResult(int requestCode, #NonNull String [] permissions, int[] grantResults){
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
if (requestCode==1001){
if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (!sURL.equals("")&&!sFileName.equals("")&&!sUserAgent.equals("")){
downloadFile(sFileName,sURL,sUserAgent);
}
}
}
}
What could be the issue?
Thank you everyone for the support.
Kind regards,
Use this code below. Replace i.setDataAndType(uri, "application/pdf");into another type of file extension if :
the file extension is not pdf; and
you want to open the file after download.
public class WebViewActivity extends AppCompatActivity {
...
private String fileName;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//setup the fileName
//fileName = URLUtil.guessFileName(url,contentDisposition,mimeType);
fileName = (contentDisposition.substring(contentDisposition.lastIndexOf("filename*=UTF-8")+17));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(fileName));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
fileName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//Registering receiver in Download Manager
registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
...
BroadcastReceiver onCompleted = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context.getApplicationContext(), "Download Finish", Toast.LENGTH_SHORT).show();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
Uri uri = FileProvider.getUriForFile(WebViewActivity.this, "com.example.app"+".provider",file);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, "application/pdf");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(i);
}
};
}
As the title says, I am trying to upload images from both camera and gallery to firebase. But I have problems in both.
When I try to upload my image from the camera I get:
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
Even though my firebase rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
But when I try using the gallery I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.varroxsystems.plant.newPlant.Fileuploader(newPlant.java:192)
at com.varroxsystems.plant.newPlant.access$100(newPlant.java:57)
at com.varroxsystems.plant.newPlant$2.onClick(newPlant.java:162)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
And I get no data in the firebase real time database nor in the firebase storage.
But I use this exact code on another application and it works just fine.
Does anyone know what am I doing wrong?
Code:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plants = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plants.setPlname(pname);
plants.setPldate(pdate);
plants.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plants);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
}
}
private String getExtension(Uri uri)
{
ContentResolver cr=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void askFileReadPermission() {
if (ContextCompat.checkSelfPermission(newPlant.this,
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.CAMERA) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.CAMERA)||ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
alert();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile && writeExternalFile)
{
alert();
} else {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
private void alert() {
new androidx.appcompat.app.AlertDialog.Builder(newPlant.this)
.setTitle(null)
.setMessage("Where would you like to get your picture from?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Open Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dispatchTakePictureIntent();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton("Open Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
gallery.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(gallery,"Select Picture"), GALLERY_REQUEST_CODE);
}
})
.setIcon(android.R.drawable.ic_menu_camera)
.show();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
File f = new File(currentPhotoPath);
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(f).getPath());
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
uri = Uri.fromFile(f);
mediaScanIntent.setData(uri);
this.sendBroadcast(mediaScanIntent);
System.out.println(databaseHelper.getProfilesCount());
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
if (requestCode == GALLERY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
if (data != null){
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri curi = item.getUri();
uri = item.getUri();
File imageFile = new File(getRealPathFromURI(newPlant.this, curi));
//mArrayUri.add();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(curi);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
// DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
// Cursor cursor22 = mDatabaseHelper.GetPath();
// while (cursor22.moveToNext()){
// System.out.println("SELECTED " + cursor22.getString(i));
// }
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
Log.v("LOG_TAG", "Selected Images ");
}else {
//Toast.makeText(profuctadd.this,"NO IMAGE EXCEPTION",Toast.LENGTH_LONG).show();
System.out.println(data.getData());
if (data.getData()!=null){
Uri contentUri = data.getData();
uri = data.getData();
System.out.println("CONTENT URI "+contentUri);
File imageFile = new File(getRealPathFromURI(newPlant.this, uri));
System.out.println("FILE "+imageFile);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(uri);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
//DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
//Cursor cursor22 = mDatabaseHelper.GetPath();
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
// }
}
}
}
}
private String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
return "";
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private String getFileExt(Uri contentUri) {
ContentResolver c = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(c.getType(contentUri));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
Toast.makeText(newPlant.this,ex.getMessage(),Toast.LENGTH_LONG).show();
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.varroxsystems.plant.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
I have the following Java code which downloads an image from an URL.
I can see the image downloaded in the folder, but the image does not appear in gallery. Only if I restart phone, Samsung S7 with android 7, I can see images in gallery. What can I do to have the images in gallery in real time after I downloaded them?
public class DetailsImgActivity extends AppCompatActivity {
private static final String TAG = "DetailsImgActivity";
private ImageView imageViewPoze;
private Button buttonDownload;
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_img);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
// image url stored in imageID
final String imageId = getIntent().getStringExtra("ImageId");
imageViewPoze = findViewById(R.id.imageViewPozeC);
Picasso.get().load(imageId).into(imageViewPoze);
buttonDownload = findViewById(R.id.btn_Download_Img);
buttonDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
downloadFile(imageId);
}
});
}
private void downloadFile(String url) {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://firebasestorage.blabla.com/");
Retrofit retrofit = builder.build();
FileDownloadClient fileDownloadClient = retrofit.create(FileDownloadClient.class);
Call<ResponseBody> call = fileDownloadClient.downloadFile(url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
// if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
return null;
}
}.execute();
//after the image has been downloaded -refresh gallery
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "error");
}
});
}
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
String folder_main = Constants.dirName;
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), folder_main);
if (!f.exists()) {
f.mkdirs();
}
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM+"/"+ Constants.dirName)
+ File.separator + UUID.randomUUID()+".jpg");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
}
I used the follwing code, but If I don't reboot phone, I can't see the picture in gallery.
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**
When the service starts, I call startRecording() from onStartCommand(), and when the service ends, onDestroy() is called, from which I call stoprecording(). But recorder.stop() gives me an IllegalStageException
void startRecording() {
recordList = new ArrayList<>();
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
recordListString = mSharedPreferences.getString("RecordList", null);
if(recordListString!=null){
recordList = new ArrayList(Arrays.asList(TextUtils.split(recordListString, ",")));
}
currentFormat = Integer.parseInt(mSharedPreferences.getString("PREF_REC_LIST", "1"));
tempRecNum = mSharedPreferences.getString("TempRecNum", null);
audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
recorder = new MediaRecorder();
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),0);
if (error){
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
}else {
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
}
cleanDate = System.currentTimeMillis();
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
/**recorder.setAudioEncodingBitRate(16);
recorder.setAudioSamplingRate(96000);**/
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
mSharedPreferences.edit().putBoolean("isRecording", true).apply();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (RuntimeException e) {
File filepath = Environment.getExternalStorageDirectory();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
String tempPath = file.getAbsolutePath();
if(contactExists) {
boolean err = new File(tempPath + "/" +
getContactDisplayNameByNumber(tempRecNum, this)+"___"+
tempRecNum+"|__"+recCount+file_exts[currentFormat]).delete();
recordList.remove(recordList.size()-1);
}else{
boolean err = new File(tempPath + "/" +
"___"+tempRecNum+"|__"+recCount+file_exts[currentFormat]).delete();
recordList.remove(recordList.size()-1);
}
error = true;
startRecording();
}
}
private String getFilename() {
File filepath = Environment.getExternalStorageDirectory();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdir();
}
path = file.getAbsolutePath() + "/";
if(contactExists(this, tempRecNum, getContentResolver())) {
contactExists = true;
fileName = getContactDisplayNameByNumber(tempRecNum, this)+
"___"+tempRecNum+"|__"+recCount+file_exts[currentFormat];
recordList.add(fileName);
return (path + "/" + fileName);
}else {
contactExists = false;
fileName = "___"+tempRecNum+"|__"+recCount+file_exts[currentFormat];
recordList.add(fileName);
return (path + "/" + fileName);
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
edit().putBoolean("isRecording", false).apply();
Toast.makeText(RecorderService.this,
"Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(RecorderService.this,
"Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
.show();
}
};
#Override public void onDestroy(){
stopRecording();
super.onDestroy();
}
void stopRecording(){
try{
if (recorder != null) {
mSharedPreferences.edit().putString("RecordList", TextUtils.join(",", recordList)).apply();
mSharedPreferences.edit().putInt("RecCount", recCount+1).apply();
recorder.stop(); //This is where the error is thrown.
recorder.release();
recorder = null;
}
}catch(RuntimeException stopException){
stopException.printStackTrace();
}
}
Hi i am trying to download video file and pdf through DownloadManager. For pdf its working fine but when i am trying to download the video its not getting downloaded.
I am using below code:
private void downloadFileFromServer(String fid, String title, String uri) {
boolean isPdf = uri.matches(".*\\b.pdf\\b.*");
if (isPdf) {
fileName = fid + ".pdf";
} else {
fileName = fid + ".mp4";
}
File file = new File(getActivity().getExternalFilesDir("DDocs/")
+ "/Files/" + fileName);
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (isPdf) {
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
} else {
intent.setDataAndType(Uri.fromFile(file), "video/mp4");
}
startActivity(intent);
} else if (BUtil.isOnline(getActivity())) {
downloadManager = (DownloadManager) getActivity().getSystemService(
DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse(uri);
DownloadManager.Request request = new DownloadManager.Request(
Download_Uri);
request.addRequestHeader(BConstant.WEB_SERVICES_COOKIES,
cookie);
request.addRequestHeader(BConstant.WEB_SERVICES_TOKEN_HEADER,
token);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE);
request.setTitle(title);
request.setDestinationInExternalFilesDir(getActivity(),
"DDocs/Files", fileName);
if (!file.exists()) {
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage(BConstant.LODING);
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
lastDownload = downloadManager.enqueue(request);
}
} else if (!BUtil.isOnline(getActivity())) {
ToastUserMessage.message(getActivity(),
BUserMessage.FIRST_TIME_LOAD_MESSAGE);
}
}