该应用程序运行,但一个特定的功能不会。 每当我尝试登录或注册帐户时,Gradle控制台都会说它跳过了框架并且运行太多。 我想要做的是接收用户信息并将其发送到数据库。这是存在问题的注册活动代码。如果我把JSON拿出来并且只是让新活动打开,那就可以了。
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
注册的Php代码:
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO data (username, email, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $username, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
注册请求代码:
private Map<String, String> params;
public RegisterRequest(String username, String email, String password, Response.Listener<String> listener){
/*
NExt line means we are going to pass some information into the register.php
*/
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
/*
This is how we pass in the information from the register to the thing, we are using a hashmap
*/
params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
}
/*
Volley needs to get the data so we do a get params
Which gives us this method
*/
@Override
public Map<String, String> getParams() {
return params;
}
}
有谁知道我怎么解决这个???我不知道如何在此输入Async任务,如果有人可以,请帮忙。无论如何在没有异步任务的情况下解决这个问题? 谢谢!
答案 0 :(得分:0)
您可能正在主线程上运行网络请求,这是Android Framework用于呈现UI的线程。您需要使用某种机制在另一个线程上执行网络任务。 AsyncTask
是最简单的实现方式,并且对您的方案有益,因为这是一项简单的任务。
扩展AsyncTask
并将您的请求参数传递给Map
:
public class RegisterTask extends AsyncTask<Map, Void, Boolean> {
@Override
protected Boolean doInBackground(Map... params) {
Map props = params[0]; // you can access your request params here
/*
Do your network request here, using HttpUrlConnection or
HttpClient. and return a result (boolean in this example),
which is passed to the onPostExecute method
*/
return false;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
// This method is run on the main thread, so you can
// update your UI after the request is completed.
}
}
您可以像这样执行此任务:
RegisterTask task = new RegisterTask();
task.execute(yourHashMapContainingData);
查看此官方Google文档以获取更多详细信息: Perform Network Operations on a Separate Thread