From a725f9890e783824e43543476879cc2ff5a162f7 Mon Sep 17 00:00:00 2001 From: Rashiq Ahmad Date: Sun, 8 Dec 2013 16:12:48 +0100 Subject: [PATCH] FileWriter --- src/org/kiwix/kiwixmobile/FileWriter.java | 87 ++++++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/src/org/kiwix/kiwixmobile/FileWriter.java b/src/org/kiwix/kiwixmobile/FileWriter.java index 290bd9843..0340dbfde 100644 --- a/src/org/kiwix/kiwixmobile/FileWriter.java +++ b/src/org/kiwix/kiwixmobile/FileWriter.java @@ -1,11 +1,96 @@ package org.kiwix.kiwixmobile; +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +import java.io.File; import java.util.ArrayList; +import java.util.Arrays; public class FileWriter { - public void saveArray(ArrayList<>){ + private static final String PREF_NAME = "csv_file"; + private static final String CSV_PREF_NAME = "csv_string"; + + private Context mContext; + + private ArrayList mDataList; + + public FileWriter(Context context) { + mContext = context; } + public FileWriter(Context context, ArrayList dataList) { + mDataList = dataList; + mContext = context; + } + + // Build a CSV list from the file paths + public void saveArray(ArrayList files) { + + ArrayList list = new ArrayList(); + + for (ZimFileSelectActivity.DataModel file : files) { + list.add(file.getPath()); + } + + StringBuilder sb = new StringBuilder(); + for (String s : list) { + sb.append(s); + sb.append(","); + } + + saveCsvToPrefrences(sb.toString()); + } + + // Add items to the MediaStore list, that are not in the MediaStore database. + // These will be loaded from a previously saved CSV file. + // We are checking, if these file still exist as well. + public ArrayList getDataModelList() { + + for (String file : readCsv()) { + if (!mDataList.contains(new ZimFileSelectActivity.DataModel(getTitleFromFilePath(file), file))) { + + mDataList.add(new ZimFileSelectActivity.DataModel(getTitleFromFilePath(file), file)); + } + } + + return mDataList; + } + + // Split the CSV by the comma and return an ArrayList with the file paths + private ArrayList readCsv() { + + String csv = getCsvFromPrefrences(); + + String[] csvArray = csv.split(","); + + return new ArrayList(Arrays.asList(csvArray)); + } + + // Save a CSV file to the prefrences + private void saveCsvToPrefrences(String csv) { + + SharedPreferences preferences = mContext.getSharedPreferences(PREF_NAME, 0); + SharedPreferences.Editor editor = preferences.edit(); + editor.putString(CSV_PREF_NAME, csv); + + editor.commit(); + } + + // Load the CSV from the prefrences + private String getCsvFromPrefrences() { + SharedPreferences preferences = mContext.getSharedPreferences(PREF_NAME, 0); + + return preferences.getString(CSV_PREF_NAME, ""); + } + + // Remove the file path and the extension and return a file name for the given file path + private String getTitleFromFilePath(String path) { + return new File(path).getName().replaceFirst("[.][^.]+$", ""); + } } + +