0

I am using HTTPAsyncClient to send a post request to the server , and it is activated with a button press (named checkbox) the problem is now when I press the first time It skips going into the TextHttpResponseHandler() and so it doesn't send anything to the server , but on the second press It gets into the function normally and calls the server , also when I switch to another activity it does the same thing and skips going into the response handler.

EDIT: I was debugging the program and I realized it does not skip the part as much as for the first run , it does not call the server at all , and returns the server_response=null but on the second call it calls the server and everything goes right

Edit2: Looking further into my code with debugging , I realized that the real problem is that the AsyncHttpClient client = new AsyncHttpClient(); takes time to get initialized that's why the response doesn't come out at first because there was not actual server call sent , but on the second time the AsyncHttpClient client = new AsyncHttpClient(); is initialized and the connection established that is why it gives out a response and acts normally , the question is now how do I fix this to make it work seamlessly

Here is the code :

public class RegisterFragment extends Fragment {
ProgressBar progressBar;
ImageView checkbutton;
EditText first_name_ET;
EditText last_name_ET;
EditText email_ET;
EditText password_ET;
EditText confirm_password_ET;
EditText phone_ET;
EditText username_ET;
String first_name;
String last_name;
String email;
String password;
String confirm_password;
String phone;
String username;
Pattern pattern;
Matcher matcher;
String URL = "http://198.58.109.238/engezni/public/android/register";
String USER_PREF = "User Pref";
String server_response = null;
String response_function_result = null;


public RegisterFragment() {
    // Required empty public constructor
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_register, container, false);
    progressBar = (ProgressBar) view.findViewById(R.id.progressbar);
    getView();
    progressBar.setVisibility(View.GONE);

    if (view != null) {
        first_name_ET = (EditText) view.findViewById(R.id.first_name_ET);
        last_name_ET = (EditText) view.findViewById(R.id.last_name_ET);
        email_ET = (EditText) view.findViewById(R.id.email_ET);
        password_ET = (EditText) view.findViewById(R.id.password_ET);
        confirm_password_ET = (EditText) view.findViewById(R.id.confirm_password_ET);
        phone_ET = (EditText) view.findViewById(R.id.phone_ET);
        username_ET = (EditText) view.findViewById(R.id.username_ET);
        checkbutton = (ImageView) view.findViewById(R.id.check_button);

    }

    first_name = first_name_ET.getText().toString().trim();
    last_name = last_name_ET.getText().toString().trim();
    email = email_ET.getText().toString().trim();
    password = password_ET.getText().toString().trim();
    confirm_password = confirm_password_ET.getText().toString().trim();
    phone = phone_ET.getText().toString().trim();
    username = username_ET.getText().toString().trim();


    checkbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Validate()) {
                response_function_result = null;
                response_function_result = SendToServer(first_name, last_name, email, password, phone, username);

                if (response_function_result != null) {

                    if (ServerErrorHandler(response_function_result)) {
                /*Saving the fields in shared prefs and going to another activity*/
                        SharedPreferences.Editor save = getActivity().getSharedPreferences(USER_PREF, 0).edit();
                        save.putString("User Name", first_name + " " + last_name);
                        save.putString("Email", email);
                        save.putString("Password", password);
                        save.putString("Phone", phone);
                        save.putString("Name", username);
                        save.commit();

                        Intent intent = new Intent(getActivity(), SignInScreen.class);
                        startActivity(intent);

                    }

                }
            }
        }
    });


    return view;
}

public boolean Validate() {
    first_name = first_name_ET.getText().toString().trim();
    last_name = last_name_ET.getText().toString().trim();
    email = email_ET.getText().toString().trim();
    password = password_ET.getText().toString().trim();
    confirm_password = confirm_password_ET.getText().toString().trim();
    phone = phone_ET.getText().toString().trim();
    username = username_ET.getText().toString().trim();
    final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);

    if (first_name.length() < 4 || first_name.length() > 30) {
        first_name_ET.setError("First name should be 4 chartacters or more");
        return false;
    } else {
        first_name_ET.setError(null);
    }

    if (last_name.length() < 4 || last_name.length() > 30) {
        last_name_ET.setError("First name should be 4 chartacters or more");
        return false;
    } else {
        last_name_ET.setError(null);
    }

    if (!matcher.matches()) {
        email_ET.setError("Invalid Email ex:example@domain.com");
        return false;
    } else {
        email_ET.setError(null);
    }
    if (password.length() < 6) {
        password_ET.setError("Password has to be 6 characters or more");
        return false;
    } else {
        password_ET.setError(null);
    }

    if (!confirm_password.equals(password)) {
        confirm_password_ET.setError("Password does not match");
        return false;
    } else {
        confirm_password_ET.setError(null);
    }

    if (phone.length() < 11) {
        phone_ET.setError("Phone number invalid");
        return false;
    } else {
        phone_ET.setError(null);
    }


    return true;
}

public String SendToServer(String first_name, String last_name, String email, String password, String phone, String username) {
    AsyncHttpClient client = new AsyncHttpClient();
    StringEntity stringEntity = null;
    JsonArray jsonArray = new JsonArray();
    JsonObject jsonObject = new JsonObject();

    try {
        jsonObject.addProperty("username", first_name + last_name);
        jsonObject.addProperty("email", email);
        jsonObject.addProperty("password", password);
        jsonObject.addProperty("name", username);
        jsonObject.addProperty("phone", phone);
        jsonObject.addProperty("dop", "dummy DOP");
        jsonArray.add(jsonObject);
        stringEntity = new StringEntity(jsonArray.toString());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    client.post(getActivity().getApplicationContext(), URL, stringEntity, "application/json", new TextHttpResponseHandler() {
        @Override
        public void onStart() {
            super.onStart();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onFinish() {
            super.onFinish();
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
            Toast.makeText(getActivity(), "onfaaail", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onSuccess(int i, Header[] headers, String s) {

            server_response = s;
            SharedPreferences.Editor save = getActivity().getSharedPreferences(USER_PREF, 0).edit();
            save.putString("Server Response", server_response);
            save.commit();


        }
    });

    return server_response;

}

public boolean ServerErrorHandler(String response) {
    String error_message = "Error Message: ";

    // Checks for errors.
    if (response.contains("INVALID") || response.contains("EXISTS")) {
        // error occured.
        if (response.contains("EMAIL_INVALID")) {
            error_message = error_message + " Invalid Email";
        }
        if (response.contains("PASSWORD_INVALID")) {
            error_message = error_message + " Invalid Password";
        }
        if (response.contains("PHONE_INVALID")) {
            error_message = error_message + " Invalid Phone";
        }
        if (response.contains("NAME_INVALID")) {
            error_message = error_message + " Invalid Name";
        }
        if (response.contains("DOP_INVALID")) {
            error_message = error_message + " Invalid DoP";
        }
        if (response.contains("USERNAME_INVALID")) {
            error_message = error_message + " Invalid Username";
        }
        if (response.contains("USERNAME_EXIST")) {
            error_message = error_message + " Name Exists";
        }
        if (response.contains("EMAIL_EXIST")) {
            error_message = error_message + " Email Exists";
        }
        if (response.contains("PHONE_EXIST")) {
            error_message = error_message + " Phone Exists";
        }

        Toast.makeText(getActivity().getApplicationContext(), error_message, Toast.LENGTH_LONG).show();


        return false;
    } else {
    /*No error*/
        Toast.makeText(getActivity().getApplicationContext(), "Registered", Toast.LENGTH_LONG).show();
        return true;

    }
}
}
Karim Bibars
  • 75
  • 1
  • 9

1 Answers1

1

When you do this: response_function_result = SendToServer(first_name, last_name, email, password, phone, username);

An Asynchronous request is made to your validation server. This basically means that there's a background thread on which the whole request is made and your main thread does not wait for the results. So while the validation request is going on in the background, this line executes straightaway return server_response; which is null and hence it returns null.

Shivam Verma
  • 7,973
  • 3
  • 26
  • 34
  • Yeah I noticed this like 10 mins ago but the question is now , how could I fix this ?? is there a way to make it wait for the server to be ready for me ? – Karim Bibars Jun 28 '14 at 11:14
  • onSuccess method executes after the success of your request, so put everything that needs values from the response inside the onSuccess method. – Shivam Verma Jun 28 '14 at 11:21
  • I will try this in a second and mark this as solved if it works , which i guess it will – Karim Bibars Jun 28 '14 at 11:23