我使用json解析数据,
{
"userDetails": [
{
"id": "186",
"username": "manoj",
"status": "1"
},
{
"id": "189",
"username": "anu",
"status": "1"
},
{
"id": "190",
"username": "manojsoyal",
"status": "1"
},
{
"id": "191",
"username": "mohit",
"status": "1"
},
{
"id": "192",
"username": "micky",
"status": "1"
},
{
"id": "193",
"username": "preet",
"status": "1"
},
{
"id": "194",
"username": "mohit",
"status": "1"
},
{
"id": "195",
"username": "mohit",
"status": "1"
},
{
"id": "196",
"username": "harold",
"status": "1"
},
{
"id": "197",
"username": "sukhi",
"status": "1"
},
{
"id": "198",
"username": "harold2",
"status": "1"
},
{
"id": "199",
"username": "sukhi",
"status": "1"
},
{
"id": "200",
"username": "neha",
"status": "1"
},
{
"id": "201",
"username": "jay",
"status": "1"
},
{
"id": "202",
"username": "qwe",
"status": "1"
}
]
}
这是我的代码
公共类MainActivity扩展了Activity {
final static String URL = "this is the url";
String appUsernames[] = null;
String appUserIDs[] = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL);
try {
JSONArray userDetails = json.getJSONArray("userDetails");
for (int i = 0; i < userDetails.length(); i++) {
JSONObject c = userDetails.getJSONObject(i);
String name = c.getString("username");
String id = c.getString("id");
appUsernames = new String[userDetails.length()];
appUserIDs = new String[userDetails.length()];
appUsernames[i] = name;
appUserIDs[i] = id;
Log.d("First", appUserIDs[i] + ": " + appUsernames[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < appUserIDs.length; i++) {
Log.d("Second", appUserIDs[i] + ": " + appUsernames[i]);
}
}
}
在我的第一个log.d上,字符串数组不为空。但是在第二个log.d中,除了字符串数组的最后一个索引外,它似乎为null。怎么了?请帮帮我。
答案 0 :(得分:0)
appUsernames = new String[userDetails.length()];
appUserIDs = new String[userDetails.length()];
将数组的创建移到for循环之外
try {
JSONArray userDetails = json.getJSONArray("userDetails");
appUsernames = new String[userDetails.length()];
appUserIDs = new String[userDetails.length()];
for (int i = 0; i < userDetails.length(); i++) {
JSONObject c = userDetails.getJSONObject(i);
String name = c.getString("username");
String id = c.getString("id");
appUsernames[i] = name;
appUserIDs[i] = id;
Log.d("First", appUserIDs[i] + ": " + appUsernames[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}