Store and Get the data from Cache in Android.

It's Interesting, most of peoples thinks about the database, shared preferences and content providers for offline data storage.

Some different came like data must be stored in cache, when app offline, retrieve data from the cache.

Just try this, It might be useful for you.


public String temp_filename = "user_data.txt";
public File tempFile;

// To Store the file in Cache
public void storeToCache(Context context, String data) {
        if (data != null && !data.equals("")) {
            FileWriter writer;
            try {
                writer = new FileWriter(getCacheFile(context));
                writer.write(data);
                writer.close();
                Log.d(TAG, "stored to cache");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

// To Check the file is exist or not
public boolean isCacheExist(Context context) {
        boolean isExist;
        isExist = getCacheFile(context).exists();
        Log.d(TAG, "cache exists " + String.valueOf(isExist));
        return isExist;
}

// To Clear the cache 
public void clearCache(Context context) {
        if (getCacheFile(context).exists()) {
            getCacheFile(context).delete();
            Log.d(TAG, "cache cleared");
        } else {
            showErrorToast(context, "File not found");
        }
}

// To retrieve the cache
public String retrieveCache(Context context) {
        String strLine = "";
        StringBuilder text = new StringBuilder();
        /** Reading contents of the temporary file, if already exists */
        try {
            FileReader fReader = new FileReader(getCacheFile(context));
            BufferedReader bReader = new BufferedReader(fReader);
            /** Reading the contents of the file , line by line */
            while ((strLine = bReader.readLine()) != null) {
                text.append(strLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text.toString();
}

// To get the Cache File
public static File getCacheFile(Context context){
File cacheDir = context.getCacheDir();
tempFile = new File(cacheDir.getPath() + "/" + temp_filename);
return tempFile;
}

Comments

Popular posts from this blog

Flutter Bloc - Clean Architecture

Dependencies vs Dev Dependencies in Flutter

What's new in android 14?