【发布时间】:2014-04-29 02:24:35
【问题描述】:
我在写入内存以及从那里访问它时遇到问题。我相信我写对了,但是在阅读它时,我在这段代码中得到了一个空指针异常:
fis = new FileInputStream(getFilesDir() + "/" + "runeInfo");
在我的代码的读取部分。我以前没有处理过将数据保存到本地文件,所以我真的不确定我可能做错了什么。如果有人能指出我正确的方向,我将不胜感激。
public class GetRunes extends AsyncTask<String, String, String> {
boolean runesCached = false;
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "runeInfo");
out = new BufferedWriter(fstream);
out.write(String.valueOf(jsonString.getBytes()));
out.close();
} catch (Exception e){}
Log.d("Cache", "Cache Complete");
runesCached = true;
}
String name = null;
try {
FileInputStream fis;
fis = new FileInputStream(getFilesDir() + "/" + "runeInfo");
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;
}
}
}
【问题讨论】:
-
你怎么知道你写得对?你在一个 try/catch 块中写了所有的东西,但是你在不处理它们的情况下丢弃了任何潜在的异常。
-
@panini 你是对的,我真的不确定。它没有抛出错误,我只是忽略了它。查看我的手机文件,我没有看到任何与我的文件名有关的内容。我的代码看起来适合写入内存吗?
-
所以你改变了 } catch (Exception e){} 来输出错误?它在 logcat 中显示了什么吗?
-
@nasch 是的,我已经改变了它,我在 fstream = new FileWriter(getFilesDir() + "/" + "runeInfo");渔获正在压制。
-
输出getFilesDir()看看是否正确。
标签: android