我嘗試使用本地主機中的排空庫將數據保存到mysql數據庫中。當我嘗試獲取json並向mysql添加一些數據時發生錯誤,應用程序不幸停止。示值誤差:Java.NullPointerException
在該行如何在android中使用volley庫將數據保存到mysql?
Controller.getInstance().addToReqQueue(request);
這裏是我的代碼:
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, age;
Button insert, show;
TextView result;
String insertUrl = "http://192.168.56.1/android_post_api/insertStudent.php";
String showUrl = "http://192.168.56.1/android_post_api/show.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstname = (EditText) findViewById(R.id.editText);
lastname = (EditText) findViewById(R.id.editText2);
age = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
show = (Button) findViewById(R.id.showstudents);
result = (TextView) findViewById(R.id.textView);
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("ww");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
JSONArray students = response.getJSONArray("students");
for (int i = 0; i < students.length(); i++) {
JSONObject student = students.getJSONObject(i);
String firstname = student.getString("firstname");
String lastname = student.getString("lastname");
String age = student.getString("age");
result.append(firstname + " " + lastname + " " + age + " \n");
}
result.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
Controller.getInstance().addToReqQueue(jsonObjectRequest);
}
});
insert.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("firstname",firstname.getText().toString());
parameters.put("lastname",lastname.getText().toString());
parameters.put("age",age.getText().toString());
return parameters;
}
};
Controller.getInstance().addToReqQueue(request);
}
});
}
}
這將有助於張貼堆棧跟蹤... –