Question

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": "",
}
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top