caching api for android application - android

There is a part in my app which text and images of an article are downloaded from server and user can read a new article everyday. what I want is to store these contents and user won't need to download them again. Is there a api for that or I should handle all file writings and checking stuff?
thanks in advanced.

File cacheDir
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(Environment.getExternalStorageDirectory(),"/Android/data/<your app package>/.dir");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists()) cacheDir.mkdirs();
Create a directory like this, it will check for sdcard or will store in internal storage.
Then save incoming stream like this.
public void saveFile(InputStream is, File file){
try {
OutputStream os = new FileOutputStream(file);
copyStream(is, os);
os.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}

Related

Android: Best way to save image at external Storage

When i'm trying to save an image at some devices the app crashes.
After some research i think the problem is the imageRoot, but i'm kind of lost with so many solutions...
I think the problem is about obtaining external storage path.
The device i'm using to test my app doesn't have any sd card, the path is /mnt/sdcard/Pictures and the image is being saved successfully.
I want it to work whether phone has an sd card or not.
Thanks for any help in advance.
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
private void saveImage() {
Bitmap bitmap = sqimage.getDrawingCache();
File image = new File(imageRoot, imageName);
if (image.exists()) {
image.delete();
}
try {
FileOutputStream output = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
new SingleMediaFileConnector(getActivity().getApplicationContext(), image);
} catch (FileNotFoundException e) {
e.printStackTrace();
success = false;
} catch (IOException e) {
e.printStackTrace();
success = false;
}
}
Sometimes getExternalStoragePublicDirectory path doesn't exist. You need to check for its existence.
try {
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
File image = new File(imageRoot, imageName);
// Make sure the Pictures directory exists.
imageRoot.mkdirs();
// Other stuffs here
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
See here for more details.
[Edit]
An alternate way can be use:
getExternalFilesDir(Environment.DIRECTORY_PICTURES);

Fastest way to save the image into SD card without using Async Task

I am using Async task for downloading some other data, while that Async task executes I want to save the image from the url into the SD card. So what can be the fastest way or any alternative to save the image into sd card without using Async task. I have searched on the Google and stackoverflow, but can't find the appropriate solution.
touchView.setDrawingCacheEnabled(true);
Bitmap bitmap = touchView.getDrawingCache();
File file = new File(Environment.getExternalStorageDirectory()
+ "/MultiTouchView_Image.png");
if (file.exists())
file.delete();
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 10, ostream);
ostream.close();
touchView.invalidate();
} catch (Exception e) {
Log.e(TAG, "Save fail!");
e.printStackTrace();
} finally {
Log.e(TAG, "Save successfull!");
touchView.setDrawingCacheEnabled(false);
touchView.invalidate();
}
TouchView : The View you want to save to image.

Save database in app folder, which wont clear when uninstall the app

I want to store my database inside the app folder as like we save images, so that when uninstall the app it wont clear, is that possible to do.
Can anyone suggest how to achieve otherwise give me alternate options
Thanks in advance
The apps internal folder will always be deleted when you uninstall an application. What you want is to create an external folder, on the SDcard this will not go when you delete your application.
Example:
public void writeToSDCard() throws IOException {
System.out.println("Write To Sd");
File f=new File("/data/data/com.yourapp/databases/Bdr");
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis=new FileInputStream(f);
fos=new FileOutputStream("/mnt/sdcard/dumped.db");
while(true){
int i=fis.read();
if(i!=-1){
fos.write(i);
}
else{
break;
}
}
fos.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
fos.close();
fis.close();
}
catch(IOException ioe){
// System.out.println(ioe);
}
}
}
The above code will write your Database to the external SDCard with the name being equal to dumped.db and you will notice upon uninstall this will still persist on your SDcard
Dont forget to edit File f=new File("/data/data/com.yourapp/databases/Bdr"); according to your use case.
Also take special care that you dont hardcode the path to SDCard use Enviornmant.getExternalStorage() instead

how to write json data to a file in android

Can someone explain what is going wrong here I am using following function
public void WriteSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = context.openFileOutput("schemas.json",Context.MODE_APPEND);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, data+"Data",Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And calling with once my http request is completed
JSONObject json_res = currentDFD.getJSONObject("result");
WriteSettings(getBaseContext(),json_res.toString());
The result is alerted in toast however not written to the file
the file is located in assets folder
thanks in advance
AFAIK You can't. The assets folder is read-only at runtime.
Pick a different location to save your data, see Data Storage in Android for more information.
The assets folder is like folders res, src, gen, etc. These are all useful to provide different files as input to build system to generate APK file for your app.
All these are read-only while your app is running. At run-time you can only write to SD card.

Save Images and copy all images in sd card

I have 10 images and want to save all this images in android application memory . so whenever any use install this apps , he have already this all images .
i have hard coded many times and not get good response .
is there any way . so i will done it.
please help me
Store all your images in the assets folder of your APK. Once it gets installed, scan the internal memory to see if desired images are there. If not, copy them there. In this way, even when users clear data of your application, you can copy them back. Another good thing is the user will not know anything about it as well, so it a good user-experience. Only thing would be your APK size would increase, so manage accordingly.
Try the below piece of code
InputStream inputStream = getAssets().open("yourfile.jpg");
OutputStream out = new FileOutputStream(new File("/sdcard/yourfile.jpg"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
You can keep the files in your asset or res folder , here I have kept the file in res/drawable/ and copy them on sdcard when I require. In below code first we check if file doesn't exist the we create a bitmap from the drawable and write the file out to sdcard.
File file = new File(pathExt+"/Pictures/", "s1.png");
if(isSDCARDMounted()){
if (!file.exists()) {
bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.s1);
try {
FileOutputStream outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
isSDCARDMounted : function for checking if card is mounted or not
pathExt : variable for external storage directory path
Make sure have permission set for writing on external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources