用于登录HttpPost Android的异步任务

时间:2012-11-04 22:01:12

标签: android login android-asynctask

我正在关注一个在Android中登录的youtube指南。到目前为止,我已经达到了这一点,我相信youtube指南依赖于早期的SDK来使其工作。对于ICS和更新版本,我已经读过我需要使用Async(我收到了NetworkOnMainThreadException)。我已经工作了2天试图找出如何实现这一点。

这会停留在装载终端,直到应用停止工作。是因为我在RunInBackground()中有太多内容吗?

如何让我的方法在适当的时间内工作。

我感谢任何人的帮助。顺便说一句,我已经阅读了很多文档来说明实现异步任务,但我的问题更多的是我将如何做到这一点?

**也是后端:app在wamp服务器上发送信息index.php然后php与数据库对话。

package com.sokies.my_team;

public class MainActivity extends Activity implements OnClickListener {

    EditText etUser, etPass;
    Button bLogin;

    //Create string variables that will have the input assigned to them
    String username, password;

    //Create a HTTPClient as the form container
    HttpClient httpclient;

    //Use HTTP POST method
    HttpPost httppost;

    //Create an array list for the input data to be sent
    ArrayList<NameValuePair> nameValuePairs;

    //Create a HTTP Response and HTTP Entity
    HttpResponse response;
    HttpEntity entity;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initialise();

    }



    private void initialise() {
        etUser = (EditText) findViewById(R.id.etUser);
        etPass = (EditText) findViewById(R.id.etPass);
        bLogin = (Button) findViewById(R.id.bSubmit);
        //Now to set an onClickListener
        bLogin.setOnClickListener(this);
    }

    public void onClick(View v)  {
        // This is where we will be working now

        new MyAsyncTask().execute();

    }//END onClick()

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }//END convertStreamToString()



    private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
        }

        @Override
        protected Void doInBackground(Void... params) {

            //Create new default HTTPClient
            httpclient = new DefaultHttpClient();

            //Create new HTTP POST with URL to php file as parameter
            httppost = new HttpPost("http://10.0.2.2/myteamapp/index.php"); 

            //Assign input text to strings
            username = etUser.getText().toString();
            password = etPass.getText().toString();



            //Next block of code needs to be surrounded by try/catch block for it to work
            try {
                //Create new Array List
                nameValuePairs = new ArrayList<NameValuePair>(2);

                //place them in an array list
                nameValuePairs.add(new BasicNameValuePair("user", "username"));
                nameValuePairs.add(new BasicNameValuePair("pass", "password"));

                //Add array list to http post
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                //assign executed form container to response
                response = httpclient.execute(httppost); //response from the PHP file

                //check status code, need to check status code 200
                if(response.getStatusLine().getStatusCode() == 200){

                    //assign response entity to http entity
                    entity = response.getEntity();

                    //check if entity is not null
                    if(entity != null){


                        //Create new input stream with received data assigned
                        InputStream instream = entity.getContent();

                        //Create new JSON Object. assign converted data as parameter.
                        JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                        //assign json responses to local strings
                        String retUser = jsonResponse.getString("user");//mySQL table field
                        String retPass = jsonResponse.getString("pass");

                        //Validate login
                        if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password 

                            //Display a Toast saying login was a success
                            Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();


                        } else {
                            //Display a Toast saying it failed.

                            Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                        }

                    }


                }


            } catch(Exception e){

               // e.printStackTrace();
                //Display toast when there is a connection error
                //Change message to something more friendly
               Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
               Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();

               return null;
            }



            return null;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您正在尝试从后台线程执行UI操作(在您的情况下它显示Toast),这在android中是被禁止的。尝试在doInBackground方法中返回一个值(f.e.,1表示成功,0表示失败),并在onPostExecute中处理,在UI线程上调用。

换句话说,总是在主线程上使用用户界面执行操作:尊重地运行后台任务之前和之后的onPreExecuteonPostExecute方法。