2015-11-03 41 views
1

我的應用程序中有一個按鈕,當我點擊它時,它聲明方法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); 
+0

爲什麼不把你的asynctask類放到'insertToDatabase'之外?然後在'insertToDatabase'裏面只需要調用'new SendPostReqAsyncTask()。execute(...);' – BNK

+0

你需要調用你的異步任務,在你的類完成後放這個行'new DownloadFilesTask()。execute(url1,url2 ,url3);' –

+0

@BNK您可以在您的評論中指定一個名爲insertintodatabase.java的新活動,然後從主活動中調用它? – Moudiz

回答

1

因爲OkHttp支持用異步,我想你也可以參考以下方式:

讓我們假設你有mHandler = new Handler(Looper.getMainLooper());onCreate

private void updateToDatabase() { 
     // POST request 
     OkHttpClient client = new OkHttpClient(); 
     RequestBody requestBody = new FormEncodingBuilder() 
       .add("key1", "value1") 
       .add("key2", "value2") 
       .build(); 
     Request request = new Request.Builder() 
       .url("http://...") 
       .post(requestBody) 
       .build(); 
     client.newCall(request).enqueue(new Callback() { 
      @Override 
      public void onFailure(final Request request, final IOException e) { 
       mHandler.post(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show(); 
        } 
       });           
      } 

      @Override 
      public void onResponse(Response response) throws IOException { 
       mHandler.post(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(mContext, response.body().string(), Toast.LENGTH_SHORT).show(); 
        } 
       });          
      } 
     }); 
    } 

如果你仍然想的AsyncTask使用,更新您的代碼如下所示:

public class MainActivity extends AppCompatActivity { 
    ... 
    public void SignUp(View view) 
    { 
     new SendPostReqAsyncTask().execute(); 
    } 

    ... 
    private 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 { 
       OkHttpClient client = new OkHttpClient(); 
       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(); 
     } 
    } 
} 
+0

那麼不需要使用異步任務呢? – Moudiz

+0

是的,但是,如果你想更新UI的視圖,如textView ...,那麼你必須使用處理程序作爲我的回答在你以前的問題:) – BNK

+0

好吧然後生病第一次完成這一個異步任務,然後生病試試你的方式,並檢查哪個更好 – Moudiz

1

某處你必須創建SendPostReqAsyncTask的對象,並調用execute方法傳遞參數...

// Example class 
class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
// some code 
} 

// Call the execute method of Async Task 
new DownloadFilesTask().execute(url1, url2, url3); 
1

//使用這樣的..

public class <Your Root class> extends Activity{ 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    // some code 

     private final OkHttpClient client = new OkHttpClient(); 
     public void SignUp(View view) 
     { 
      new SendPostReqAsyncTask().execute(); 
     } 
    } 
    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(); 

        } 

} 
+0

您應該將String參數傳遞到新的SendPostReqAsyncTask()。execute(); :) – BNK

+0

這是沒有必要的。我用了很多次。\ –

+0

嗯,那是因爲你不需要任何參數來處理asynctask類中的內容 – BNK