我正在创建一个应用程序,它使用本地json文件来显示一些信息。因此我解析了数据和显示数据的文本视图。但是我实际需要的是解析的数据必须显示在Listview
中。这个怎么做 ?如何从本地JSON文件解析JSON到Android中的ListView?
这是我的代码。
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsonshoutdata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjsonstring = sb.toString();
// Try to parse JSON
try {
urlist = new ArrayList<HashMap<String, String>>();
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("message");
// JSONArray has four JSONObject
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");
HashMap<String, String> map = new HashMap<String, String>();
map.put("msg", msg);
urlist.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是我customList适配器
CustomList adapter = new CustomList(MainActivity.this,urlist);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();
}
});
这是我的适配器类
public class CustomList extends ArrayAdapter<String>
{
public final ArrayList<HashMap<String, String>> urlist;
private Activity context;
public CustomList(Activity context,ArrayList<HashMap<String, String>> urlist)
{
super(context, R.layout.list_single);
this.context = context;
this.urlist=urlist;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText((CharSequence) urlist);
return rowView;
}
}
哪里...哪部分让你困惑......? –
问我..如果你什么都不明白.. –
请问你能按照正确的顺序编辑它吗? – Nevaeh