使用AsyncTask执行方法时Android App崩溃

时间:2016-05-19 18:32:54

标签: java android multithreading android-studio android-asynctask

我的应用程序包含名为BackgroundWorker的类,它扩展了AsyncTask以处理与在线服务器的通信。 我试图从两个不同的类激活backgroundWorker类 - 一个来自我的MainActivity类,另一个来自Register类。 运行以下行时:

BackgroundWorker bgw = new BackgroundWorker(MainActivity.this);
bgw.execute(type , username , password);
来自MainActivity类的

- 一切都很好但是当试图从另一个类运行它们时,就像这样注册类:

 BackgroundWorker bgw = new BackgroundWorker(Register.this);
 bgw.execute(type ,name, surname, age, username , password);

该应用程序崩溃并显示以下弹出消息:

  

不幸的是,APPNAME已停止

我知道它是

  

bgw.execute()

导致这种情况的行,因为我调试了程序。

以下是我的2个类的完整代码:

MainActivity (执行方法完美运行):

public class MainActivity extends AppCompatActivity {

    EditText etUser;
    EditText etPass;
    Button btnLogin;
    Button btnRegister;
    TextView tvStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etUser = (EditText) findViewById(R.id.editText_username);
        etPass = (EditText) findViewById(R.id.editText_password);
        btnLogin = (Button) findViewById(R.id.button_login);

        btnRegister = (Button) findViewById(R.id.button_reg);

        onLoginClick();
        onRegisterClick();
    }

    public void onLoginClick() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUser.getText().toString();
                String password = etPass.getText().toString();
                String type = "login";
                BackgroundWorker bgw = new BackgroundWorker(MainActivity.this);
                bgw.execute(type , username , password);

            }
        });
    }
    public void onRegisterClick() {
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent openRegisterActivity = new Intent(MainActivity.this , Register.class);
                startActivity(openRegisterActivity);
            }
        });
    }
}

注册类(执行使应用程序崩溃的地方):

public class Register extends AppCompatActivity {

    Button btnSubmit;
    EditText etName;
    EditText etSurname;
    EditText etAge;
    EditText etUsername;
    EditText etPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        btnSubmit = (Button) findViewById(R.id.button_submit);
        etName = (EditText) findViewById(R.id.editText_name);
        etSurname = (EditText) findViewById(R.id.editText_surname);
        etAge = (EditText) findViewById(R.id.editText_age);
        etUsername = (EditText) findViewById(R.id.editText_username);
        etPassword = (EditText) findViewById(R.id.editText_password);


        onSubmit();
    }
    public void onSubmit() {
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = etName.getText().toString();
                String surname = etSurname.getText().toString();
                String age = etAge.getText().toString();
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                String type = "Register";

                BackgroundWorker bgw = new BackgroundWorker(Register.this);
                bgw.execute(type ,name, surname, age, username , password);
            }
        });
    }
}

我并不认为它与崩溃相关,但无论如何这里是我的 BackgroundWorker类(扩展了AsyncTask)代码:

public class BackgroundWorker extends AsyncTask <String , Integer , String> {
    Context context;
    AlertDialog alertDialog;
    public BackgroundWorker(Context userContext) {
        this.context = userContext;
    }

    @Override
    protected String doInBackground(String... params) {
        // STACK OVERFLOW SAY TO PUT THIS FOR DUBUG
        if(android.os.Debug.isDebuggerConnected())
            android.os.Debug.waitForDebugger();

        // Reading the arguments in the order I sent them in MainActivity
        String type = params[0];

        // Making structure for updating during the wat using Toasts (and showing the first one
        int progressValue = 0;          // Before if
        publishProgress(progressValue);
        // Initial String that will hold the text to read from server
        String result = "";
        // Initial the URL String
        String loginURL = "http://noche.netai.net/login.php";
        String registerURL = "http://noche.netai.net/register.php";
        if (type.equals("login")) {

            String username = params[1];
            String password = params[2];

            progressValue++;    //1
            publishProgress(progressValue);

            try {
                URL url = new URL(loginURL);

                progressValue++;    //2
                publishProgress(progressValue);

                // Building the HttpUrlConnection object
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                progressValue++;    //3
                publishProgress(progressValue);

                // Building the writing infrastructure
                // IOException occurs after the commit of the next line
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

                progressValue++;    //4
                publishProgress(progressValue);

                // Building the message to the PHP script
                String post_data = URLEncoder.encode("user_name" , "UTF-8") + "=" + URLEncoder.encode(username , "UTF-8")
                        + "&" + URLEncoder.encode("user_pass" , "UTF-8") + "=" + URLEncoder.encode(password , "UTF-8");

                progressValue++;    //5
                publishProgress(progressValue);

                // Writing the data
                bufferedWriter.write(post_data);

                progressValue++;    //6
                publishProgress(progressValue);

                // Closing all writing structures
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                // Building the Reading Infrastructure
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream , "iso-8859-1"));

                // Reading the data
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
                // Closing all reading structures
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();


            } catch (MalformedURLException e) {
                e.printStackTrace();
                progressValue = 10;
                publishProgress(progressValue);
            } catch (IOException e) {
                progressValue = 11;
                publishProgress(progressValue);
                e.printStackTrace();
            }
        }

        if (type.equals("register")) {

            String name = params[1];
            String surname = params[2];
            String age = params[3];
            String username = params[4];
            String password = params[5];

            progressValue++;    //1
            publishProgress(progressValue);

            try {
                URL url = new URL(registerURL);

                progressValue++;    //2
                publishProgress(progressValue);

                // Building the HttpUrlConnection object
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                progressValue++;    //3
                publishProgress(progressValue);

                // Building the writing infrastructure
                // IOException occurs after the commit of the next line
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

                progressValue++;    //4
                publishProgress(progressValue);

                // Building the message to the PHP script
                String post_data = URLEncoder.encode("name" , "UTF-8") + "=" + URLEncoder.encode(name , "UTF-8")
                        + "&" + URLEncoder.encode("surname" , "UTF-8") + "=" + URLEncoder.encode(surname , "UTF-8")
                        + "&" + URLEncoder.encode("age" , "UTF-8") + "=" + URLEncoder.encode(age , "UTF-8")
                        + "&" + URLEncoder.encode("username" , "UTF-8") + "=" + URLEncoder.encode(username , "UTF-8")
                        + "&" + URLEncoder.encode("password" , "UTF-8") + "=" + URLEncoder.encode(password , "UTF-8");

                progressValue++;    //5
                publishProgress(progressValue);

                // Writing the data
                bufferedWriter.write(post_data);

                progressValue++;    //6
                publishProgress(progressValue);

                // Closing all writing structures
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                // Building the Reading Infrastructure
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream , "iso-8859-1"));

                // Reading the data
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
                // Closing all reading structures
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();


            } catch (MalformedURLException e) {
                e.printStackTrace();
                progressValue = 10;
                publishProgress(progressValue);
            } catch (IOException e) {
                progressValue = 11;
                publishProgress(progressValue);
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // FOR CHECKING THE PROBLEM WITH CONNECTING TO THE WAMP SERVER
        /*
        int progressValue = values[0];
        // Before IF statement
        if (progressValue == 0) Toast.makeText(this.context , "Before if" , Toast.LENGTH_SHORT).show();
        // After IF statement
        if (progressValue == 1) Toast.makeText(this.context , "After if" , Toast.LENGTH_SHORT).show();
        // After URL statement
        if (progressValue == 2) Toast.makeText(this.context , "After URL Setting" , Toast.LENGTH_SHORT).show();
        // Before Writing data
        if (progressValue == 3) Toast.makeText(this.context , "After making HTML" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 4) Toast.makeText(this.context , "After making writing infra" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 5) Toast.makeText(this.context , "Before Writing data" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 6) Toast.makeText(this.context , "After Writing data" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 10) Toast.makeText(this.context , "First exception" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 11) Toast.makeText(this.context , "IO Exception" , Toast.LENGTH_SHORT).show();
        */
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        String subRes = result.substring(0,26); // To cut all the bulshit
        alertDialog.setMessage(subRes);
        alertDialog.show();
    }
}

编辑:这是Stack Trace(我想,我是Android开发的新手,所以不太确定堆栈跟踪应该在哪里):

  E/AndroidRuntime: FATAL EXCEPTION: main java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=26
                                                                                                       at java.lang.String.startEndAndLength(String.java:583)
                                                                                                       at java.lang.String.substring(String.java:1464)
                                                                                                       at com.example.nok_000.mysqlwithandroidproject.BackgroundWorker.onPostExecute(BackgroundWorker.java:246)
                                                                                                       at com.example.nok_000.mysqlwithandroidproject.BackgroundWorker.onPostExecute(BackgroundWorker.java:29)
                                                                                                       at android.os.AsyncTask.finish(AsyncTask.java:631)
                                                                                                       at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                                                                       at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
                                                                                                       at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                                       at android.os.Looper.loop(Looper.java:137)
                                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                                       at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                                                       at dalvik.system.NativeStart.main(Native Method)

谢谢你, 诺姆

2 个答案:

答案 0 :(得分:1)

问题解决了,崩溃是因为没有正确处理一些String问题(与AsyncTask无关)。

答案 1 :(得分:1)

    String subRes = result.substring(0,26); // To cut all the bulshit

此行包含问题,因为字符串result短于26个字符。检查那是什么,并更仔细地使用子字符串。

这就是你获得异常的原因,要么删除该行,要么更仔细地检查它(不要硬核 26,而是使用indexOf(something),其中something是标记你想要保留在字符串中的最后一件事的东西。)