本文介绍了STIL不能与连接到数据库的运行我的登录应用程序。我申请的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还是老样子不能与连接到数据库的运行我的登录应用程序。我申请的AsyncTask,但仍没有运气。一些可以检查此,请。提前致谢。首先,我为我点击运行按钮,一旦得到这个错误。能否请您检查code代表我,告诉我是什么wronge。先谢谢了。

 公共类MainActivity扩展活动实现OnClickListener {                的EditText etUser,etPass;
                按钮bLogin;                //创建一个将输入分配给他们的字符串变量
                字符串的用户名,密码;                //创建了HTTPClient的形式容器
                HttpClient的HttpClient的;                //使用HTTP POST方法
                HttpPost httppost;                //创建一个数组列表为要发送的输入数据
                ArrayList的<&的NameValuePair GT; namevaluepairs中;                //创建一个HTTP响应和HTTP实体
                HTT presponse响应;
                HttpEntity实体;
                @覆盖
                公共无效的onCreate(捆绑savedInstanceState){                    super.onCreate(savedInstanceState);
                    的setContentView(R.layout.activity_main);                    初始化();                }                私人无效INITIALISE(){
                    etUser =(EditText上)findViewById(R.id.etUser);
                    etPass =(EditText上)findViewById(R.id.etPass);
                    bLogin =(按钮)findViewById(R.id.etSubmit);
                    //现在设置一个onClickListener
                    bLogin.setOnClickListener((android.view.View.OnClickListener)本);
                }                公共无效的onClick(视图v){
                    //这是我们将现在的工作                    新MyAsyncTask()执行();                } // END的onClick()                私人静态字符串convertStreamToString(InputStream为){
                    / *
                     *要InputStream中转换为字符串,我们使用使用BufferedReader.readLine()
                     *方法。我们重复,直到BufferedReader中返回NULL,这意味着
                     *没有更多的数据读取。每一行追加到一个StringBuilder
                     *和返回为String。
                     * /
                    读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是));
                    StringBuilder的SB =新的StringBuilder();                    串线= NULL;
                    尝试{
                        而((行= reader.readLine())!= NULL){
                            sb.append(行+\\ n);
                        }
                    }赶上(IOException异常五){
                        e.printStackTrace();
                    } {最后
                        尝试{
                            is.close();
                        }赶上(IOException异常五){
                            e.printStackTrace();
                        }
                    }
                    返回sb.toString();
                } // END convertStreamToString()                私有类MyAsyncTask扩展的AsyncTask<太虚,太虚,太虚>
            {
                    ProgressDialog mProgressDialog;
                    @覆盖
                    保护无效onPostExecute(虚空结果){
                        mProgressDialog.dismiss();
                    }                    @覆盖
                    在preExecute保护无效(){
                        mProgressDialog = ProgressDialog.show(MainActivity.this,载入中...,数据载入中......);
                    }                    @覆盖
                    保护无效doInBackground(虚空...... PARAMS){                        //创建新的默认了HTTPClient
                        HttpClient的=新DefaultHttpClient();                        //创建新的URL HTTP POST到PHP文件作为参数
                        httppost =新HttpPost(http://10.0.2.2/myteamapp/index.php);                        //指定输入文本为字符串
                        。用户名= etUser.getText()的toString();
                        。密码= etPass.getText()的toString();                        需要//下一步code块由try / catch块包围它的工作
                        尝试{
                            //创建新的数组列表
                            namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);                            //将它们放置在一个数组列表
                            nameValuePairs.add(新BasicNameValuePair(用户,用户名));
                            nameValuePairs.add(新BasicNameValuePair(通,密码));                            //添加数组列表以HTTP POST
                            httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                            //执行分配形式容器响应
                            响应= httpclient.execute(httppost); //从PHP文件响应                            //检查状态code,则需要检查状态code 200
                            如果(response.getStatusLine()的getStatus code()== 200){                                //指定响应实体到http实体
                                实体= response.getEntity();                                //检查,如果实体不为空
                                如果(实体!= NULL){
                                    //创建与分配接收到的数据新的输入流
                                    InputStream的河道= entity.getContent();                                    //创建新的JSON对象。分配转换的数据作为参数。
                                    JSONObject的jsonResponse =新的JSONObject(convertStreamToString(河道));                                    //分配JSON响应当地字符串
                                    字符串retUser = jsonResponse.getString(用户); // MySQL表领域
                                    字符串retPass = jsonResponse.getString(通行证);                                    //验证登录
                                    如果(username.equals(retUser)及和放大器; password.equals(retPass)){//检查retUser'和'retPass'是否匹配用户名/密码                                        //显示举杯说登录成功
                                        Toast.makeText(getBaseContext(),成功,Toast.LENGTH_SHORT).show();
                                    }其他{
                                        //显示举杯说它失败了。                                        Toast.makeText(getBaseContext(),无效的登录信息,Toast.LENGTH_SHORT).show();
                                    }                                }
                            }
                        }赶上(例外五){                           // e.printStackTrace();
                            //显示敬酒时,有一个连接错误
                            //改变消息的东西更友好
                           Toast.makeText(getBaseContext(),e.​​toString(),Toast.LENGTH_SHORT).show();
                           Toast.makeText(getBaseContext(),连接错误,Toast.LENGTH_SHORT).show();                           返回null;
                        }                        返回null;
                    }
                }                @覆盖
                公共无效的onClick(DialogInterface对话,诠释它){
                    // TODO自动生成方法存根                }
            }


解决方案

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

问题是你在你的doInBackground显示吐司消息。

  Toast.makeText(getBaseContext(),成功,Toast.LENGTH_SHORT).show();
 Toast.makeText(getBaseContext(),无效的登录信息,Toast.LENGTH_SHORT).show();

和在捕捞

  Toast.makeText(getBaseContext(),e.​​toString(),Toast.LENGTH_SHORT).show();
 Toast.makeText(getBaseContext(),连接错误,Toast.LENGTH_SHORT).show();

由于doInBackground适用于非UI线程,你不能在它执行UI操作。

所以,当你试图让基本上下文它将返回null为你而引起NullPointerException异常。

在doInBackground

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

stil not able to run my login app with connection to the database. I applied asynctask , but still no luck . can some check this please. Thanks in advance. First of all i get this error as soon as I click the run button. Can you please check the code for me and tell me what is wronge. thanks in advance.

            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

                }
            }
解决方案

You are trying to perform UI operation in doInBackGround as@codeMagic pointedout and what he said is right, but he pointed out something different.

problem is you are displaying Toast message in your doInBackground.

i.e

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

And in Catch

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

As doInBackground works on non UI thread, you can't perform UI operation in it..

So when you are trying to get base context it will return null for you and cause NullPointerException.

To remove those Toast messages in doInBackground and Display them onPostExcecute, as onPostExecute runs on UI thread.

这篇关于STIL不能与连接到数据库的运行我的登录应用程序。我申请的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 12:55