• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Android Register form not working but data goes into database

I am trying to implement an android register form which is not working as when users try to register the application just crashes and closes, however, users information does get inserted into the database.

My question is that why does it close down as the data does get inserted into the database successfully. Please advise and help.

Log cat error Message

Code:
  {"tag":"register","success":1,"error":0,"user":{"fname":"crisnfg","lname":"nawadv","email":"christina@gmail.com","uname":"crisitina","uid":"56e99196d80403.95127534","created_at":"2016-03-16 17:02:14"}}
    03-16 17:01:48.945 8482-11204/com.bradvisor.bradvisor E/Buffer Error: Error converting result org.json.JSONException: Value 2016-03-16 of type java.lang.String cannot be converted to JSONObject
    03-16 17:01:48.948 8482-8482/com.empier E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.empier, PID: 8482
                                                                           java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
                                                                               at com.empier.Register$ProcessRegister.onPostExecute(Register.java:209)
                                                                               at com.empier.Register$ProcessRegister.onPostExecute(Register.java:169)


    03-16 19:34:03.519 19048-19048/com.empier D/debug_tag: false
    03-16 19:34:10.110 19048-19048/com.empier D/debug_tag: false
    03-16 19:34:10.198 19048-19048/com.empier D/debug_tag: false
    03-16 19:35:42.417 19048-19048/com.empier D/debug_tag: false
    03-16 19:35:43.093 19048-19048/com.empier D/debug_tag: false
    03-16 19:37:07.778 19048-19048/com.empier D/debug_tag: false
    03-16 19:38:22.195 19048-19048/com.empier D/debug_tag: false
    03-16 19:40:23.161 19048-19048/com.empier D/debug_tag: false
    03-16 19:42:56.833 24951-24951/com.empier D/debug_tag: true
    03-16 19:58:16.518 29411-29411/? D/debug_tag: true
Register.Java Code



Code:
public class Register extends Activity {
 
 
        /**
         *  JSON Response node names.
         **/
 
 
        private static String KEY_SUCCESS = "success";
        private static String KEY_UID = "uid";
        private static String KEY_FIRSTNAME = "fname";
        private static String KEY_LASTNAME = "lname";
        private static String KEY_USERNAME = "uname";
        private static String KEY_EMAIL = "email";
        private static String KEY_CREATED_AT = "created_at";
        private static String KEY_ERROR = "error";
 
        /**
         * Defining layout items.
         **/
 
        EditText inputFirstName;
        EditText inputLastName;
        EditText inputUsername;
        EditText inputEmail;
        EditText inputPassword;
        ImageButton btnRegister;
        TextView registerErrorMsg;
 
 
        /**
         * Called when the activity is first created.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.register);
 
            /**
             * Defining all layout items
             **/
            inputFirstName = (EditText) findViewById(R.id.fname);
            inputLastName = (EditText) findViewById(R.id.lname);
            inputUsername = (EditText) findViewById(R.id.uname);
            inputEmail = (EditText) findViewById(R.id.email);
            inputPassword = (EditText) findViewById(R.id.pword);
            btnRegister = (ImageButton) findViewById(R.id.Registerbtn);
            registerErrorMsg = (TextView) findViewById(R.id.register_error);
 
            /**
             * Register Button click event.
             * A Toast is set to alert when the fields are empty.
             * Another toast is set to alert Username must be 5 characters.
             **/
 
            btnRegister.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
 
                    if (  ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
                    {
                        if ( inputUsername.getText().toString().length() > 4 ){
                            NetAsync(view);
 
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(),
                                    "Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(),
                                "One or more fields are empty", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        /**
         * Async Task to check whether internet connection is working
         **/
 
        private class NetCheck extends AsyncTask<String,String,Boolean>
        {
            private ProgressDialog nDialog;
 
            @Override
            protected void onPreExecute(){
                super.onPreExecute();
                nDialog = new ProgressDialog(Register.this);
                nDialog.setMessage("Loading..");
                nDialog.setTitle("Checking Network");
                nDialog.setIndeterminate(false);
                nDialog.setCancelable(true);
                nDialog.show();
            }
 
            @Override
            protected Boolean doInBackground(String... args){
 
 
    /**
     * Gets current device state and checks for working internet connection by trying Google.
     **/
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnected()) {
                    try {
                        URL url = new URL("http://www.google.com");
                        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                        urlc.setConnectTimeout(3000);
                        urlc.connect();
                        if (urlc.getResponseCode() == 200) {
                            return true;
                        }
                    } catch (MalformedURLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                return false;
 
            }
            @Override
            protected void onPostExecute(Boolean th){
 
                if(th == true){
                    nDialog.dismiss();
                    new ProcessRegister().execute();
                }
                else{
                    nDialog.dismiss();
                    registerErrorMsg.setText("Error in Network Connection");
                }
            }
        }
 
 
        private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
 
            /**
             * Defining Process dialog
             **/
            private ProgressDialog pDialog;
 
            String email,password,fname,lname,uname;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                inputUsername = (EditText) findViewById(R.id.uname);
                inputPassword = (EditText) findViewById(R.id.pword);
                fname = inputFirstName.getText().toString();
                lname = inputLastName.getText().toString();
                email = inputEmail.getText().toString();
                uname= inputUsername.getText().toString();
                password = inputPassword.getText().toString();
                pDialog = new ProgressDialog(Register.this);
                pDialog.setTitle("Contacting Servers");
                pDialog.setMessage("Registering ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
 
            @Override
            protected JSONObject doInBackground(String... args) {
 
 
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
 
                return json;
 
 
            }
            @Override
            protected void onPostExecute(JSONObject json) { Log.d("debug_tag", json == null ? "true" : "false");
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
 
                        registerErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
 
                        String red = json.getString(KEY_ERROR);
 
                        if(Integer.parseInt(res) == 1){
                            pDialog.setTitle("Getting Data");
                            pDialog.setMessage("Loading Info");
 
                            registerErrorMsg.setText("Successfully Registered");
 
 
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user"); Log.d("debug_tag", "User json :: " + json_user==null ? "true": "false");
 
                            /**
                             * Removes all the previous data in the SQlite database
                             **/
 
                            UserFunctions logout = new UserFunctions();
                            logout.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
                            /**
                             * Stores registered data in SQlite Database
                             * Launch Registered screen
                             **/
 
                            Intent registered = new Intent(getApplicationContext(), Registered.class);
 
                            /**
                             * Close all views before launching Registered screen
                             **/
                            registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            pDialog.dismiss();
                            startActivity(registered);
 
 
                            finish();
                        }
 
                        else if (Integer.parseInt(red) ==2){
                            pDialog.dismiss();
                            registerErrorMsg.setText("User already exists");
                        }
                        else if (Integer.parseInt(red) ==3){
                            pDialog.dismiss();
                            registerErrorMsg.setText("Invalid Email id");
                        }
 
                    }
 
 
                    else{
                        pDialog.dismiss();
 
                        registerErrorMsg.setText("Error occurred in registration");
                    }
 
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }}
        public void NetAsync(View view){
            new NetCheck().execute();
        }}

Userfunction.java code

[CODE]
   /**
         * Function to  Register
         **/
        public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
            // Building Parameters
            List params = new ArrayList();
            params.add(new BasicNameValuePair("tag", register_tag));
            params.add(new BasicNameValuePair("fname", fname));
            params.add(new BasicNameValuePair("lname", lname));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("uname", uname));
            params.add(new BasicNameValuePair("password", password));
            JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
            return json;
  
        }

Registered.java file

Code:
    public class Registered extends Activity {
  
  
  
        /**
         * Called when the activity is first created.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.registered);
  
  
            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
  
            HashMap<String,String> user = new HashMap<String, String>();
            user = db.getUserDetails();
  
            /**
             * Displays the registration details in Text view
             **/
  
            final TextView fname = (TextView)findViewById(R.id.fname);
            final TextView lname = (TextView)findViewById(R.id.lname);
            final TextView uname = (TextView)findViewById(R.id.uname);
            final TextView email = (TextView)findViewById(R.id.email);
            final TextView created_at = (TextView)findViewById(R.id.regat);
            fname.setText(user.get("fname"));
            lname.setText(user.get("lname"));
            uname.setText(user.get("uname"));
            email.setText(user.get("email"));
            created_at.setText(user.get("created_at"));
  
  
            ImageButton loginbtn = (ImageButton) findViewById(R.id.loginscreenbtn);
            loginbtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent myIntent = new Intent(view.getContext(), Login.class);
                    startActivityForResult(myIntent, 0);
                    finish();
                }
  
            });
  
        }}


Register.XML File


Code:
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        tools:context="bradvisor.bradvisor.com.bradvisor.LoginActivity"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:background="#ffffffff"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">
  
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:id="@+id/imageView5"
            android:layout_gravity="center_horizontal|top"
            android:src="@drawable/logofinal"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
  
        <ImageButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/Registerbtn"
            android:src="@drawable/registerbtn"
            android:background="#00000000"
            android:layout_below="@+id/pword"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="First Name"
            android:ems="10"
            android:id="@+id/fname"
            android:textColor="#ff3b5998"
            android:layout_below="@+id/imageView5"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:singleLine="false" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Last Name"
            android:ems="10"
            android:id="@+id/lname"
            android:layout_below="@+id/fname"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColor="#3b5998" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:id="@+id/uname"
            android:textSize="20dp"
            android:layout_below="@+id/lname"
            android:layout_alignParentLeft="true"
            android:text="Username"
            android:textColor="#3b5998"
            android:inputType="textPersonName" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:ems="10"
            android:id="@+id/email"
            android:layout_below="@+id/uname"
            android:layout_centerHorizontal="true"
            android:text="Email"
            android:textColor="#3b5998" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:ems="10"
            android:id="@+id/pword"
            android:layout_below="@+id/email"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:text="Password"
            android:textColor="#3b5998" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="56dp"
            android:textColor="#3b5998"
            android:id="@+id/register_error"
            android:layout_below="@+id/Registerbtn"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="30dp" />
    </RelativeLayout>

registered.xml

Code:
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        tools:context="bradvisor.bradvisor.com.bradvisor.LoginActivity"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:background="#ffffffff"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">
  
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:id="@+id/imageView5"
            android:layout_gravity="center_horizontal|top"
            android:src="@drawable/logofinal"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
  
        <ImageButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/Registerbtn"
            android:src="@drawable/registerbtn"
            android:background="#00000000"
            android:layout_below="@+id/pword"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="First Name"
            android:ems="10"
            android:id="@+id/fname"
            android:textColor="#ff3b5998"
            android:layout_below="@+id/imageView5"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:singleLine="false" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Last Name"
            android:ems="10"
            android:id="@+id/lname"
            android:layout_below="@+id/fname"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColor="#3b5998" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:id="@+id/uname"
            android:textSize="20dp"
            android:layout_below="@+id/lname"
            android:layout_alignParentLeft="true"
            android:text="Username"
            android:textColor="#3b5998"
            android:inputType="textPersonName" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:ems="10"
            android:id="@+id/email"
            android:layout_below="@+id/uname"
            android:layout_centerHorizontal="true"
            android:text="Email"
            android:textColor="#3b5998" />
  
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:ems="10"
            android:id="@+id/pword"
            android:layout_below="@+id/email"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:text="Password"
            android:textColor="#3b5998" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="56dp"
            android:textColor="#3b5998"
            android:id="@+id/register_error"
            android:layout_below="@+id/Registerbtn"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="30dp" />
    </RelativeLayout>

When I debug the application I do not get anything as everything works fine. please help and advise?.

The crash logs show that there is NullPointerException in onPostExecute() method. So either my json object which I am getting in onPostExecute() as a parameter is null or json_user in -

Code:
JSONObject json_user = json.getJSONObject("user");
is null. I have added two logs for these 2 objects and check for null to find out which of them are causing the issue. I am unsuccessful. Could you please help how I am able to find the error message and check where the null is coming from.
 
Last edited:
Your problem is definitely that json_user is null at some point.

I would set a breakpoint at this line

Code:
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);

and examine the returned json object, because for one of your param sets, you get a JSON data structure which does not contain element "user".
 
I have added the break point and debugged the application, however I can see that json is returning a new null value. Please see the below results.

Code:
this = {UserFunctions@831721419648}
jsonParser = {JSONParser@831721420368}
json = null
params = {ArrayList@831721420384}  size = 6
0 = {BasicNameValuePair@831721420544} "tag=register"
  value = {String@831721419456} "register"
  name = {String@831694602352} "tag"
1 = {BasicNameValuePair@831721420688} "fname=lawson"
  name = {String@831697794824} "fname"
  value = {String@831721366152} "lawson"
2 = {BasicNameValuePair@831721420712} "lname=Junior"
  name = {String@831697794888} "lname"
  value = {String@831721366248} "Junior"
3 = {BasicNameValuePair@831721420736} "email=lawson123@ymaill.com"
  name = {String@831697795120} "email"
  value = {String@831721366368} "lawson123@ymaill.com"
4 = {BasicNameValuePair@831721420760} "uname=junior_l"
  name = {String@831697795056} "uname"
  value = {String@831721366488} "junior_l"
5 = {BasicNameValuePair@831721420784} "password=Lampard8"
  name = {String@831694110784} "password"
  value = {String@831721366584} "Lampard8"

jsonParser = {JSONParser@831721420368}
registerURL= {String@831721419264} "http://192.168.85.1/bradvisor_login_api/"
Please advise or help, what shall I do next.
 
Last edited:
Ok so you have established that the server is returning null for this set of input params. Can you determine why that happened? Are you able to debug the server? Presumably it's inserting this data into a database and returning the result back to you. Is there some problem with the database insertion?
 
No, the data does get inserted into the database. How can I debug the server. I do not think that is a problem as login, change password and reset password are working all fine.
 
Last edited:
Let me amend the phpmyadmin.conf file to allow it access from all ipaddress to see if this will make a difference. I do not understand as the login, change and reset password works without giving any null values. I am using the same server address for register. Its weird.
 
I have checked it again and this time it is not returning null. Please advice?.
Code:
this = {UserFunctions@831721408496} 
 jsonParser = {JSONParser@831721409216} 

params = {ArrayList@831721409232}  size = 6
 0 = {BasicNameValuePair@831721409392} "tag=register"
  name = {String@831694577584} "tag"
  value = {String@831721408304} "register"
 1 = {BasicNameValuePair@831721409536} "fname=This"
  name = {String@831697796640} "fname"
  value = {String@831721349768} "This"
 2 = {BasicNameValuePair@831721409560} "lname=Monring"
  name = {String@831697796704} "lname"
  value = {String@831721349856} "Monring"
 3 = {BasicNameValuePair@831721409584} "email=thismorning@gmail.com"
  name = {String@831697796936} "email"
  value = {String@831721349984} "thismorning@gmail.com"
 4 = {BasicNameValuePair@831721409608} "uname=thismorning"
  name = {String@831697796872} "uname"
  value = {String@831721350120} "thismorning"
 5 = {BasicNameValuePair@831721409632} "password=Ruth1234"
  name = {String@831694135360} "password"
  value = {String@831721350224} "Ruth1234"
jsonParser = {JSONParser@831721409216}

registerURL= {String@831721409216} "http://192.168.85.1/bradvisor_login_api/"
 
Ok let's rewind a bit.
Your basic problem is that variable json_user is null:

Code:
JSONObject json_user = json.getJSONObject("user")

This did actually happen because the stack trace in your first post proves it.

From this we can say for sure that the JSON data structure returned from your web service did not contain the element "user"

To determine when this occurs, I suggest putting a breakpoint at this line of code

Code:
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);

Which will stop every time you get to that point. You can then look at the values of your parameters *and* the returned JSON data structure. This will tell you under what circumstances the web service returns the incomplete JSON data.

But as I said before, you will have to do some analysis of the server code to work out why incorrect data is being returned.

And it's no good simply sprinkling your code with Log statements. The best way to track this down is using breakpoints and looking at the variable values in the debugger.

I cannot give any clearer advice than this.
 
Actually, set the breakpoint here if you can

Code:
return json;

What you are wanting to do is look at the value of variable 'json' after the call to the web request returns. Ok?
 
After putting the break point in, I can now see that the value is returning null.

Code:
userFunction = {UserFunctions@831722144728} 
 jsonParser = {JSONParser@831722145448} 
 json= null
 lname = {String@831722145448} "jones"
 email = {String@831722145448} "vincejames@yahoo.com"
 uname = {String@831722145448} "JonesVince"
 password = {String@831722145448} "Lion123456"
 fname = {String@831722145448} "Vince"

Could you please advice what shall I can do to fix this issue so that json returns a value instead of null.
 
Maybe if you show details of what is on the server side of this
 
I have added my databasehandler.java file.

Code:
public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "bradvisor_login_api";

    // Login table name
    private static final String TABLE_LOGIN = "users";




    // Login Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_FIRSTNAME = "fname";
    private static final String KEY_LASTNAME = "lname";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_USERNAME = "uname";
    private static final String KEY_UID = "uid";
    private static final String KEY_CREATED_AT = "created_at";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_FIRSTNAME + " TEXT,"
                + KEY_LASTNAME + " TEXT,"
                + KEY_EMAIL + " TEXT UNIQUE,"
                + KEY_USERNAME + " TEXT,"
                + KEY_UID + " TEXT,"
                + KEY_CREATED_AT + " TEXT" + ")";
        db.execSQL(CREATE_LOGIN_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

        // Create tables again
        onCreate(db);
    }

    /**
     * Storing user details in database
     * */
    public void addUser(String fname, String lname, String email, String uname, String uid, String created_at) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_FIRSTNAME, fname); // FirstName
        values.put(KEY_LASTNAME, lname); // LastName
        values.put(KEY_EMAIL, email); // Email
        values.put(KEY_USERNAME, uname); // UserName
        values.put(KEY_UID, uid); // Email
        values.put(KEY_CREATED_AT, created_at); // Created At

        // Inserting Row
        db.insert(TABLE_LOGIN, null, values);
        db.close(); // Closing database connection
    }


    /**
     * Getting user data from database
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String,String> user = new HashMap<String,String>();
        String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if(cursor.getCount() > 0){
            user.put("fname", cursor.getString(1));
            user.put("lname", cursor.getString(2));
            user.put("email", cursor.getString(3));
            user.put("uname", cursor.getString(4));
            user.put("uid", cursor.getString(5));
            user.put("created_at", cursor.getString(6));
        }
        cursor.close();
        db.close();
        // return user
        return user;
    }






    /**
     * Getting user login status
     * return true if rows are there in table
     * */
    public int getRowCount() {
        String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int rowCount = cursor.getCount();
        db.close();
        cursor.close();

        // return row count
        return rowCount;
    }


    /**
     * Re crate database
     * Delete all tables and create them again
     * */
    public void resetTables(){
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_LOGIN, null, null);
        db.close();
    }

}

Index.php

Code:
<?php

/*
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 */

require_once 'mailer.php';

if (isset($_POST['tag']) && $_POST['tag'] != '')
{
    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
   
    // response Array
    $response = array("tag" => $_POST['tag'], "success" => 0, "error" => 0);

    // check for tag type
    switch($_POST['tag'])
    {
        case 'login':
            // Request type is check Login
            $email = $_POST['email'];
            $password = $_POST['password'];
     
            // check for user
            $user = $db->getUserByEmailAndPassword($email, $password);
            if ($user != false)
            {
                // user found
                // echo json with success = 1
                $response["success"] = 1;
                $response["user"]["fname"] = $user["firstname"];
                $response["user"]["lname"] = $user["lastname"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["uname"] = $user["username"];
                $response["user"]["uid"] = $user["unique_id"];
                $response["user"]["created_at"] = $user["created_at"];
            }
            else
            {
                // user not found
                // echo json with error = 1
                $response["error"] = 1;
                $response["error_msg"] = "Incorrect email or password!";
            }
        break;

        case 'chgpass':
            $email = $_POST['email'];
            $newpassword = $_POST['newpas'];

            $hash = $db->hashSSHA($newpassword);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];

            if ($db->isUserExisted($email))
            {
                $user = $db->forgotPassword($email, $encrypted_password, $salt);
                if ($user)
                {
                    $response["success"] = 1;

                    $subject = "Change Password Notification";
                    $message = "Hello $fname,\n\nYour Password is successfully changed.\n\nRegards,\nBradVisor Team.";
                    send_email($subject, $message, $email);
                }
                else
                {
                    $response["error"] = 1;
                }
                // user is already existed - error response
            } 
            else
            {
                $response["error"] = 2;
                $response["error_msg"] = "User not exist";
            }
        break;

        case 'forpass':
            $email = $_POST['forgotpassword'];
            $randomcode = $db->random_string();
     
            $hash = $db->hashSSHA($randomcode);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];

            if ($db->isUserExisted($email))
            {
                $user = $db->forgotPassword($email, $encrypted_password, $salt);
                if ($user)
                {
                    $response["success"] = 1;

                    $subject = "Password Recovery";
                    $message = "Hello $fname,\n\nYour Password is successfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nBradVisor Team.";
                    send_email($subject, $message, $email);
                }
                else
                {
                    $response["error"] = 1;
                }
                // user is already existed - error response
            } 
            else
            {
                $response["error"] = 2;
                $response["error_msg"] = "User not exist";
            } 
        break;

        case 'register':
            // Request type is Register new user
            $fname = $_POST['fname'];
            $lname = $_POST['lname'];
            $email = $_POST['email'];
            $uname = $_POST['uname'];
            $password = $_POST['password'];
     
            // check if user is already existed
            if ($db->isUserExisted($email))
            {
                // user is already existed - error response
                $response["error"] = 2;
                $response["error_msg"] = "User already existed";
            } 
            else if(!$db->validEmail($email))
            {
                $response["error"] = 3;
                $response["error_msg"] = "Invalid Email Id";          
            }
            else
            {
                // store user
                $user = $db->storeUser($fname, $lname, $email, $uname, $password);
                if ($user)
                {
                    // user stored successfully
                    $response["success"] = 1;
                    $response["user"]["fname"] = $user["firstname"];
                    $response["user"]["lname"] = $user["lastname"];
                    $response["user"]["email"] = $user["email"];
                    $response["user"]["uname"] = $user["username"];
                    $response["user"]["uid"] = $user["unique_id"];
                    $response["user"]["created_at"] = $user["created_at"];

                    $subject = "Registration";
                    $message = "Hello $fname,\n\nYou have successfully registered to our service.\n\nRegards,\nAdmin.";

                    $name = $user['firstname'] . ' ' . $user['lastname'];
                    send_email($subject, $message, $email, $name);
                }
                else
                {
                    // user failed to store
                    $response["error"] = 1;
                    $response["error_msg"] = "JSON Error occured in Registartion";
                }
            }
        break;

        default:
            $response["error"] = 3;
            $response["error_msg"] = "JSON ERROR";
    }

    echo json_encode($response);
}
else
{
    echo "BradVisor Login API";
}
?>

userfunction.php

Code:
/**
     * Adding new user to mysqli database
     * returns user details
     */

    public function storeUser($fname, $lname, $email, $uname, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysqli_query($this->db,"INSERT INTO `users`(`unique_id`, `firstname`, `lastname`, `username`, `email`, `encrypted_password`, `salt`, `created_at`) VALUES('$uuid', '$fname', '$lname', '$uname', '$email', '$encrypted_password', '$salt', NOW())") or die(mysqli_error($db)); 
                                         
  // check for successful store
        if ($result) {
            // get user details 
            $uid = mysqli_insert_id($this->db); // last inserted id
            $result = mysqli_query($this->db, "SELECT * FROM users WHERE uid = $uid") or die(mysqli_error($this->db));
            // return user details
            return mysqli_fetch_array($result);
        } else {
            return false;
        }
    }
 
In the code for getJSONFromUrl(), which you have not shown, I presume it's making a HTTP POST request to your server.

This code will have access to the response message. I can see that your server is putting error messages into the response at several places. You should examine the response to see what error was set. This will tell you why the null value was returned.
For example, this is one reason for failure

Code:
if ($db->isUserExisted($email))
            {
                // user is already existed - error response
                $response["error"] = 2;
                $response["error_msg"] = "User already existed";
            }

I suspect you have no error checking code at the moment.
 
how shall I add error checking code. if user is already registered then it says that user already exists.

Do you feel its php related issue from the server side instead of Android Studio side.
 
I was asking for you to show your getJSONfromUrl() method. You need to add error checking code to that method.
 
Back
Top Bottom