7 Replies - 906 Views - Last Post: 19 January 2016 - 10:06 AM

#1 john_1993   User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 148
  • Joined: 16-March 15

gives error in registration, however data still goes into database

Posted 06 January 2016 - 05:23 AM

I have in the process of developing a registration app using Android Studios, however once users try to register the application just says error in registration and the CatLog does not give any error, as well as when debugging the app, I still get no errors.

Please can you help and tell me where I am going wrong as the code is correct as it was working couple of months ago, however since I have returned from holiday it just says "Error occurred in registration".

User data gets entered into the database however it does not allow the user to move ont to the next activity as it says "Error occurred in registration". Please can you help or advise?

LogCat

{"tag":"register","success":1,"error":0,"user":{"fname":"cherly","lname":"Cole","email":"[email protected]","uname":"cherlyc4","uid":"568c22e598ad32.87079168","created_at":"2016-01-05 20:09:09"}}
    01-05 20:08:19.603    4719-4768/com.bradvisor.bradvisor E/JSON Parser﹕ Error parsing data org.json.JSONException: Value 2016-01-05 of type java.lang.String cannot be converted to JSONObject
    01-05 20:08:19.625    4719-4732/com.bradvisor.bradvisor E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7d9800


Register.Java

 @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) {
            try {
                if (json != null && json.getString(KEY_SUCCESS) != null) {
                    if (json != null && 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");

                        /**
                         * 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

 //URL of the PHP API
       
        private static String registerURL = "http://10.0.2.2/Register_api/";
        
    private static String register_tag = "register";
       
    
    
        /**
             * 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;
            }

Jsonpasar.java

public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {
    
        }
    
        public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
                Log.e("JSON", json);
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }


DatabaseHandler.java

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 = "cloud_contacts";
    
        // Login table name
        private static final String TABLE_LOGIN = "login";
    
        // 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();
        }


Is This A Good Question/Topic? 0
  • +

Replies To: gives error in registration, however data still goes into database

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15438
  • View blog
  • Posts: 61,855
  • Joined: 12-June 08

Re: gives error in registration, however data still goes into database

Posted 06 January 2016 - 08:38 AM

You should be able to work back using some logic.

If you are getting this message:
72	                   registerErrorMsg.setText("Error occurred in registration");


then look at the 'if' condition associated.

I am tracking, what.. this line is your 'if' condition?
15	               if (json != null && json.getString(KEY_SUCCESS) != null) {


Start examining the values there.. don't assume, but stop the app, look at them, output them, etc.
Was This Post Helpful? 0
  • +
  • -

#3 john_1993   User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 148
  • Joined: 16-March 15

Re: gives error in registration, however data still goes into database

Posted 06 January 2016 - 02:32 PM

I e put breakpoint where suggested, however the debugger is taking the piss to load as it just been showing a blank screen for the last 2 hours.
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15438
  • View blog
  • Posts: 61,855
  • Joined: 12-June 08

Re: gives error in registration, however data still goes into database

Posted 06 January 2016 - 02:53 PM

What are you using for an IDE or debugger?
Was This Post Helpful? 0
  • +
  • -

#5 john_1993   User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 148
  • Joined: 16-March 15

Re: gives error in registration, however data still goes into database

Posted 06 January 2016 - 03:26 PM

Android Studios and the Emulator for debugger.
Was This Post Helpful? 0
  • +
  • -

#6 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15438
  • View blog
  • Posts: 61,855
  • Joined: 12-June 08

Re: gives error in registration, however data still goes into database

Posted 06 January 2016 - 03:28 PM

Mkay.. use an actual device, figure out how to speed up the debugging process, use a breakpoint to wait and hit, or dump out contents of variables around where you want to debug and make inferences on what is going on.
Was This Post Helpful? 0
  • +
  • -

#7 john_1993   User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 148
  • Joined: 16-March 15

Re: gives error in registration, however data still goes into database

Posted 07 January 2016 - 05:44 AM

I have debugged it and now it shows two error within the messages which says the following below and its a nullpointerexception error.


Error parsing data org.json.JSONException: Value 2016-01-07 of type java.lang.String cannot be converted to JSONObject
01-07 15:14:42.938 2161-2161/com.Oakland E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.Oakland, PID: 2161
                                                                       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.Oakland.Register$ProcessRegister.onPostExecute(Register.java:211)
                                                                           at com.Oakland.Register$ProcessRegister.onPostExecute(Register.java:171)



Register.Java File

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) {
            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");

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


Line 211-
if (json.getString(KEY_SUCCESS) != null) {




The data still gets inserted into the database, however the application crashes.

This post has been edited by john_1993: 07 January 2016 - 08:28 AM

Was This Post Helpful? 0
  • +
  • -

#8 john_1993   User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 148
  • Joined: 16-March 15

Re: gives error in registration, however data still goes into database

Posted 19 January 2016 - 10:05 AM

I have debugged this by adding break points and using the debugger in Android Studios, which shows that username field is not giving a value. could you please help me and how can I make username give a value rather than giving nothing.

Debugger results.

Firstname Value

 result = {[email protected]} "android.widget.EditText{5281dc2c VFED..CL ........ 48,498-1032,642 #7f0c00b9 app:id/fname}"
     mTransformed = {ReplacementTransformationMethod$[email protected]} "Sam"
      mSpanned = {[email protected]} "Sam"
     mTransformation = {[email protected]} 
     mText = {[email protected]} "Sam"


Surname Value


    result = {[email protected]} "android.widget.EditText{528168f4 VFED..CL ........ 48,642-1032,786 #7f0c00ba app:id/lname}"
         mTransformed = {ReplacementTransformationMethod$[email protected]} "Jones"
          mSpanned = {[email protected]} "Jones"
         mTransformation = {[email protected]} 
         mText = {[email protected]} "Jones"
Username Value.

Username value

 result = {[email protected]} "android.widget.EditText{5281e154 VFED..CL ........ 48,786-1032,906 #7f0c00bb app:id/uname}"
     mTransformed = {[email protected]} "joness"
     mTransformation = null
     mText = {[email protected]} "joness"


Email Value.

result = {[email protected]} "android.widget.EditText{52820b44 VFED..CL .F...... 48,906-1032,1050 #7f0c0084 app:id/email}"
     mTransformed = {ReplacementTransformationMethod$[email protected]} "[email protected]"
      mSpanned = {[email protected]} "[email protected]"
     mTransformation = {[email protected]} 
     mText = {[email protected]} "[email protected]"



Password Value



    result = {[email protected]} "android.widget.EditText{5281bf8c VFED..CL ........ 48,1050-1032,1194 #7f0c0085 app:id/pword}"
     mTransformed = {PasswordTransformationMethod$[email protected]} ""
     mTransformation = {[email protected]} 
     mText = {[email protected]} "Password"


mTransformation = null Is returning null for usernmae field however for the other fields it is returning a method and value. Please help?.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1