我试图在我的 Volley 请求中设置一个参数,但我没有从我的输入字段(在对话框中)正确获取和设置参数 - 导致空指针。服务器端确认该参数为空。这是我的 listDialog 方法:
public void listDialog() {
// get layout for prompt
LayoutInflater layoutInflater = LayoutInflater.from(this);
View promptView = layoutInflater.inflate(R.layout.list_name_prompt, null);
final EditText input = (EditText) promptView.findViewById(R.id.userInput);
listName = (input.getText().toString());
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
//set promptview to be the layout file for alerdialog builder
alertDialogBuilder.setView(promptView);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText listNameBox = (EditText) findViewById(R.id.userInput);
listName = listNameBox.getText().toString();
createListRequest();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();
}
我在 Activity 顶部设置了 listName
:
private String listName;
在 createListRequest
方法中,我使用参数,如下所示:
公共(public)无效createListRequest(){
JsonObjectRequest createRequest = new JsonObjectRequest(Request.Method.POST, createUrl, null,
new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
try {
//success
if (response.getBoolean("success")) {
Log.d("Response", response.toString());
}
} catch (Exception e) {
//not success
Log.d("Error.Response", e.toString());
}
}
},
new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
Log.d("Error.response", error.toString());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("auth_token", mPreferences.getString("AuthToken", "") );
return headers;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", listName);
return params;
}
};
AppController.getInstance().addToRequestQueue(createRequest);
}
我将是第一个承认我对 Java 变量和类字段的理解不够深入的人 - 这可能就是一个症状。
最佳答案
您的 listNameBox
为 null,因为您的对话框 View 是 promptView
并且 userInput
id 是 promptView
的一部分,所以改变一下
EditText listNameBox = (EditText) findViewById(R.id.userInput);
至
EditText listNameBox = (EditText)promptView.findViewById(R.id.userInput);
关于Java NullPointerException - 从文本框设置字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24646446/