gpt4 book ai didi

ANDROID:如何将 JSON 数据保存在文件中并进行检索?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:56:44 30 4
gpt4 key购买 nike

我是 android 的新手,所以请帮助我。我试图将我的 ToDoList 保存在一个文件中,以便下次打开它时,所有项目都会重新加载

这是我目前的代码,

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() 中,我想检查文件是否存在,如果存在,则从文件导入数据并显示在屏幕上。

最佳答案

每个 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 = context.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();
}

Activity的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

关于ANDROID:如何将 JSON 数据保存在文件中并进行检索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40168601/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com