0

I have a login and registration page. After registration, datas are getting inserted properly in DB. When I use registered username and password for login, first time control goes into OnClick method but when I logout and login again(click on Login button), control does not goes into OnClick method...Please Help

Code is as follows:

DBHelper1.java

package com.example.app;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper1 extends SQLiteOpenHelper
{
    private SQLiteDatabase db1;

    public static final String KEY_ROWID = "id";
    public static final String KEY_GNAME = "givenname";
    public static final String KEY_FNAME = "firstname";
    public static final String KEY_MNAME = "middlename";
    public static final String KEY_ADDRESS1 = "address1";

    public static final String KEY_ADDRESS2 = "address2";
    public static final String KEY_CITYVILLAGE = "cityvillage";
    public static final String KEY_STATEPROVINCE = "stateprovince";
    public static final String KEY_COUNTRY= "country";

    public static final String KEY_POSTALCODE= "postalcode";
    public static final String KEY_AGE= "age";
    public static final String KEY_BIRTHDATE= "birthdate";
    public static final String KEY_GENDER= "gender";
    public static final String KEY_USERNAME= "username";
    public static final String KEY_PASS= "password";

    DBHelper1 DB1 = null;
    private static final String DATABASE_NAME = "db7";
    private static final int DATABASE_VERSION = 2;
    public static final String DATABASE_TABLE_NAME = "registration1";

    private static final String DATABASE_TABLE_CREATE = "CREATE TABLE "
            + DATABASE_TABLE_NAME
            + "("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "givenname TEXT NOT NULL, firstname TEXT NOT NULL, middlename TEXT NOT NULL,address1 TEXT NOT NULL, address2 TEXT NOT NULL, cityvillage TEXT NOT NULL,stateprovince TEXT NOT NULL, country TEXT NOT NULL,postalcode TEXT NOT NULL, age TEXT NOT NULL, birthdate TEXT NOT NULL, gender TEXT NOT NULL, username TEXT NOT NULL,password TEXT NOT NULL );";



    public DBHelper1(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        System.out.println("In constructor");
    }

    @Override
    public void onCreate(SQLiteDatabase db1) {

        try {
            System.out.println("CREATE TABLE--------->>>>>");
            db1.execSQL(DATABASE_TABLE_CREATE);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db1, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

    public Cursor rawQuery(String string, String[] strings) {
        // TODO Auto-generated method stub
        return null;
    }

    public void open() {

        getWritableDatabase();
    }

    /*public Cursor getDetails(String text) throws SQLException 
    {
        System.out.println("iN getDetails------>>" +text);
        Cursor mCursor = db1.query(true, DATABASE_TABLE_NAME, new String[] {
                KEY_ROWID, KEY_GNAME, KEY_FNAME, KEY_MNAME,KEY_ADDRESS1,KEY_ADDRESS2,KEY_CITYVILLAGE,KEY_STATEPROVINCE,
                KEY_COUNTRY,KEY_POSTALCODE,KEY_AGE,KEY_BIRTHDATE,KEY_GENDER,KEY_USERNAME}, KEY_USERNAME + "=" + text, null, null, null, null,
                null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }*/

}

Registration1.java

package com.example.app;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Registration1 extends Activity  implements OnClickListener,
OnItemSelectedListener{

    private Button mSubmit;
    private Button mCancel;
    private EditText mGname;
    private EditText mFname;
    private EditText mMname;
    private EditText mAddress1;
    private EditText mAddress2;
    private EditText mCityvillage;
    private EditText mStateprovince;
    private EditText mCountry;
    private EditText mPostalcode;
    private EditText mAge;
    private EditText mBirthdate;
    private Spinner mGender;
    private EditText mUsername;
    private EditText mpass;

    private String Gen;

    protected DBHelper1 DB1 = new DBHelper1(Registration1.this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration1);

        // Assignment of UI fields to the variables
        mSubmit = (Button) findViewById(R.id.submit);
        mSubmit.setOnClickListener(this);

        mCancel = (Button) findViewById(R.id.cancel);
        mCancel.setOnClickListener(this);

        mGname = (EditText) findViewById(R.id.egname);
        mFname = (EditText) findViewById(R.id.efname);
        mMname = (EditText) findViewById(R.id.eMname);
        mAddress1 = (EditText) findViewById(R.id.eaddress1);
        mAddress2 = (EditText) findViewById(R.id.eaddress2);
        mCityvillage = (EditText) findViewById(R.id.ecityvillage);
        mStateprovince = (EditText) findViewById(R.id.estateprovince);
        mCountry = (EditText) findViewById(R.id.ecountry);
        mPostalcode = (EditText) findViewById(R.id.epostalcode);
        mAge = (EditText) findViewById(R.id.eage);
        mBirthdate = (EditText) findViewById(R.id.ebirthdate);
        mGender = (Spinner) findViewById(R.id.spinner1);
        mUsername = (EditText) findViewById(R.id.eusername);
        mpass = (EditText) findViewById(R.id.epass);


        // Spinner method to read the on selected value
        ArrayAdapter<State> spinnerArrayAdapter = new ArrayAdapter<State>(this,
                android.R.layout.simple_spinner_item, new State[] {
                        new State("Male"), new State("Female") });
        mGender.setAdapter(spinnerArrayAdapter);
        mGender.setOnItemSelectedListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

        case R.id.cancel:
            Intent i = new Intent(getBaseContext(), MainActivity.class);
            startActivity(i);
            // finish();
            break;

        case R.id.submit:
            System.out.println("rEGISTER BUTTON CLICK");
            String gname = mGname.getText().toString();
            String fname = mFname.getText().toString();
            String mname = mMname.getText().toString();
            String address1 = mAddress1.getText().toString();

            String address2 = mAddress2.getText().toString();
            String cityvillage = mCityvillage.getText().toString();
            String stateprovince = mStateprovince.getText().toString();
            String country = mCountry.getText().toString();

            String postalcode = mPostalcode.getText().toString();
            String age = mAge.getText().toString();
            String birthdate = mBirthdate.getText().toString();
            Gen = mGender.getSelectedItem().toString();
            String username = mUsername.getText().toString();
            String password = mpass.getText().toString();

            boolean invalid = false;

            if (gname.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(), "Enter your Givenname",
                        Toast.LENGTH_SHORT).show();
            } else

            if (fname.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your firstname", Toast.LENGTH_SHORT)
                        .show();
            } else

            if (mname.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your middlename", Toast.LENGTH_SHORT)
                        .show();
            } else

            if (address1.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your address1", Toast.LENGTH_SHORT)
                        .show();

            } else if (address2.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your address2", Toast.LENGTH_SHORT)
                        .show();
            } else if (cityvillage.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your cityvillage", Toast.LENGTH_SHORT).show();
            } else if (stateprovince.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your stateprovince", Toast.LENGTH_SHORT).show();
            } else if (country.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your country", Toast.LENGTH_SHORT).show();
            } else if (postalcode.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your postalcode", Toast.LENGTH_SHORT).show();
            } else if (age.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your age", Toast.LENGTH_SHORT).show();
            }else if (birthdate.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your birthdate", Toast.LENGTH_SHORT).show();
            }else if (username.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your Username", Toast.LENGTH_SHORT).show();
            } else if (password.equals("")) {
                invalid = true;
                Toast.makeText(getApplicationContext(),
                        "Please enter your password", Toast.LENGTH_SHORT).show();
            } 
            else if (invalid == false) 
            {
                addEntry(gname, fname, mname, address1, address2, cityvillage,
                        stateprovince, country, postalcode, age, birthdate, Gen,
                        username,password);
                Intent i_register = new Intent(Registration1.this,
                        LoginActivity1.class);
                startActivity(i_register);
                // finish();
            }

            break;
        }
    }

    public void onDestroy() {
        super.onDestroy();
        //DB1.close();
    }

    private void addEntry(String gname,String fname,String mname,String address1,String address2,String cityvillage,String
            stateprovince,String country,String postalcode,String age,String birthdate,String Gen,String username,String password) 
    {

        SQLiteDatabase db1 = DB1.getWritableDatabase();
        ContentValues values = new ContentValues();
        //values.put("id", 2);
        values.put("givenname", gname);
        values.put("firstname", fname);
        values.put("middlename", mname);
        values.put("address1", address1);
        values.put("address2", address2);
        values.put("cityvillage", cityvillage);
        values.put("stateprovince", stateprovince);
        values.put("country", country);
        values.put("postalcode", postalcode);
        values.put("age", age);
        values.put("birthdate", birthdate);
        values.put("gender", Gen);
        values.put("username", username);
        values.put("password", password);

        try {
            long rowId = db1.insert(DBHelper1.DATABASE_TABLE_NAME, null, values);
            System.out.println("rowId: "+rowId);
            Toast.makeText(getApplicationContext(),
                    "your details submitted Successfully...",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
        // Get the currently selected State object from the spinner
        State st = (State) mGender.getSelectedItem();

        // Show it via a toast
        toastState("onItemSelected", st);
    }

    public void toastState(String name, State st) {
        if (st != null) {
            Gen = st.name;
            // Toast.makeText(getBaseContext(), Gen, Toast.LENGTH_SHORT).show();

        }

    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }




}

LoginActivity1.java

package com.example.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity1 extends Activity implements OnClickListener 
{

    Button mLogin;
    Button mRegister;


    EditText muname;
    EditText mpassword;

    DBHelper1 DB2 = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_activity1);

        mRegister = (Button) findViewById(R.id.register1);
        mRegister.setOnClickListener(this);

        mLogin = (Button) findViewById(R.id.login1);
        mLogin.setOnClickListener(this);
    }
        /*public void onClick(View v) {
            switch (v.getId()) {

            case R.id.register:
                Intent i = new Intent(getBaseContext(), Registration1.class);
                startActivity(i);
                break;

            case R.id.login:
                System.out.println("LOGIN BUTTON CLICKED-----111----->>>");
                muname = (EditText) findViewById(R.id.Ledituname);
                mpassword = (EditText) findViewById(R.id.Leditpw);

                String username = muname.getText().toString();
                String password = mpassword.getText().toString();

                if (username.equals("") || username == null) {
                    Toast.makeText(getApplicationContext(),
                            "Please enter User Name", Toast.LENGTH_SHORT).show();
                } else if (password.equals("") || password == null) {
                    Toast.makeText(getApplicationContext(),
                            "Please enter your Password", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    boolean validLogin = validateLogin(username, password,
                            getBaseContext());
                    System.out.println("LOGIN BUTTON CLICKED-------222--->>>");
                    if (validLogin) {
                        // System.out.println("In Valid");
                        //Intent in = new Intent(getBaseContext(), TabBar.class);
                        // in.putExtra("UserName", muname.getText().toString());
                        //startActivity(in);
                        Intent i1 = new Intent(getBaseContext(), TabBar.class);
                        Toast.makeText(getApplicationContext(),
                                "Success Valid Login", Toast.LENGTH_SHORT)
                                .show();
                        startActivity(i1);
                        // finish();
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(),
                                "Register First", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
                break;

            }

        }
*/
        private boolean validateLogin(String username, String password,
                Context baseContext) {
            System.out.println("in validateLogin---1");
            DB2 = new DBHelper1(getBaseContext());System.out.println("in validateLogin---2");
            SQLiteDatabase db2 = DB2.getReadableDatabase();System.out.println("in validateLogin--3");

            String[] columns = { "id" };

            String selection = "username=? AND password=?";
            String[] selectionArgs = { username, password };

            Cursor cursor = null;
            try {

                cursor = db2.query(DBHelper1.DATABASE_TABLE_NAME, columns, selection,
                        selectionArgs, null, null, null);
                System.out.println("in validateLogin---4");
                //startManagingCursor(cursor);
            } catch (Exception e)

            {
               System.out.println("Excetion in valid login"+e.getMessage());
            }

            int numberOfRows = cursor.getCount();
            System.out.println("numberOfRows::"+numberOfRows);

            if (numberOfRows <= 0) {

                Toast.makeText(getApplicationContext(),
                        "User Name and Password miss match.Register First.\nPlease Try Again",
                        Toast.LENGTH_LONG).show();
                Intent intent = new Intent(getBaseContext(), MainActivity.class);
                startActivity(intent);
                return false;
            }

            return true;

        }

        @Override
        public void onClick(View v) {
            System.out.println("onClick OF lOGINaCTIVITY----->>>");
            switch (v.getId()) {

            case R.id.register1:
                Intent i = new Intent(getBaseContext(), Registration1.class);
                startActivity(i);
                break;

            case R.id.login1:
                System.out.println("LOGIN BUTTON CLICKED-----111----->>>");
                muname = (EditText) findViewById(R.id.Ledituname);
                mpassword = (EditText) findViewById(R.id.Leditpw);

                String username = muname.getText().toString();
                String password = mpassword.getText().toString();

                if (username.equals("") || username == null) {
                    Toast.makeText(getApplicationContext(),
                            "Please enter User Name", Toast.LENGTH_SHORT).show();
                } else if (password.equals("") || password == null) {
                    Toast.makeText(getApplicationContext(),
                            "Please enter your Password", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    boolean validLogin = validateLogin(username, password,
                            getBaseContext());
                    System.out.println("LOGIN BUTTON CLICKED-------222--->>>");
                    if (validLogin) {
                         System.out.println("In Valid");
                        //Intent in = new Intent(getBaseContext(), TabBar.class);
                        // in.putExtra("UserName", muname.getText().toString());
                        //startActivity(in);
                        Intent i1 = new Intent(getBaseContext(), TabBar.class);
                        Toast.makeText(getApplicationContext(),
                                "Success Valid Login", Toast.LENGTH_SHORT)
                                .show();
                        startActivity(i1);
                        // finish();
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(),
                                "Register First", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
                break;

            }

        }

         @Override
            public void onDestroy() {
                super.onDestroy();
                //DB2.close();
            }
    }

activity_login_activity1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/Luname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="User Name"

        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/Ledituname"

        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:singleLine="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp">


        <requestFocus />
    </EditText>


    <TextView
        android:id="@+id/Lpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/Leditpw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"/>


    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
        android:id="@+id/login1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:text="Login" />

    <Button
        android:id="@+id/register1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Register" />

    </RelativeLayout>




</LinearLayout>

Please Help guys.....

user3736518
  • 75
  • 1
  • 2
  • 12
  • Possible duplicate of [Unable to login(android application)](http://stackoverflow.com/questions/24550764/unable-to-loginandroid-application) – tir38 May 03 '17 at 19:18

1 Answers1

0

Are you sure you're getting a valid database reference in the second pass? For database access in general, you should try to stick to the "one helper, one reference" principles outlined here:

What are the best practices for SQLite on Android?

Community
  • 1
  • 1
WalkingFood
  • 136
  • 5
  • Thanks WalkingFood for your answer. Yes am getting valid DB reference in second pass. I have one DBHelper. – user3736518 Jul 04 '14 at 03:05
  • Actually, you have several Helper objects. You create a new one each time you call validateLogin, and each time your Registration1 Activity is created. The single helper reference I was talking about can be seen in something like this: http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection – WalkingFood Jul 04 '14 at 14:47
  • As a next step for debugging this, can you try to change your query so that it doesn't check for any parameters, just to see if your database reference is finding any data at all in the second pass? Something like: cursor = db2.query(DBHelper1.DATABASE_TABLE_NAME, null, null, null, null, null, null); – WalkingFood Jul 04 '14 at 14:49