-2

嗨,我有RegisterActivity.java这样的:

    public class RegisterActivity  extends Activity{
        private static final String TAG = "PostFetcher";
        private static String URL = "http://api.example.com/";
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.register);

            final EditText inputFname = (EditText) findViewById(R.id.registerFname);
            final EditText inputLname = (EditText) findViewById(R.id.registerLname);
            final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
            Button btnRegister = (Button) findViewById(R.id.btnRegister);
            Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
            final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);

            // Register Button Click event
            btnRegister.setOnClickListener(new View.OnClickListener() {  
                Login login2;
                RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
                public void onClick(View view) {
                    String fname = inputFname.getText().toString();
                    String lname = inputLname.getText().toString();
                    String email = inputEmail.getText().toString();

                    // get selected radio button from radioGroup
                    int selectedId = radioSexGroup.getCheckedRadioButtonId();
                    RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
                    String gender = radioSexButton.getText().toString();
                    //System.out.println(fname);
                    //Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();

                    String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
                    System.out.println(registerURL);

                    if( email.length() == 0) {
                        loginErrorMsg.setText(R.string.empty);
                        //Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
                        return;
                    }else{

                        try {
                            //Create an HTTP client
                            DefaultHttpClient client = new DefaultHttpClient();
                            HttpPost post = new HttpPost(registerURL);

                            //Perform the request and check the status code
                            HttpResponse response = client.execute(post);
                            StatusLine statusLine = response.getStatusLine();
                            if(statusLine.getStatusCode() == 200) {
                                HttpEntity entity = response.getEntity();
                                InputStream content = entity.getContent();

                                try {
                                    //Read the server response and attempt to parse it as JSON
                                    Reader reader = new InputStreamReader(content);

                                    Gson gson = new Gson();
                                    this.login2 = gson.fromJson(reader, Login.class);
                                    //System.out.println(this.login2);
                                    //handlePostsList(posts);
                                } catch (Exception ex) {
                                    Log.e(TAG, "Failed to parse JSON due to: " + ex);
                                    failedLoading();
                                }
                            } else {
                                Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
                                failedLoading();
                            }
                        } catch(Exception ex) {
                            Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
                            failedLoading();
                        }

                        //To set register message
                        if(login2.getResult().equals("OK")){
                            loginErrorMsg.setText(login2.getMessage().toString());
                        }else if(login2.getResult().equals("KO")){
                            loginErrorMsg.setText(login2.getMessage().toString());
                        }
                    }

                }
            });


            // Link to Login
            btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        Intent i = new Intent(getApplicationContext(),LoginActivity.class);
                        startActivity(i);
                        finish();
                    }
            });

        }

        public void onRadioButtonClicked(View view) {
            // Is the button now checked?
            boolean checked = ((RadioButton) view).isChecked();

            // Check which radio button was clicked
            switch(view.getId()) {
                case R.id.male:
                    if (checked)
                        // Pirates are the best
                    break;
                case R.id.female:
                    if (checked)
                        // Ninjas rule
                    break;
            }
        }

        private void failedLoading() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
                }
            });
        }
}

但是我收到如下错误:Failed to send HTTP POST request due to: android.os.NetworkOnMainThreadException Android开发者论坛建议我使用它AsyncTask来解决这个问题。但我不知道如何改变这一点。有人可以帮我解决这个问题吗?我花了几个小时,但找不到任何解决方案。

4

3 回答 3

0

老实说,我认为您会通过一些努力来解决这个问题,但是您可以这样做:

public class RegisterActivity  extends Activity{
private static final String TAG = "PostFetcher";
private static String URL = "http://api.example.com/";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    final EditText inputFname = (EditText) findViewById(R.id.registerFname);
    final EditText inputLname = (EditText) findViewById(R.id.registerLname);
    final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
    Button btnRegister = (Button) findViewById(R.id.btnRegister);
    Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
    final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);

    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {  
        Login login2;
        RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
        public void onClick(View view) {
            String fname = inputFname.getText().toString();
            String lname = inputLname.getText().toString();
            String email = inputEmail.getText().toString();

            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
            String gender = radioSexButton.getText().toString();
            //System.out.println(fname);
            //Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();

            String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
            System.out.println(registerURL);

            if( email.length() == 0) {
                loginErrorMsg.setText(R.string.empty);
                //Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
                return;
            }else{
                new LoginTask.execute();
            }

        }
    });


    // Link to Login
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(i);
                finish();
            }
    });

}

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.male:
            if (checked)
                // Pirates are the best
            break;
        case R.id.female:
            if (checked)
                // Ninjas rule
            break;
    }
}

private void failedLoading() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
        }
    });

private class LoginTask extends
        AsyncTask<Void, Void, Void> {

            ProgressDialog progressDialog;

    // Before running code in separate thread
    @Override
    protected void onPreExecute() {
        // Create a new progress dialog.
        progressDialog = new ProgressDialog(context);
        // Set the progress dialog to display a horizontal bar .
        // progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // Set the dialog title to 'Loading...'.
        // progressDialog.setTitle("Loading...");
        // Set the dialog message to 'Loading application View, please
        // wait...'.
        progressDialog.setMessage("Loading...");
        // This dialog can't be canceled by pressing the back key.
        progressDialog.setCancelable(false);
        // This dialog isn't indeterminate.
        progressDialog.setIndeterminate(true);
        // The maximum number of progress items is 100.
        // progressDialog.setMax(100);
        // Set the current progress to zero.
        // progressDialog.setProgress(0);
        // Display the progress dialog.
        progressDialog.show();

    }

    // The code to be executed in a background thread.
    @Override
    protected VoiddoInBackground(Void... arg) {
        try {
                    //Create an HTTP client
                    DefaultHttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(registerURL);

                    //Perform the request and check the status code
                    HttpResponse response = client.execute(post);
                    StatusLine statusLine = response.getStatusLine();
                    if(statusLine.getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();
                        InputStream content = entity.getContent();

                        try {
                            //Read the server response and attempt to parse it as JSON
                            Reader reader = new InputStreamReader(content);

                            Gson gson = new Gson();
                            this.login2 = gson.fromJson(reader, Login.class);
                            //System.out.println(this.login2);
                            //handlePostsList(posts);
                        } catch (Exception ex) {
                            Log.e(TAG, "Failed to parse JSON due to: " + ex);
                            failedLoading();
                        }
                    } else {
                        Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
                        failedLoading();
                    }
                } catch(Exception ex) {
                    Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
                    failedLoading();
                }

    }


    // after executing the code in the thread
    @Override
    protected void onPostExecute() {
        // close the progress dialog
        progressDialog.dismiss();
                                   //To set register message
                if(login2.getResult().equals("OK")){
                    loginErrorMsg.setText(login2.getMessage().toString());
                }else if(login2.getResult().equals("KO")){
                    loginErrorMsg.setText(login2.getMessage().toString());
                }

    }
}

}
于 2013-09-29T16:21:15.033 回答
0

让您入门的最简单方法是创建一个匿名内部类并在您的onCreate:

// if email length != 0
new AsyncTask<Void, Void, Void> {
    protected void doInBackground() {
        //Create an HTTP client
        //Update login2
     }
}.execute();

但是,有很多细微差别,我强烈建议阅读所有这两个页面:http: //developer.android.com/reference/android/os/AsyncTask.htmlhttp://developer.android.com /guide/components/processes-and-threads.html

于 2013-09-29T16:15:41.193 回答
0

您想将所有网络/解析代码放入doInBackground(). AsyncTask使AsyncTask您的Activity. 获得结果后,您将希望将其返回onPostExecute()以执行任何操作UI,例如更新Views

通过创建AsyncTask一个内部类,您将可以访问 theActivity及其函数的成员变量。

这个答案AsyncTask将为您提供创建和调用它的良好起点。

通读 AsyncTask Docs以了解它所需的规则

查看这些链接并尝试一下。然后在遇到麻烦时发布一个更具体的问题(如果遇到困难,请务必包含相关代码和 logcat 错误)。

于 2013-09-29T16:16:38.487 回答