问题
i'm trying to call a JsonWriter
method to add something to test.json after receiving wifi information, but after it successful write the file, the file still empty.Here are the codes.
OnReceive
@Override
public void onReceive(Context c, Intent i) {
if (i.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
{
dbhelp = new DataBaseHelper(c);
wifilist = new ArrayList<ScanResult>();
wifilist = ((WifiManager) c.getSystemService(Context.WIFI_SERVICE)).getScanResults();
dialog.dismiss();
file = new File(c.getExternalCacheDir(),"testJson.json");
try
{
out = new FileOutputStream(file);
writeJson(out);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
JsonWriter
public void writeJson(OutputStream out) throws IOException {
writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
writer.setIndent(" ");
jsonFinal(writer);}
public void jsonFinal(JsonWriter writer) throws IOException{
writer.beginObject();
writer.name("status").value("OK");
writer.name("num_results").value("");
writer.endObject();
}
the expected result should like
{
"status": "OK",
"num_results": "",
}
回答1:
you forget to call JsonWriter.close();
after writing JSONObject
do it as:
writer.name("status").value("OK");
writer.name("num_results").value("");
writer.endObject();
writer.close(); //<<< call close here
来源:https://stackoverflow.com/questions/19277529/android-jsonwriter-can-not-write-to-a-file