Opening Previously Downloaded Database - java

So, this program downloads a file from firebase storage,
my downloading code is:
private void downloadFiles(Context context, String fileName, String destinationDirectory, String url) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName);
downloadManager.enqueue(request);
}
public void downloading(final String name) {
downloadRef = storage.getInstance().getReference().child(name);
downloadRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFiles(Main2Activity.this, name, Environment.getExternalStorageState((File) Downloads), url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main2Activity.this, "Failed!!!", Toast.LENGTH_LONG).show();
}
});
}
and then I want to use this database so I tried to open it with:
database = SQLiteDatabase.openDatabase(Environment.getExternalStorageState((File) Downloads) + "/" + name, null, SQLiteDatabase.OPEN_READWRITE);
but it says
Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
How can I solve this one?

Related

java.io.FileNotFoundException: open failed: ENOENT (No such file or directory) - Android 11

I am not sure what I am doing wrong exactly but keep getting this error while trying to save the bitmap into a png file and send to another Activity:
private void savePhoto() {
resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "Image_" + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + getFilesDir() + File.separator + "TextPhoto");
imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
// outputMediaFile.createNewFile();
SaveSettings build = new SaveSettings.Builder().setClearViewsEnabled(true).setTransparencyEnabled(true).build();
if (ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") == 0) {
mPhotoEditor.saveAsFile(new File(imageUri.getPath()).getAbsolutePath(), build, new PhotoEditor.OnSaveListener() {
public void onFailure(Exception exc) {
}
public void onSuccess(String str) {
listPhoto.set(position, str);
EditPhotoActivity editPhotoActivity = EditPhotoActivity.this;
intent.putStringArrayListExtra("AFTER", listPhoto);
editPhotoActivity.setResult(115, editPhotoActivity.intent);
finish();
}
});
}
}
Content schemacontent:// is not File schema file:// cannot use in File class

Android Studio WebView - Downloading files with admin-ajax.php extension

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

Downloaded file not visible from the file browser

I download a file from firebase using file like. If I run this code on android emulator then I can see the downloaded file from file browser but in the real phone, it does not display the file.
private void DownloadFromStorage(String fileName) {
// CREATE FOLDER IF NOT EXIST
File dir = new File(DownloadActivity.this.getExternalFilesDir(null), "notes");
if (!dir.exists()) {
boolean b = dir.mkdir();
}
// CREATE FILE
File file = new File(DownloadActivity.this.getExternalFilesDir(null), fileName);
StorageReference storageReference = FirebaseStorage.getInstance().getReference()
.child("note")
.child(fileName);
Log.d("downloadFile: " ,""+ storageReference.getPath());
storageReference.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
if (getBaseContext() != null) {
txtStatus.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
myToast("Download Complete.");
Log.d("downloadFile: " ,"DOWNLOAD COMPLETE");
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (getBaseContext() != null) {
txtStatus.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
myToast("Download Fail");
Log.d("downloadFile: " ,"DOWNLOAD FAIL");
}
}
}).addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull FileDownloadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
#SuppressLint("DefaultLocale") String uc = String.format("Downloading... %.2f ", progress);
if (getBaseContext() != null) txtStatus.setText(uc);
}
});
}
How can I see this file from the file browser?

Why Broadcast Receiver doesn't Call after download manager is completed?

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

setting image uri gives Unable to decode stream: java.io.FileNotFoundException:

I've simple app for capturing image using Camera using following code
#AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
Log.d(TAG, "launchCamera");
// Check that we have permission to read images from external storage.
String perm = android.Manifest.permission.READ_EXTERNAL_STORAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !EasyPermissions.hasPermissions(this, perm)) {
EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
RC_STORAGE_PERMS, perm);
return;
}
// Create intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Choose file storage location
File file = new File(Environment.getExternalStorageDirectory(), UUID.randomUUID().toString() + ".jpg");
mFileUri = Uri.fromFile(file);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// Launch intent
startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}
now I want to upload that image to Firebase storage
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_TAKE_PICTURE) {
if (resultCode == RESULT_OK) {
if (mFileUri != null) {
uploadFromUri(mFileUri);
} else {
Log.w(TAG, "File URI is null");
}
} else {
Toast.makeText(this, "Taking picture failed.", Toast.LENGTH_SHORT).show();
}
}
}
private void uploadFromUri(Uri fileUri) {
Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());
// [START get_child_ref]
// Get a reference to store file at photos/<FILENAME>.jpg
final StorageReference photoRef = mStorageRef.child("photos")
.child(fileUri.getLastPathSegment());
// [END get_child_ref]
// Upload file to Firebase Storage
// [START_EXCLUDE]
showProgressDialog();
// [END_EXCLUDE]
Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
photoRef.putFile(fileUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Upload succeeded
Log.d(TAG, "uploadFromUri:onSuccess");
// Get the public download URL
mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
Log.w("IMAGE_URL", "Path is " + mDownloadUrl.toString());
uploadedImage = (ImageView) findViewById(R.id.uploaded_img);
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
// [START_EXCLUDE]
hideProgressDialog();
///updateUI(mAuth.getCurrentUser());
// [END_EXCLUDE]
}
})
);
}
in uploadFromUri() at line
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
image is not set in ImageView and I get error
07-29 09:54:23.055 18445-18445/? W/IMAGE_URL: Path is https://firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6
07-29 09:54:23.056 18445-18445/? E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: https:/firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6: open failed: ENOENT (No such file or directory)
and if I open this link I see image there, question is why it is not set in image view
setImageURI() is for content URIs particular to the Android
platform, not URIs specifying Internet resources.
Try getting your bitmap from internet in a new thread an then add it to your ImageView. Like this:
uploadedImage.setImageBitmap(getImageBitmap(mDownloadUrl));
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
You also can use a useful library to set image (Internal and external images) called Picasso http://square.github.io/picasso/
Add Picasso library for image loading and use the following code.
Picasso.with(activity).load(imageURL)
.resize(imageWidth,imageHeight)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
Log.d(TAG,"successfully load the image");
}
#Override
public void onError() {
Log.d(TAG,"fail to load the image");
}
});

Categories