2012-12-25 64 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