[英]Restore data from a Json file using GSON
I'm having a hard time trying to read in a Json file.我很难读取 Json 文件。 My restoreObjects ArrayList is always null.
我的 restoreObjects ArrayList 始终是 null。 Also, I'm not even sure if I should be parsing the file path like that, But I can't seem to understand how I'm supposed to use ContentResolver.
另外,我什至不确定我是否应该像那样解析文件路径,但我似乎无法理解我应该如何使用 ContentResolver。 Any insight would be much appreciated.
任何见解将不胜感激。
public void restoreObjects(Uri backupJsonFile) {
File backupFilePath = new File(backupJsonFile.getPath());
String sFile = backupFilePath.toString();
String split[] = sFile.split(":");
String filePath = Environment.getExternalStorageDirectory() + "/" + split[1];
//Get all the current "Objects" that are saved.
ArrayList<Object> currentObjects = getAllObjects();
int newid = getNewObjectId();
try {
//get contents of Json file
JsonReader backupData = new JsonReader(new FileReader(filePath));
//This is were the array should be populated, but is left null
ArrayList<Object> restoreObjects = gsonBuilder.fromJson(backupData, type);
for (Object rObject : restoreObjects) {
if (currentObject.contains(rObject.getId())) {
//Do work here
}
}
} catch (JsonSyntaxException | NullPointerException | IOException e) {
e.printStackTrace();
Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
}
}
Figured it out.弄清楚了。 It was combination of not capturing the InputStream and not using getContentResolver to locate the file.
这是不捕获 InputStream 和不使用 getContentResolver 定位文件的组合。
public void restoreObjects(Uri backupFile) {
ArrayList<Object> currentObjects = getAllObjects();
try {
InputStream is = mContext.getContentResolver().openInputStream(backupFile);
String jsonString;
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonString = new String(buffer, "UTF-8");
ArrayList<Object> restoreObjects = gsonBuilder.fromJson(jsonString, type);
for (Objects rObject : restoreObjects) {
if (currentObjects.contains(rObject.getId())) {
//do work
}
}
}
} catch (JsonSyntaxException | NullPointerException | IOException e) {
e.printStackTrace();
Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
}
Toast.makeText(mContext, "R.string.success", Toast.LENGTH_SHORT).show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.