【问题标题】:android AsyncTask creationandroid AsyncTask 创建
【发布时间】:2013-03-17 20:43:55
【问题描述】:

我正在尝试通过 http 发布请求发布一些数据,并了解整个过程。我在 android 开发者网站上红色文档,我看过一些 youtube 教程,但我仍然有一些我不熟悉的点。我找到了以下登录示例代码,但它不在 AsyncTask 中。我知道它必须是。但是,当我尝试使用 AsyncTask 执行此操作时,我的参数定义错误并且我被卡住了。如果我想将一些数据传递给 http 服务器上的 .php 脚本,任何人都可以帮助我并解释它是如何工作的吗?这是我的代码:(编辑后,这是我对 AsyncTask 的尝试):

 public class AndroidLogin extends Activity implements OnClickListener{

Button ok,back,exit;
TextView result;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_android_login);

 // Login button clicked
    ok = (Button)findViewById(R.id.btn_login);
    ok.setOnClickListener(this);

    result = (TextView)findViewById(R.id.lbl_result);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_android_login, menu);
    return true;
}

private class Login extends AsyncTask <String,String,String>{

    @Override
    protected String doInBackground(String... params) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();

        /* login.php returns true if username and password is equal to saranga */
        HttpPost httppost = new HttpPost("http://www.mysite.com/login.php");

        try {
            // Add user name and password
         EditText uname = (EditText)findViewById(R.id.txt_username);
         String username = uname.getText().toString();

         EditText pword = (EditText)findViewById(R.id.txt_password);
         String password = pword.getText().toString();

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            Log.w("SENCIDE", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);

            String str = inputStreamToString(response.getEntity().getContent()).toString();
            Log.w("SENCIDE", str);

            if(str.toString().equalsIgnoreCase("true"))
            {
             Log.w("SENCIDE", "TRUE");
             result.setText("Login successful");   
            }else
            {
             Log.w("SENCIDE", "FALSE");
             result.setText(str);             
            }

        } catch (ClientProtocolException e) {
         e.printStackTrace();
        } catch (IOException e) {
         e.printStackTrace();
        }

        StringBuilder inputStreamToString(InputStream is); 
            String line = "";
            StringBuilder total = new StringBuilder();
            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            // Read response until the end
            try {
             while ((line = rd.readLine()) != null) { 
               total.append(line); 
             }
            } catch (IOException e) {
             e.printStackTrace();
            }
            // Return full string
            return total;

        return null;
    }


}

public void onClick(View view) {

    new Login().execute();
}

}

【问题讨论】:

  • 您想知道代码的第二部分发生了什么,或者您想知道 AsyncTask 的工作原理?
  • 老实说这两件事。我想知道如何将它放入 AsyncTask 中,我也想知道第二部分代码发生了什么。 :)
  • “但是当我尝试使用 AsyncTask 执行此操作时,我的参数定义错误并且我被卡住了。” - 好的,所以发布你尝试使用 AsyncTask - 那你的问题是不是?
  • 我按照你的建议编辑了我的问题

标签: android android-asynctask httprequest


【解决方案1】:

首先方法签名protected String doInBackground(String... params)意味着params需要是一个String数组。

其次,永远不要在 AsyncTaskdoInBackground(...) 方法中执行类似以下操作...

 EditText uname = (EditText)findViewById(R.id.txt_username);
 String username = uname.getText().toString();

 EditText pword = (EditText)findViewById(R.id.txt_password);
 String password = pword.getText().toString();

...原因是doInBackground(...) 方法在与主(UI)线程不同的线程上运行,并且尝试访问诸如EditText 小部件之类的UI 元素将导致异常。相反,将这些代码行移至ActivityonClick(...) 方法。然后,您可以使用以下(例如)将凭据传递给 doInBackground(...) 方法...

new Login().execute(new String[] {username, password});

...那么在doInBackground(String... params) 方法中,params[0] 将是用户名,params[1] 将是密码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    相关资源
    最近更新 更多