编写和访问保存到内部存储器的JSON文件

时间:2014-04-29 19:17:10

标签: java android json

我尝试将JSON保存到内部内存,以减少我的应用访问网络的次数,并加快性能。我遇到的问题似乎是永远不会创建该文件。

写入文件:

protected JSONObject doInBackground(String... arg0) {
            JSONParser jParser = new JSONParser();

            // Get JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            JSONObject runeInfo = jParser.getJSONFromUrl(url2);
            Log.i("Main JSON", "" + json);

            // Get JSON containing Rune Info and cache it
            String jsonString = runeInfo.toString();
            File file = new File(getFilesDir(), "runesInfo.json");

            FileOutputStream fOut = null;
            try {
                fOut = openFileOutput("runesInfo.json", Context.MODE_PRIVATE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                fOut.write(jsonString.getBytes());
                fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d("Cache", "Cache Complete");

            return json;
        }

从文件中读取:

 public class GetRunes extends AsyncTask<String, String, String> {


        protected String doInBackground(String[] runeId) {

            String readJson = null;
            String name = null;

            try {
                FileInputStream fis = openFileInput("runesInfo.json");
                InputStreamReader isr = new InputStreamReader(fis);

                fis.read(readJson.getBytes());
                JSONObject storedJson = new JSONObject(readJson);
                Log.d("Stored JSON", "" + storedJson);
                JSONObject idJson = storedJson.getJSONObject("data");
                JSONObject single = idJson.getJSONObject(runeId[0]);

                try {
                    name = single.getString("name");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return name;
        }
    }

我的logcat:

04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ java.util.concurrent.ExecutionException: java.lang.NullPointerException
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:223)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask.get(FutureTask.java:82)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.get(AsyncTask.java:482)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData.getRuneInfo(GetStaticData.java:36)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.RunesActivity$GetRunes.onPostExecute(RunesActivity.java:150)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.RunesActivity$GetRunes.onPostExecute(RunesActivity.java:46)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 19:00:30.237      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4745)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ Caused by: java.lang.NullPointerException
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.content.ContextWrapper.openFileInput(ContextWrapper.java:159)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData$GetRunes.doInBackground(GetStaticData.java:165)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData$GetRunes.doInBackground(GetStaticData.java:156)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-29 19:00:30.241      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ java.util.concurrent.ExecutionException: java.lang.NullPointerException
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:223)
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask.get(FutureTask.java:82)
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.get(AsyncTask.java:482)
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData.getRuneInfo(GetStaticData.java:36)
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.RunesActivity$GetRunes.onPostExecute(RunesActivity.java:150)
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.RunesActivity$GetRunes.onPostExecute(RunesActivity.java:46)
04-29 19:00:30.245      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4745)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ Caused by: java.lang.NullPointerException
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.content.ContextWrapper.openFileInput(ContextWrapper.java:159)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData$GetRunes.doInBackground(GetStaticData.java:165)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData$GetRunes.doInBackground(GetStaticData.java:156)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-29 19:00:30.249      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
04-29 19:00:30.253      890-890/edu.appdesign.leaguestats W/System.err﹕ java.util.concurrent.ExecutionException: java.lang.NullPointerException
04-29 19:00:30.253      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:223)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask.get(FutureTask.java:82)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.get(AsyncTask.java:482)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData.getRuneInfo(GetStaticData.java:36)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.RunesActivity$GetRunes.onPostExecute(RunesActivity.java:150)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.RunesActivity$GetRunes.onPostExecute(RunesActivity.java:46)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-29 19:00:30.257      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4745)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ Caused by: java.lang.NullPointerException
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.content.ContextWrapper.openFileInput(ContextWrapper.java:159)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData$GetRunes.doInBackground(GetStaticData.java:165)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at edu.appdesign.leaguestats.GetStaticData$GetRunes.doInBackground(GetStaticData.java:156)
04-29 19:00:30.261      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-29 19:00:30.265      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-29 19:00:30.265      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-29 19:00:30.265      890-890/edu.appdesign.leaguestats W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-29 19:00:30.265      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-29 19:00:30.265      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-29 19:00:30.265      890-890/edu.appdesign.leaguestats W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
04-29 19:00:34.009      995-995/edu.appdesign.leaguestats I/Process﹕ Sending signal. PID: 995 SIG: 9

GetStaticData.java:165:

FileInputStream fis = openFileInput("runesInfo.json");

GetStaticData:

public class GetStaticData {

    private static String api_key = "d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
    public static String region = MainActivity.region.toLowerCase();

    public String getRuneInfo(String runeId) {
        String name = null;
        try {
            name = new GetRunes()
                    .execute(runeId)
                    .get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return name;
    }

    public String getChampionName(String champId) {
        String name = null;
        try {
            name = new GetChampionName()
                    .execute(champId)
                    .get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return name;
    }

    public static Summary getSummary(String summId) throws JSONException {
        Summary summary = new Summary();
        try {
            summary = new GetSummary()
                    .execute(summId)
                    .get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return summary;
    }

    public static class GetChampionName extends AsyncTask<String, String, String> {

        public static String champName;

        protected String doInBackground(String[] champId) {
            String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/champion/" + champId[0] + "?api_key=" + api_key;
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = jsonParser.getJSONFromUrl(url);
            Log.i("JSON", "" + jsonObject);
            try {
                champName = jsonObject.getString("key");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return champName;
        }
    }

    public static class GetSummary extends AsyncTask<String, String, Summary> {

        protected Summary doInBackground(String[] summId) {
            String url = "https://prod.api.pvp.net/api/lol/" + MainActivity.region.toLowerCase() + "/v1.3/stats/by-summoner/" + summId[0] + "/summary?season=SEASON4&api_key=" + api_key;
            Log.i("Summary URL", url);
            String url2 = "https://prod.api.pvp.net/api/lol/" + MainActivity.region.toLowerCase() + "/v2.3/league/by-summoner/" + summId[0] + "/entry?api_key=" + api_key;
            JSONParser jsonParser = new JSONParser();
            JSONArrayParser jsonArrayParser = new JSONArrayParser();
            JSONObject jsonObject = jsonParser.getJSONFromUrl(url);
            JSONArray jsonArray = jsonArrayParser.getJSONFromUrl(url2);
            Summary summary = new Summary();
            Log.i("Stats JSON", "" + jsonObject);
            JSONArray array;
            JSONObject league;
            try {
                array = jsonObject.getJSONArray("playerStatSummaries");
                league = jsonArray.getJSONObject(0);
                JSONObject rankedStats = array.getJSONObject(4);
                JSONObject normalStats = array.getJSONObject(8);
                summary.rWins = rankedStats.getString("wins");
                summary.rLoss = rankedStats.getString("losses");
                summary.nWins = normalStats.getString("wins");
                summary.rTier = league.getString("tier");
                summary.rLeague = league.getString("leagueName");
                summary.rRank = league.getString("rank");
                summary.rLeaguePoints = league.getString("leaguePoints");
                Log.i("Ranked", "" + summary.rWins + " " + summary.rLoss);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return summary;
        }
    }

    public static class Summary {
        public String rWins;
        public String rLoss;
        public String nWins;
        public String rTier;
        public String rLeague;
        public String rRank;
        public String rLeaguePoints;

        public Summary() {
            super();
        }

        public Summary(String rWins, String rLoss, String nWins, String rTier, String rLeague, String rRank, String rLeaguePoints) {
            super();
            this.rWins = rWins;
            this.rLoss = rLoss;
            this.nWins = nWins;
            this.rTier = rTier;
            this.rLeague = rLeague;
            this.rRank = rRank;
            this.rLeaguePoints = rLeaguePoints;
        }
    }

    public class GetRunes extends AsyncTask<String, String, String> {


        protected String doInBackground(String[] runeId) {

            String readJson;
            String name = null;

            try {
                FileInputStream fis = openFileInput("runesInfo.json");
                InputStreamReader isr = new InputStreamReader(fis);

                fis.read(readJson.getBytes());
                JSONObject storedJson = new JSONObject(readJson);
                Log.d("Stored JSON", "" + storedJson);
                JSONObject idJson = storedJson.getJSONObject("data");
                JSONObject single = idJson.getJSONObject(runeId[0]);


                try {
                    name = single.getString("name");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return name;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

我们来看看openFileInput方法:

public FileInputStream openFileInput(String name)
        throws FileNotFoundException {
        return mBase.openFileInput(name);
}
抛出

NPE,因为mBasenull。什么是mBase的类型?

Context mBase;

我相信您的GetStaticData类不是从任何基于Context的类继承的。如果是这样,您应该自己提供Context的构造函数:

public GetStaticData(Context context) {
    mContext = context;
}

稍后您应使用此openFileInput

致电Context
mContext.openFileInput(...)

答案 1 :(得分:0)

public String loadJSONFromAsset() {
    String json = null;
    try {

        InputStream is = getAssets().open("file_name.json");

        int size = is.available();

        byte[] buffer = new byte[size];

        is.read(buffer);

        is.close();

        json = new String(buffer, "UTF-8");


    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;

}