0

仍然无法通过连接到数据库来运行我的登录应用程序。我应用了 asynctask,但仍然没有运气。请检查一下。提前致谢。首先,当我单击运行按钮时,我会收到此错误。你能帮我检查一下代码并告诉我什么是错的吗?提前致谢。

            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.etSubmit);
                    //Now to set an onClickListener
                    bLogin.setOnClickListener((android.view.View.OnClickListener) 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;
                    }
                }



                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            }
4

3 回答 3

1

您正试图在 doInBackGround 中执行 UI 操作,正如@codeMagic 指出的那样,他说的是对的,但他指出了一些不同的东西。

问题是您Toast在 doInBackground 中显示消息。

IE

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

并在 Catch

 Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
 Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();

由于 doInBackground 在非 UI 线程上工作,您不能在其中执行 UI 操作..

因此,当您尝试获取基本上下文时,它将为您返回 null 并导致 NullPointerException。

要在 doInBackground 中删除这些Toast消息并在 onPostExcecute 上显示它们,因为 onPostExecute 在 UI 线程上运行。

于 2013-03-26T20:02:30.547 回答
0

正如@Pragnani 所说,Toast 可以在onPostExecute()方法中使用。但是,如果您希望它本身在那里使用,您可能会使用它runOnUiThread来显示 Toast 消息。

于 2013-03-26T21:06:54.083 回答
0

当您单击时,您没有引用任何按钮。

  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.bLogin:
        new MyAsyncTask().execute();
        break;
    default:
        break;
    }}
于 2013-03-26T19:48:55.733 回答