android - 如何使 httprequest 成为异步任务的示例

标签 android asynchronous httprequest

全部,

我有一个小型功能应用程序,它根据按钮点击发送的用户输入向服务器发出 http 请求。我正在寻求一些帮助,通过将此 httprequest 设为异步任务,使我的小型应用程序与 SDK 11+ 兼容。

我花了几天时间阅读有关异步任务的内容,并了解其原理以及将 httprequest 远离 UI 线程的原因。

但是我无法让代码在我的情况下工作。我什至无法编译它。我在下面包含了我的功能代码(即在尝试使 httprequest 异步之前)

如果能提供一些具体的帮助,我将不胜感激。我为我的垃圾代码道歉,这个问题的变体已经得到回答。

提前致谢 杰米

我的 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();
    }

}

}

最佳答案

这是您的异步​​类:

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);

关于android - 如何使 httprequest 成为异步任务的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187559/

相关文章:

java - 使用 http volley 发出 get 请求时响应为空

javascript - react-native-router-flux 不路由

php - Laravel 中的异步队列

python - Asyncio执行流程问题

javascript - 如何从异步调用返回响应?

java - 我们如何计算我网站的每个网页发出的 HTTP 请求

Silverlight WebClient 和 HTTP 状态代码

android - 未附加 ViewPager 和 Fragment

java - 回去 Activity

javascript - iOS 停止随机发送 httprequests[Titanium]