-2

Hi I've the RegisterActivity.java like this:

    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();
                }
            });
        }
}

But I'm getting error as follows: Failed to send HTTP POST request due to: android.os.NetworkOnMainThreadException Android developers forum suggest me to implement it using AsyncTask to solve this problem. But I don't know how to change this. Can someone help me to solve this issue? I spent several hours, but couldn't find any solution.

Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
Kabe
  • 223
  • 2
  • 4
  • 16

3 Answers3

0

The simplest approach to get you started is to create an anonymous inner class and execute it in your onCreate:

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

There are, however, a lot of subtle nuances and I highly recommend reading all of these 2 pages: http://developer.android.com/reference/android/os/AsyncTask.html and http://developer.android.com/guide/components/processes-and-threads.html

Abdullah Jibaly
  • 53,220
  • 42
  • 124
  • 197
0

You want to put all of your network/parsing code in doInBackground() of your AsyncTask. Make the AsyncTask an inner class of your Activity. After getting your result you will want to return this to onPostExecute() to do any UI stuff such as updating Views.

By making the AsyncTask an inner class you will have access to member variables of the Activity and its functions.

This answer will give you a good starting point for creating your AsyncTask and calling it.

Read through the AsyncTask Docs to understand the rules it requires

Check out those links and give it a try. Then post a question with a more specific problem when you run into trouble (be sure to include relevant code and logcat errors if you get stuck).

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • Can you help me with this question please: http://stackoverflow.com/questions/19092708/error-parsing-json-to-java-object-com-google-gson-jsonsyntaxexception-expectin – Kabe Sep 30 '13 at 11:11
0

I honestly think you would figure it out with some effort, but here you go:

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());
                }

    }
}

}
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33