java - 创建线程会导致 Android 应用程序强制关闭

标签 java android

我正在尝试创建一个线程来处理按下登录按钮时执行的登录函数,以便我可以显示进度对话框。

   btnLogin.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Check Login


            ProgressDialog.show(Activity.this, "", "Loading...");
            new Thread(new Runnable(){
                public void run(){
                    try{
                        int duration;
                        Toast toast;
                        Context context;
                        String username = etUsername.getText().toString();
                        String password = etPassword.getText().toString();

                        JSONArray jsonArray=null;
                        password=ServerConnection.encryptPassword(password);
                        //Log.i("login hash",password);
                        jsonArray=ServerConnection.login(username, password);

                        if(jsonArray!=null) //login successful
                        {
                            context=getApplicationContext();
                            duration=Toast.LENGTH_SHORT;
                            toast=Toast.makeText(context, "Login Successful!", duration);
                            toast.show();//Shows the little pop up right at the bottom of the screen
                            Intent i = new Intent(getApplicationContext(), MapWithFriends.class);
                            startActivity(i);
                        }
                        else
                        {
                            context=getApplicationContext();
                            duration=Toast.LENGTH_SHORT;
                            toast=Toast.makeText(context, "Login Fail", duration);
                            toast.show();//Shows the little pop up right at the bottom of the screen
                            //lblResult.setText("Login failed. Username and/or password doesn't match.");
                        }
                    }catch(Exception e)
                    {
                        Log.e("tag", e.getMessage());
                    }
                    progressDialog.dismiss();
                }

            }).start();


        }
    });

但是,当创建线程时,它会强制关闭。如果我改回无线程,它就可以正常工作。

谢谢

编辑:
崩溃LogCat:
无法在未调用 Looper.prepare() 的线程内创建处理程序
致命异常:Thread-10
java.lang.NullPointerException
…… 你们还需要更多吗?

最佳答案

除了主线程之外,您不应该从任何线程修改UI,就像在:progressDialog.dismiss();

中所做的那样

考虑使用HandlerAsyncTask反而。我还建议阅读 this article .

关于java - 创建线程会导致 Android 应用程序强制关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249613/

相关文章:

Java Jlist 不更新

java - 如何在不知道 id 的情况下在 EditText 中设置文本?

android - Unity Android 的 StreamingAssets 文件夹位置

java - Spinner 中带有字符串数组的 NullPointerException

java - 如何在 Android 中发起 http get 请求

java - ByteArrayOutputStream.toByteArray() 还是从流中读取?

java - java中如何安全删除文件

java - Android的replaceAll和字符串比较与==

java - 为什么添加类路径导致找不到主类?

java - 如何使用带有Jersey的JAX-RS处理CORS