简体   繁体   中英

Android: save gson.toJson() return string on my sdcard

I am trying to make an app their save some Json-data in a local-file(on sdcard)..

The first time it run I just have to save the json-data in a file...

Then return the 'applications_arr' (NOT from the file but from the JsonReader)

See the holde asyncTask-class here :

And there ApplicationsModel.class (implements Parcelable)


amFile = new File(this.activity.getFilesDir()+"/applications"+UUID.randomUUID()+".json");
gson = new GsonBuilder().create();

reader = new JsonReader(new BufferedReader(new InputStreamReader(new URL("http://software-center.ubuntu.com/api/2.0/applications/any/ubuntu/any/any/").openConnection().getInputStream())));
reader.beginArray();

//save am-json-data on sdcard
FileWriter fw = new FileWriter(amFile.getAbsoluteFile());
fw.write(gson.toJson(reader, ApplicationsModel.class));
fw.close();

//create am-arraylist to use now.. amFile is other use      
while (reader.hasNext()) {
    ApplicationsModel model = gson.fromJson(reader, ApplicationsModel.class);
    applications_arr.add(model);
}
reader.endArray();
reader.close();

It look like the error is with:

fw.write(gson.toJson(reader, ApplicationsModel.class));

My Logcat look like this .

You probably need to specify the WRITE_EXTERNAL_STORAGE permission in your manifest .

This would look like:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

EDIT:

Looking at your logcat, the error is:

java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException: expected receiver of type com.ubuntu.apps.ApplicationsModel, not com.google.gson.stream.JsonReader

Which is saying that Gson is expecting to read in an ApplicationModel, and instead you are giving it a JsonReader.

That said, the line where you are trying to save the Json you're reading streaming from the URL to a file doesn't need Gson. Just stream the Json straight to the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM