我的应用程序中有一个按钮,当我点击它时,它声明方法insertintodatabase
。但是,当我点击它时什么也没有发生,即使log
没有显示任何东西。 问题在哪里?请建议。点击按钮时异步方法没有运行
private final OkHttpClient client = new OkHttpClient();
public void SignUp(View view)
{
insertToDatabase();
}
private void insertToDatabase(){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute()
{
name = usernam.getText().toString();
pass = passw.getText().toString();
emails = email.getText().toString();
Log.e("GetText","called");
}
@Override
protected String doInBackground(String... params) {
String json = "";
try {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", name);
jsonObject.accumulate("password", pass);
jsonObject.accumulate("email", emails);
json = jsonObject.toString();
Log.e("MYAPP", "getjson");
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
}
try{
RequestBody formBody = new FormEncodingBuilder()
.add("result", json)
.build();
Request request = new Request.Builder()
.url("https://justedhak.comlu.com/receiver.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
} catch (IOException e){
Log.e("MYAPP", "unexpected JSON exception", e);
}
return "success";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
PHP
$username= $_POST['username'];
$password= $_POST['password'];
$email= $_POST['email'];
$image =$_POST['image'];
$sql = "insert into USERS (username,password,email) values ('$username','$password','$email')";
if(mysqli_query($con,$sql)){
echo 'success';
}
else{
echo 'failure';
}
mysqli_close($con);
为什么不把你的asynctask类放到'insertToDatabase'之外?然后在'insertToDatabase'里面只需要调用'new SendPostReqAsyncTask()。execute(...);' – BNK
你需要调用你的异步任务,在你的类完成后放这个行'new DownloadFilesTask()。execute(url1,url2 ,url3);' –
@BNK您可以在您的评论中指定一个名为insertintodatabase.java的新活动,然后从主活动中调用它? – Moudiz