01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
public
class
JSONExample
extends
Activity {
private
static
final
String TAG =
"JSONExample"
;
private
static
final
boolean
D =
true
;
private
static
String mJsonData =
"[{\"name\":\"zhangsan\"},{\"name\":\"lisi\"},{\"name\":\"wangwu\"}]"
;
private
ArrayList<String> mList =
null
;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
mList =
new
ArrayList<String>();
try
{
parse(mJsonData, mList);
}
catch
(JSONException e) {
e.printStackTrace();
}
ListView lv =
new
ListView(
this
);
lv.setLayoutParams(
new
LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, mList));
lv.setAdapter(
new
MyAdapter(
this
, mList));
setContentView(lv);
}
/**
* 解析JSON数据
*
* @param content json数据
* @param list
* @throws JSONException
*/
private
void
parse(String content, ArrayList<String> list)
throws
JSONException {
if
(content ==
null
|| content.length() ==
0
)
return
;
if
(list ==
null
)
return
;
// 此处是解析数组型的json
JSONArray jsonArray =
new
JSONArray(content);
if
(jsonArray !=
null
) {
for
(
int
i =
0
; i < jsonArray.length(); i++) {
// 如果你的json数据不是数组,直接使用下面的方式
// JSONObject jsonObj = new JSONObject(content);
JSONObject jsonObj = jsonArray.optJSONObject(i);
if
(jsonObj ==
null
)
continue
;
String name = jsonObj.optString(
"name"
);
list.add(name);
}
}
}
class
MyAdapter
extends
BaseAdapter {
private
ArrayList<String> mList;
private
Context mContext;
private
LayoutInflater mInflater;
public
MyAdapter(Context context, ArrayList<String> list) {
mContext = context;
mList = list;
mInflater = LayoutInflater.from(context);
}
@Override
public
int
getCount() {
return
mList.size() ==
0
?
0
: mList.size();
}
@Override
public
Object getItem(
int
position) {
if
(mList ==
null
|| mList.size() ==
0
)
return
null
;
return
mList.get(position);
}
@Override
public
long
getItemId(
int
position) {
return
position;
}
@Override
public
View getView(
int
position, View convertView, ViewGroup parent) {
if
(convertView ==
null
)
convertView = mInflater.inflate(android.R.layout.simple_list_item_1,
null
);
String s = getItem(position).toString();
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
tv.setText(s);
return
convertView;
}
}
}
|
Json解析数据载入ListView中
最新推荐文章于 2018-04-16 16:44:51 发布