I am trying to get the APK of an app and save it in a folder on storage directory. I have got the apk but I am not able to save it to my desired folder.
Here is how I am generating apk file:
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> apps = getPackageManager().queryIntentActivities(mainIntent, 0);
for (ResolveInfo info : apps) {
File fileToSave = new File(info.activityInfo.applicationInfo.publicSourceDir)
}
Here is the code to Save the APK file where I am passing the same file to save:
private void createDirectoryAndSaveFile(File fileToSave) {
try {
String folderName = "MyCreatedFolder";
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + folderName);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
File path = new File(context.getFilesDir(), folderName);
File mypath = new File(path, fileToSave.getName());
new BufferedWriter(new FileWriter(mypath));
Toast.makeText(context, "Created", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
System.out.println("----" + e.getLocalizedMessage());
}
}
The fileToSave is the APK file but writing it says no such file or directory.
java.io.FileNotFoundException: ..../MyCreatedFolder/base.apk: open
failed: ENOENT (No such file or directory)
All the required permissions are there and runtime permissions not required as TargetSDK is 21.
How to save this file to my storage directory.?
Try this code because you want to create a folder (if it does not exist),then write into the same exact folder you created/specified hence the omission of this line File path = new File(context.getFilesDir(), folderName); but instead the path of the folder we created.
private void createDirectoryAndSaveFile(File fileToSave) {
try {
String folderName = "MyCreatedFolder";
String dire = Environment.getExternalStorageDirectory().toString();
File dir = new File(dire +"/"+ folderName);
boolean success = true;
if (!dir.exists()) {
success=dir.mkdirs();
}
if (success) {
File mypath = new File(dir + "/"+folderName+"/", fileToSave.getName());
new BufferedWriter(new FileWriter(mypath));
Toast.makeText(context, "Created", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
System.out.println("----" + e.getLocalizedMessage());
}
}
Related
I Have five sqlite databases and I want user to be able to have local backup in his phone and he can restore the backup file .
I don't know how to create these backups and restore them programatcally .
I used A github repo but it did not work at all,
I need your help to create this process of backup and restore .
Thank for your attention
In your Activity make backup and restore button and define local database variable like,
private MainDatabase localBackup = new MainDatabase(this);
Then perform backup and restore operation when it's just click
#Override
public void onClick(View v) {
final MainDatabase db = new MainDatabase(getApplicationContext());
switch (v.getId()) {
case R.id.tvBackUp:
String outFileName = Environment.getExternalStorageDirectory() +
File.separator + getResources().getString(R.string.app_name) + File.separator;
localBackup.performBackup(db, outFileName);
break;
case R.id.tvRestore:
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + getApplicationContext().getResources().getString(R.string.app_name));
if (folder.exists()) {
final File[] files = folder.listFiles();
if (files.length == 0) {
Toast.makeText(this, "No any Backup", Toast.LENGTH_SHORT).show();
} else {
localBackup.performRestore(db);
}
}
break;
}
}
Make a method for backup in your database file
public void performBackup(final MainDatabase db, final String outFileName) {
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ mContext.getResources().getString(R.string.app_name));
boolean success = true;
if (!folder.exists())
success = folder.mkdirs();
if (success) {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.backup_dialog);
dialog.getWindow().getAttributes().windowAnimations =
R.style.PauseDialogAnimation;
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
Button btnSave = dialog.findViewById(R.id.btnSave);
Button btnCancel = dialog.findViewById(R.id.btnCancel);
EditText etName = dialog.findViewById(R.id.etName);
etName.setInputType(InputType.TYPE_CLASS_TEXT);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String m_Text = etName.getText().toString();
String out = outFileName + m_Text + ".db";
db.backup(out);
dialog.dismiss();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
} else
Toast.makeText(mContext, "Unable to create directory. Retry",
Toast.LENGTH_SHORT).show();
}
public void backup(String outFileName) {
//database path
final String inFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Backup Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to backup database. Retry",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
As well as for restore do this thing,
ask to the user what backup to restore
public void performRestore(final MainDatabase db) {
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ mContext.getResources().getString(R.string.app_name));
if (folder.exists()) {
final File[] files = folder.listFiles();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item);
for (File file : files)
arrayAdapter.add(file.getName());
AlertDialog.Builder builderSingle = new AlertDialog.Builder(mContext);
builderSingle.setTitle("Select & Restore ");
builderSingle.setNegativeButton("cancle", (dialog, which) ->
dialog.dismiss());
builderSingle.setAdapter(arrayAdapter, (dialog, which) -> {
try {
db.importDB(files[which].getPath());
} catch (Exception e) {
Toast.makeText(mContext, "Unable to restore. Retry",
Toast.LENGTH_SHORT).show();
}
});
builderSingle.show();
} else
Toast.makeText(mContext, "Backup folder not present.\nDo a backup before a
restore!", Toast.LENGTH_SHORT).show();
}
public void importDB(String inFileName) {
final String outFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Restore Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to import database. Retry",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
Android already supports system automatic backups if you have android:allowBackup="true" at your manifest. If it isn't enough and you want to manage backups manually between app reinstalls than you have to copy database from context.getDatabasePath("<your-database-name>") to external storage somewhere, and then copy it back when you want
Im building an android app that needs to fetch an image from an url and, after is done displaying it into the image view, I want to store it in the hard drive of the phone so it can be use later without creating a new petition or depending on the cache.
Im using glide 4.9.0
Some of the solutions online include using some deprecated clases such as SimpleTarget and Target that wont be applicable in this project.
This is what I have so far.
File file = new File(holder.context.getExternalFilesDir(null), fileName);
if (file.exists()) {
GlideApp.with(holder.context).load(file).into(holder.ivProductImage);
} else {
GlideApp.with(holder.context).load(urlImage).into(holder.ivProductImage);
// save the image to the hard drive
}
//Step 1
Glide.with(mContext)
.load(images.get(position).getThumbnail())
.asBitmap()
.into(new Target<Bitmap>(100,100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
saveImage(resource,position);
}
});
//Step 2
private String saveImage(Bitmap image, int position) {
String savedImagePath = null;
String imageFileName = "JPEG_" + images.get(position).getName() + ".jpg";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Comicoid");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
}
return savedImagePath;
}
//Step 3
private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
Hello I am tring to open a .pdf file present in a file using an intent but it is giving me 2 errors on the following line
File file = new File(getContext().getAssets().open("assets/test.pdf"));
Errors
1.Unhandled java.IO.Exception.
2.getAssets()may produce java.lang.NullPointerException
Here us the code in a fragment
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
File file = new File(getContext().getAssets().open("assets/test.pdf"));
if (file .exists())
{
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent ); }
catch (ActivityNotFoundException e)
{
Toast.makeText(getActivity(), "Please install a pdf file viewer",
Toast.LENGTH_LONG).show();
}
}
}
}
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abc.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card
try with the file provider
Intent intent = new Intent(Intent.ACTION_VIEW);
// set flag to give temporary permission to external app to use your FileProvider
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
String uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
// I am opening a PDF file so I give it a valid MIME type
intent.setDataAndType(uri, "application/pdf");
// validate that the device can open your File!
PackageManager pm = getActivity().getPackageManager();
if (intent.resolveActivity(pm) != null) {
startActivity(intent);
}
To serve a file from assets to another app you need to use a provider.
Google for the StreamProvider of CommonsWare.
So I have a bitmap and after I edit it I want that the User can save it and see it in the gallery. I was searching in google and a found many Ideas but all I tried didn't work. This is my code:
((ImageButton) findViewById(R.id. imageButton)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(MainActivity7.this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
});
So whats wrong or do you have any other solutions how I can save my bitmap in the gallery?
Go to Settings > App and find Storage permission is allowed for your app or not. If not, allow it and try again.
I got an error in console crashes & anrs. This error is showing sometimes and I couldn't find where the problem is.
java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
The function code to save picture is:
public static String sharePhoto(Context context, Bitmap bmp) {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Folder");
boolean success = true;
String file_path = null;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
file_path = folder + "/Img_" + System.currentTimeMillis() / 1000 + ".jpg";
}
OutputStream os = null;
try {
os = new FileOutputStream(file_path);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Do something else on failure
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(file_path);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
return file_path;
}
Try this:
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/MyFolder");
Thing is that getExternalStorageDirectory() returns File. You need to get absolute path of that file and concatenate with "/Pictures/MyFolder".