在Android中读取Json文件并在ListView中填充 [英] Read Json file in Android and Populate in ListView
本文介绍了在Android中读取Json文件并在ListView中填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了这段代码来读取json文件,并在listview中显示它,但返回空列表.如果有人建议我,我将不胜感激.谢谢
I write this piece of code for reading json file and show it in listview but it return empty list . I would appreciate if anybody advise me. Thanks
eventList.json:
eventList.json:
{
"events": [
{
"event": "Taste of day"
},
{
"event": "House Party at Park"
},
{
"event": "Farmers Markets"
},
{
"event": "Blues Festival Preview Events"
},
{
"event": "Cultural Alliance - Heritage and Fashion"
}
]
}
这是一个用于读取和解析json文件的活动:
and this an Activity for reading and parsing json file :
public class EventSelectActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_select);
// Reading json file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"eventList.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if ((br != null)) {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
JSONObject jsonObjMain = new JSONObject();
JSONArray jsonArray = jsonObjMain.getJSONArray("events");
ArrayList<String> messages = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
String message = jsonObj.getString("msg");
messages.add(message);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(EventSelectActivity.this,
android.R.layout.simple_list_item_1, messages);
ListView list=(ListView)findViewById(R.id.eventList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(EventSelectActivity.this, "TEST List View", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
推荐答案
变量sb
保存已使用的JSON数据.
The variable sb
holds the consumed JSON data.
没有引用实际的JSON对象,因为它是空的.
There was no reference to actual JSON object as it was empty.
JSONObject jsonObjMain = new JSONObject();
更改代码块:
try {
JSONObject jsonObjMain = new JSONObject(sb.toString());
JSONArray jsonArray = jsonObjMain.getJSONArray("events");
// ...
对JSON字段"msg"有未定义的引用,也许应该是事件"?
There is a undefined reference to the JSON field, "msg", maybe it should be "event"?
// Getting data from individual JSONObject
String message = jsonArray.getString(i);
messages.add(message);
这篇关于在Android中读取Json文件并在ListView中填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文