easy way to save a LinkedList in a Android Application?

前端 未结 3 637
暗喜
暗喜 2021-01-22 16:07

what is the easyest or native way to save a list of objects in a android application?

i need to save it and then load it when the app starts again.

would be nice

3条回答
  •  难免孤独
    2021-01-22 16:15

    I usually don't provide full answers, but since it's in my clipboard...

    This should work with any List implementation.

    Further you'll need to to define / exchange Constants.EXTERNAL_CACHE_DIR and might want to use something else than the UI-Thread for production.

     public static void persistList(final List listToPersist, final String fileName) {
        FileWriter writer = null;
        BufferedWriter bufferedWriter = null;
        File outFile = new File(Constants.EXTERNAL_CACHE_DIR, fileName);
        try {
          if (outFile.createNewFile()) {
            writer = new FileWriter(outFile);
            bufferedWriter = new BufferedWriter(writer);
            for (String item : listToPersist) {
              bufferedWriter.write(item + "\n");
            }
            bufferedWriter.close();
            writer.close();
          }
        } catch (IOException ioe) {
          Log.w(TAG, "Exception while writing to file", ioe);
        }
      }
    
      public static List readList(final String fileName) {
        List readList = new ArrayList();
        try {
          FileReader reader = new FileReader(new File(Constants.EXTERNAL_CACHE_DIR, fileName));
          BufferedReader bufferedReader = new BufferedReader(reader);
          String current = null;
          while ((current = bufferedReader.readLine()) != null) {
            readList.add(current);
          }
        } catch (FileNotFoundException e) {
          Log.w(TAG, "Didn't find file", e);
        } catch (IOException e) {
          Log.w(TAG, "Error while reading file", e);
        }
        return readList;
      }
    

提交回复
热议问题