【发布时间】:2014-05-08 05:58:01
【问题描述】:
我正在尝试检索我在 assets 中生成的 .json 文件以测试我的 ListView ,我在运行 try/catch 的应用程序时遇到了问题总是返回异常并且文件永远不会加载,ListView 返回 "No data" ,这是我的代码
请注意这个类扩展了 FragmentList
public View onCreateView( LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState )
{
View view = inflater.inflate(R.layout.frag1, container, false);
try {
obj = new JSONObject(loadJSONFromAsset("Questions.json"));
JSONArray m_jArry = obj.getJSONArray("Questions");
ArrayList<HashMap<String, String>> formList= new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++)
{
JSONObject jo_inside = m_jArry.getJSONObject(i);
String Created_At = jo_inside.getString("Created At");
String Asker_Name = jo_inside.getString("Asker_Name");
String Question_Title = jo_inside.getString("QuestionTitle");
String Question_Body = jo_inside.getString("QuestionBody");
String Question_Id = jo_inside.getString("Question_Id");
Question question = new Question(Asker_Name, Question_Title, Question_Body, Created_At);
questions.add(question);
//Add your values in your `ArrayList` as below:
m_li=new HashMap<String, String>();
m_li.put("Created At", Created_At );
m_li.put("Asker_Name", Asker_Name );
m_li.put("QuestionTitle", Question_Title);
m_li.put("QuestionBody", Question_Body );
m_li.put("Question_Id", Question_Id );
formList.add(m_li);
//Same way for other value...
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是loadJSONFromAsset的方法
public String loadJSONFromAsset(String path) {
String json = null;
try {
InputStream is = getActivity().getAssets().open(path);
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;
}
【问题讨论】:
标签: android json listview android-fragments android-assets