This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12个答案)
3年前关闭。
这是我的代码,我正在使用volley来调用Web服务
发生任何错误,获取
网址:
https://www.bgr.ionidea.com/math_lms/webservice/rest/server.php?wstoken=840e7d1cb52ca12239b01926310e0c68&wsfunction=local_math_get_android_version&moodlewsrestformat=json
ShowJson方法
解析JSON类
随着更多的用户,它看起来像:
要么
如果您无法更改JSON,则需要进行一些更改:
请勿在开始时使用JSONObject,而应立即从JSONArray开始,例如
就像@Ironman告诉您的那样,您需要将ID更改为int []而不是String [],并使用
(12个答案)
3年前关闭。
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
发生任何错误,获取
NullPointerException
网址:
https://www.bgr.ionidea.com/math_lms/webservice/rest/server.php?wstoken=840e7d1cb52ca12239b01926310e0c68&wsfunction=local_math_get_android_version&moodlewsrestformat=json
ShowJson方法
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.id,ParseJSON.app_version);
listView.setAdapter(cl);
}
解析JSON类
public class ParseJSON {
public static String[] id;
public static String[] app_version;
public static final String JSON_ARRAY = "result";
public static final String KEY_ID = "id";
public static final String KEY_APP_VERSION = "app_version";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
id = new String[users.length()];
app_version = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
id[i] = jo.getString(KEY_ID);
app_version[i] = jo.getString(KEY_APP_VERSION);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
最佳答案
我认为它与您的JSON有关。
您首先需要一个JSONObject。
在此JSONObject中,您需要一个名为result的JSONArray。
在此JSONArray中,您要求输入2个值:id和app_version。
所以我认为您的JSON需要看起来像这样:
{
"result": [
{"id": "1", "app_version": "1"}
]
}
随着更多的用户,它看起来像:
{
"result": [
{"id": "1", "app_version": "1"},
{"id": "2", "app_version": "1"},
{"id": "3", "app_version": "2"}
]
}
要么
如果您无法更改JSON,则需要进行一些更改:
请勿在开始时使用JSONObject,而应立即从JSONArray开始,例如
users = new JSONArray(json);
就像@Ironman告诉您的那样,您需要将ID更改为int []而不是String [],并使用
getInt()
而不是getString()
。