-2

Her is my code for registration using web service , everything is working fine but i dont know how to get json response status from the web service

Register.java

package com.example.limitscale.beautylog;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONException;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;

public class Register extends Activity {

private EditText editTextName;
private EditText editTextUsername;
private EditText editTextPassword;
private EditText editTextEmail;
private EditText editTextMobile;

private Button buttonRegister;

private static final String REGISTER_URL = "http://beauty.limitscale.com/webservices/register.php";


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

    editTextName = (EditText) findViewById(R.id.name);
    editTextUsername = (EditText) findViewById(R.id.username);
    editTextPassword = (EditText) findViewById(R.id.password);
    editTextEmail = (EditText) findViewById(R.id.email);
    editTextMobile = (EditText) findViewById(R.id.mobile);

    buttonRegister = (Button) findViewById(R.id.register);

    buttonRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {



            String name=editTextName.getText().toString();
            String uname=editTextUsername.getText().toString();
            String password=editTextPassword.getText().toString();
            String email=editTextEmail.getText().toString();
            String mobile=editTextMobile.getText().toString();

            if(Utility.isNotNull(name) && Utility.isNotNull(email) && Utility.isNotNull(password)
                    && Utility.isNotNull(mobile) && Utility.isNotNull(uname)){
                // When Email entered is Valid
                registerUser();
                Intent intentSignUP = new Intent(Register.this, MainActivity.class);
                startActivity(intentSignUP);

                }
            else {
                Toast.makeText(getApplicationContext(), "Please enter valid email", Toast.LENGTH_LONG).show();
            }
        }
    });
}




private void registerUser() {
    String name = editTextName.getText().toString().trim().toLowerCase();
    String username = editTextUsername.getText().toString().trim().toLowerCase();
    String password = editTextPassword.getText().toString().trim().toLowerCase();
    String email = editTextEmail.getText().toString().trim().toLowerCase();
    String mobile = editTextMobile.getText().toString().trim().toLowerCase();

    register(name,username,password,email,mobile);
}

private void register(String name, String username, String password, String email,String mobile) {
    class RegisterUser extends AsyncTask<String, Void, String>{
        ProgressDialog loading;
        RegisterUserClass ruc = new RegisterUserClass();


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(Register.this, "Please Wait",null, true, true);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(String... params) {

            HashMap<String, String> data = new HashMap<String,String>();
            data.put("name",params[0]);
            data.put("username",params[1]);
            data.put("password",params[2]);
            data.put("email",params[3]);
            data.put("mobile",params[4]);

            String result = ruc.sendPostRequest(REGISTER_URL,data);

            return  result;
        }
    }

    RegisterUser ru = new RegisterUser();
    ru.execute(name,username,password,email,mobile);
}}class RegisterUserClass {

public String sendPostRequest(String requestURL,
                              HashMap<String, String> postDataParams) {

    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();
        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            response = br.readLine();
        }
        else {
            response="Error Registering";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}}

Here when am clicking the registration button redirecting to next activity , even when am displaying user already exist text its getting into next step so i want to redirect to the next activity only when am getting json status as true

Sivakumar S
  • 129
  • 2
  • 3
  • 16

1 Answers1

3

It's because your code is structured as such:

registerUser();
 Intent intentSignUP = new Intent(Register.this, MainActivity.class);
 startActivity(intentSignUP);

This means that regardless the result, your user will still be redirected to the MainActivity.

Instead, the redirection should be done in onPostExecute() if the JSON status is true. Otherwise don't redirect and toast an error message. So try updating your code as follow.

if(Utility.isNotNull(name) && Utility.isNotNull(email) && Utility.isNotNull(password)
                    && Utility.isNotNull(mobile) && Utility.isNotNull(uname)){
                // When Email entered is Valid
                registerUser();
                }

And in your onPostExecute(),

@Override
          protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                //do your JSON status checking here.
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
            }
Zhi Kai
  • 1,549
  • 1
  • 13
  • 31
  • Thank you kai , can you tell me how to check json status here – Sivakumar S Feb 15 '16 at 09:01
  • What does your result returns for the following line? String result = ruc.sendPostRequest(REGISTER_URL,data); And if you are wanting to get a JSON object from your POST request, use JSONObject myObject = new JSONObject(result); – Zhi Kai Feb 15 '16 at 09:19