2016-10-21 4 views
2

Я новичок в android, поэтому, пожалуйста, помогите мне. Я пытаюсь сохранить мой ToDoList в файле, так что в следующий раз я открываю его, все элементы перезагружаетсяANDROID: Как сохранить данные JSON в файле и получить его?

Это код, который я до сих пор,

MainActivity.java

@Override 
protected void onCreate(Bundle savedInstanceState) { 
gson = new Gson(); 
    try { 
     BufferedReader br = new BufferedReader(new FileReader("storage.json")); 
     Entry e = gson.fromJson(br, Entry.class); 
     Log.d("reading", e.toString()); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    }} 

@Override 
protected void onStop() { 
    super.onStop(); 
    json = gson.toJson(mEntries); 
    Log.d("jsondata", json); 
    try { 
     file1 = new FileWriter("storage.json"); 
     file1.write(json); 
     file1.flush(); 
     file1.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

Entry.java

public class Entry { 
String S; 
boolean b; 

public Entry(String S, boolean b) { 
    this.S = S; 
    this.b = b; 
} 

public String getS() { 
    return S; 
} 

public void setS(String S) { 
    this.S = S; 
} 

public void setB(boolean b) { 
    this.b = b; 
} 

public boolean isB() { 
    return b; 
} 

}

Как это исходит? В onCreate() Я хотел бы проверить, существует ли файл, и да, импортировать данные из файла и отображать на экране.

+0

Возможный дубликат [Как для чтения/записи строки из файла в Android] (HTTP://stackoverflow.com/questions/14376807/how-to-read-write-string-from-a-file-in-android) –

+0

Прочтите [здесь] (https://developer.android.com/training/basics/data -Хранение/files.html) –

ответ

1

У каждого приложения для Android есть собственное внутреннее хранилище, доступное только для приложения, вы можете читать или писать на него.

В этом случае вы сначала хотите проверить, существует ли такой файл до его создания.

private String read(Context context, String fileName) { 
    try { 
     FileInputStream fis = context.openFileInput(fileName); 
     InputStreamReader isr = new InputStreamReader(fis); 
     BufferedReader bufferedReader = new BufferedReader(isr); 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
      sb.append(line); 
     } 
     return sb.toString(); 
    } catch (FileNotFoundException fileNotFound) { 
     return null; 
    } catch (IOException ioException) { 
     return null; 
    } 
} 

private boolean create(Context context, String fileName, String jsonString){ 
    String FILENAME = "storage.json"; 
    try { 
     FileOutputStream fos = openFileOutput(fileName,Context.MODE_PRIVATE); 
     if (jsonString != null) { 
      fos.write(jsonString.getBytes()); 
     } 
     fos.close(); 
     return true; 
    } catch (FileNotFoundException fileNotFound) { 
     return false; 
    } catch (IOException ioException) { 
     return false; 
    } 

} 

public boolean isFilePresent(Context context, String fileName) { 
    String path = context.getFilesDir().getAbsolutePath() + "/" + fileName; 
    File file = new File(path); 
    return file.exists(); 
} 

OnCreate в деятельности, вы можете использовать сделайте следующее

boolean isFilePresent = isFilePresent(getActivity(), "storage.json"); 
if(isFilePresent) { 
    String jsonString = read(getActivity(), "storage.json"); 
    //do the json parsing here and do the rest of functionality of app 
} else { 
    boolean isFileCreated = create(getActivity, "storage.json", "{}"); 
    if(isFileCreated) { 
    //proceed with storing the first todo or show ui 
    } else { 
    //show error or try again. 
    } 
} 

присвоенный https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Смежные вопросы