2013-01-06 72 views
4

所有,例如何使HttpRequest的異步任務

我有一個小的功能應用程序,使一個HttpRequest基於由buttonclick發送用戶輸入的服務器。我正在尋找一些幫助,使我的小應用程序與SDK 11+兼容,通過使此httprequest成爲異步任務。

我已經花了一些時間閱讀關於異步任務的內容,並理解了使得httprequest遠離UI線程的原理和原因。

但是我不能讓代碼在我的情況下工作。我甚至無法編譯它。我已經包括在我的功能代碼下面(即嘗試使httprequest asyncronous之前)

我非常感謝一些特定的幫助。我爲我的垃圾代碼表示歉意,並且這個問題的變化已經得到了回答。

在此先感謝 傑米

我的MainActivity代碼如下:

package com.jrcdesign.ebookbeamer; 
import java.io.IOException; 
import org.apache.http.client.ClientProtocolException; 
import java.util.ArrayList; 
import java.util.List; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.message.BasicNameValuePair; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 
import android.widget.Spinner; 
import android.view.View.OnClickListener; 


public class MainActivity extends Activity { 

Button sendButton; 
Button btnSubmit; 
EditText msgTextField; 
EditText msg2TextField; 
Spinner spinner1; 

/** Called when the activity is first created. */ 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    // load the layout 
    setContentView(R.layout.main);   

    // make message text field object 
    msgTextField = (EditText) findViewById(R.id.msgTextField); 
    msg2TextField = (EditText) findViewById(R.id.msg2TextField); 

    // make send button object 
    sendButton = (Button) findViewById(R.id.sendButton); 
    btnSubmit = (Button) findViewById(R.id.btnSubmit);  
    addListenerOnButton(); 
    addListenerOnSpinnerItemSelection(); 

}    

    public void addListenerOnSpinnerItemSelection() { 
    spinner1 = (Spinner) findViewById(R.id.spinner1); 
    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener()); 
    } 

    // get the selected dropdown list value 
    public void addListenerOnButton() { 

    spinner1 = (Spinner) findViewById(R.id.spinner1); 
    btnSubmit = (Button) findViewById(R.id.btnSubmit); 

    btnSubmit.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 

     Toast.makeText(MainActivity.this, 
     "OnClickListener : " + 
        "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()), 
      Toast.LENGTH_SHORT).show(); 

     msgTextField.setText("" + String.valueOf(spinner1.getSelectedItem())); 

     } 

    }); 
    } 


    // Called when the SEND button is pressed 
    // Need to make this an async task 

    public void send(View v) 
{ 
    // get the message from the message text box 
    msgTextField.setText("" + String.valueOf(spinner1.getSelectedItem())); 
    String msg = msgTextField.getText().toString(); 
    String msg2 = msg2TextField.getText().toString(); 

    if (msg.length()>0) 
    { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://54.235.198.96/test1.php"); 
    try { 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("id", msg2)); 
     nameValuePairs.add(new BasicNameValuePair("message", msg)); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     httpclient.execute(httppost); 
     msgTextField.setText(""); // clear text box 
     msg2TextField.setText(""); // clear text box 

     Toast.makeText(MainActivity.this, 
       "Your request is being processed", 
        Toast.LENGTH_LONG).show(); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 

    } 
    else 
    { 
     // display message if text fields are empty 
     Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show(); 
    } 

} 

} 

回答

1

這裏是你的異步類:

private class AsyncTaskDownloadSomething extends 
     AsyncTask<String[], String, String> { 

    DataClassLentABook mData; 





    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     //Do some prepartations over here, before the task starts to execute 
     //Like freeze the button and/or show a progress bar 


    } 





    @Override 
    protected String doInBackground(String... urls) { 
     // Task starts executing. 
     String url = urls[0]; 

     // Execute HTTP requests here, with one url(urls[0]), 
     // or many urls using the urls table 
     // Save result in myresult 

     return myresult; 

    } 





    protected void onPostExecute(String result) { 
       //Do modifications you want after everything is finished 
       //Like re-enable the button, and/or hide a progressbar 
       //And of course do what you want with your result got from http-req 



    } 
} 

要執行你的異步任務,當用戶點擊您的按鈕,只寫這個:

new AsyncTaskDownloadSomething().execute(someURL); 
+1

謝謝,我非常感謝您的幫助。 – jamierc

+1

謝謝。我還沒有應用程序的工作 - 但我認爲你已經幫了我夠了。我需要擱置幾個晚上來調整我的代碼以實施您的建議。 – jamierc

+0

不客氣@jamierc!祝你好運! – Paschalis