2012-12-25 37 views
1

我试图让一个应用程序其保存在本地文件的一些JSON的数据(SD卡上)..安卓:保存gson.toJson()返回的字符串在我的SD卡

第一次运行它我只需要保存JSON数据文件中的...

然后返回“applications_arr”(而不是从文件,但是从JsonReader)

见holde的AsyncTask类here

还有ApplicationsModel.class(实现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(); 

它看起来像错误是:

fw.write(gson.toJson(读取器,ApplicationsModel.class));

我的Logcat看起来像this

+0

什么是错误,你有什么在logcat或你根本没有得到预期的结果? – vodich

+0

是logcat说FATAL EXCEPTION:AsyncTask#2 ..我用logcat-drop更新了这个问题。 – Voidcode

回答

0

您可能需要在您的manifest中指定WRITE_EXTERNAL_STORAGE权限。

这看起来像:

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

编辑:

看着你logcat中,错误的是:

java.util.concurrent.ExecutionException: 的java.lang。 IllegalArgumentException:类型为 的预期接收方com.ubuntu.apps.ApplicationsModel,而不是 com.google.gson.stream.JsonReader

这是说,Gson期待在ApplicationModel中读取,而是你给它一个JsonReader。

也就是说,你正试图保存你正在阅读的Json流从URL到一个文件的行并不需要Gson。只需将Json直接流入文件。

+0

我在清单中加上了WRITE_EXTERNAL_STORAGE加ACCESS_NETWORK_STATE和INTERNET。所以这不是错误! – Voidcode