我已创建此代码以从我的数据库访问用户以进行登录。当我在OnResponse方法内部时,我可以访问对象'st'但是当我尝试返回返回对象时,它给我null。此外,当我在返回之前尝试访问此st对象时,它会给出NullPointerException。什么是确切的问题?
public class ServerRequests {
ProgressDialog progressDialog;
public static user_Student st;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://prem-pc:8989/";
Context ct;
public ServerRequests(Context context) {
ct = context;
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please Wait....");
}
public ServerRequests() {
}
public user_Student fetchUserDataInBackground(user_Student user) {
progressDialog.show();
Toast.makeText(ct, "Data in background: ", Toast.LENGTH_SHORT).show();
user_Student ust = doInBackground(user);
progressDialog.dismiss();
return ust;
}
public user_Student doInBackground(user_Student user) {
String URL = SERVER_ADDRESS + "connect.php?prn=" + user.prn + "&password=" + user.password;
RequestQueue req = Volley.newRequestQueue(ct);
Toast.makeText(ct, "Do in Background", Toast.LENGTH_SHORT).show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jObject) {
try {
// Parsing json object response
// response will be a json object
if (jObject.length() == 0) {
st = null;
Toast.makeText(ct, "Null JSON Object", Toast.LENGTH_SHORT).show();
} else {
String prn = jObject.getString("prn");
String fname = jObject.getString("fname");
String mname = jObject.getString("mname");
String lname = jObject.getString("lname");
String clas = jObject.getString("clas");
String dept = jObject.getString("dept");
String batch = jObject.getString("batch");
String scontact = jObject.getString("scontact");
String pcontact = jObject.getString("pcontact");
String email = jObject.getString("email");
String password = jObject.getString("password");
String dob = jObject.getString("dob");
st = new user_Student(prn, fname, mname, lname, clas, dept, batch, scontact, pcontact, email, password, dob);
Toast.makeText(ct, "JSON Object:" + st.fname, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ct, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ct, error.getMessage(), Toast.LENGTH_SHORT).show(); // hide the progress dialog
}
});
req.add(jsonObjReq);
//Toast.makeText(ct,"DO in back End"+st.fname,Toast.LENGTH_SHORT).show();
return st;
}
}
答案 0 :(得分:0)
您无法从匿名内部类返回,但您可以在ServerRequests
内创建一个方法,该方法将user_Student
作为参数并从onResponse
内调用该方法。这种方法可以随心所欲。
答案 1 :(得分:0)
你必须使用AsyncTask做功能doInBackground(user_Student用户)
您可以查看此帖子以了解AsyncTask: How to use AsyncTask correctly in Android