Click here to Skip to main content
15,923,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Am doing an application that requires that I check if the database exist else I create it.My code works for the first time. But subsequently when I try to call other methods inside the class that holds the sqlite constructor, my former database is erased and a new one is created because I call the constructor.

What I have tried:

package com.pass;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    String DB_NAME = "passManager.db";
    String TAG = "MY DATABASE";

    Database database;
    //FOR REGISTRATION
    EditText MASTER_EM, MASTER_PASS, MASTER_CPASS, MASTER_QUES, MASTER_ANS;
    String masterEmail, masterPass, masterConfirmPass, masterQuestion, masterAnswer;
    Context context;

    //FOR LOGIN
    EditText TEXTEMAIL, TEXTPASSWORD;
    String loginEmail, loginPassword;
    Button btn,btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        boolean status = dataBaseExist(DB_NAME);
        database = new Database(context);
        if(status){

            setContentView(R.layout.register);
            //collect values from UI for registration
            MASTER_EM = (EditText) findViewById(R.id.MASTER_EMAIL_REG);
            MASTER_PASS = (EditText) findViewById(R.id.MASTER_PASSWORD_REG);
            MASTER_CPASS = (EditText)findViewById(R.id.RMASTER_PASSWORD);
            MASTER_QUES = (EditText) findViewById(R.id.QUESTION);
            MASTER_ANS = (EditText) findViewById(R.id.ANSWER);
            btn = (Button) findViewById(R.id.REGISTER_ACCT);
            btn.setOnClickListener(this);
        }
        else{
            setContentView(R.layout.activity_main);

            //collect values from UI for login
            TEXTEMAIL = (EditText) findViewById(R.id.txtemail);
            TEXTPASSWORD = (EditText) findViewById(R.id.txtpass);

            btn2 = (Button)findViewById(R.id.btnsignin);
            btn2.setOnClickListener(this);

        }

    }

   private boolean dataBaseExist(String databaseName){
       boolean val = false;
       File database=getApplicationContext().getDatabasePath(databaseName);
       //File d = getApplicationContext().getFilesDir().getPath(databaseName);

       if (!database.exists()) {

           val = true;
           Log.i("My Database", "Not Found");

       } else {

           Log.i("My Database", "Found");
       }

       return val;
   }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.REGISTER_ACCT :

                masterPass = MASTER_PASS.getText().toString();
                masterConfirmPass = MASTER_CPASS.getText().toString();
                masterEmail = MASTER_EM.getText().toString();
                masterQuestion = MASTER_QUES.getText().toString();
                masterAnswer = MASTER_ANS.getText().toString();

                    if(!masterPass.equals(masterConfirmPass)){

                        Toast.makeText(this, "PASSWORD & PASSWORD CONFIRM DID NOT MATCH", Toast.LENGTH_LONG).show();

                    }
                    else {
                        //Save the Data to Database
                        UserInfoAsynctask userInfoAsynctask = new UserInfoAsynctask(context);
                        userInfoAsynctask.execute("insert",masterEmail,masterPass,masterQuestion,masterAnswer);

                        //Restart app
                        Intent i = getBaseContext().getPackageManager()
                                .getLaunchIntentForPackage( getBaseContext().getPackageName() );
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);

                    }
                break;
            case R.id.btnsignin :
                loginEmail = TEXTEMAIL.getText().toString();
                loginPassword = TEXTPASSWORD.getText().toString();
                long check = database.authMaster(loginEmail, loginPassword);
                    if(check == 1){
                        Intent intent = new Intent(MainActivity.this, Profile.class);
                        intent.putExtra("email", loginEmail);
                        startActivity(intent);
                    }
                break;

        }
    }
//Here is the Class for the Database 
package com.pass;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Database extends SQLiteOpenHelper {

    //LOGCAT MESSAGE TAG
    private static final String LOGCAT = "DATABASE CLASS : ";

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "passManager.db";

    // Table Names
    private static final String TABLE_SITES = "sites";
    private static final String TABLE_NOTES = "notes";
    private static final String TABLE_USER = "user";
    private static final String TABLE_NOTE_CAT = "note_cat";

    // SITES Table - column nmaes
    private static final String URL_ID = "url";
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";

    // NOTES Table - column names
    private static final String NOTE_ID = "note_id";
    private static final String NOTES_NOTE_CAT = "note_cat";
    private static final String NOTE_DESC = "note_desc";
    private static final String NOTE_BODY = "note_body";
    private static final String NOTE_DATE = "note_date";



    // NOTE CATEGORY TABLE - column names
    private static final String CAT_ID = "note_cat";
    private static final String CAT_DESC = "desc";

    //MASTER USER ACCOUT TABLE
    private static final String USER_ID = "email";
    private static final String USER_PASSWORD = "password";
    private static final String USER_QUESTION = "question";
    private static final String USER_ANSWER = "answer";

    //CREATE TABLE QUERIES [USER ACCOUNT]
    private static final String CREATE_TABLE_USER_ACCT = "CREATE TABLE "
            + TABLE_USER
            + "("
            + USER_ID + " TEXT PRIMARY KEY,"
            + USER_PASSWORD + " TEXT,"
            + USER_QUESTION + " TEXT,"
            + USER_ANSWER + " TEXT"
            + ")";

    /* NOTE CAT table create statement */
    private static final String CREATE_TABLE_NOTE_CAT = "CREATE TABLE " + TABLE_NOTE_CAT
            + "(" + CAT_ID + " TEXT PRIMARY KEY," + CAT_DESC + " TEXT" + ")";

    /* NOTES table create statement */
    private static final String CREATE_TABLE_NOTES = "CREATE TABLE "
            + TABLE_NOTES + "(" + NOTE_ID + " TEXT PRIMARY KEY," + NOTES_NOTE_CAT + " TEXT," + NOTE_DESC
            + " TEXT," + NOTE_BODY + " TEXT," + NOTE_DATE
            + " TEXT" + ")";

    /* Sites table create statement */
    private static final String CREATE_TABLE_SITES = "CREATE TABLE "
            + TABLE_SITES + "(" + URL_ID + " TEXT PRIMARY KEY," + USERNAME
            + " TEXT," + PASSWORD + " TEXT" + ")";

    public Database(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.d("Database ",DATABASE_NAME+" Created");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //create tables
        db.execSQL(CREATE_TABLE_SITES);
        Log.d("Tables ",TABLE_SITES + " created");

        db.execSQL(CREATE_TABLE_NOTE_CAT);
        Log.d("Tables ",TABLE_NOTE_CAT + " created");

        db.execSQL(CREATE_TABLE_NOTES);
        Log.d("Tables ",TABLE_NOTES + " created");

        db.execSQL(CREATE_TABLE_USER_ACCT);
        Log.d("Tables ",CREATE_TABLE_USER_ACCT + " created");
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTE_CAT);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SITES);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
        Log.d("Tables ",TABLE_SITES + " created");
        // create new tables
        onCreate(db);
    }

    //INSERT INTO USER ACCT TABLE
    public long createUser(String email,String password,String question,String answer){

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(USER_ID, email);
        values.put(USER_PASSWORD, password);
        values.put(USER_QUESTION, question);
        values.put(USER_ANSWER, answer);

        Log.d("Reply","User Created....Sucessfully");
    return db.insert(TABLE_USER,null,values);


    }
    public long authMaster(String userName, String pass) {
        Log.i("NOTE ", userName + "+" + pass);
    return 1;
    }
}
Posted
Updated 15-Jan-17 3:30am
v2
Comments
Richard MacCutchan 15-Jan-17 9:20am    
I cannot see anywhere in the above code where you create the database. What am I missing?
Member 12853279 15-Jan-17 9:30am    
Richard MacCutchan, I have updated the question.
Richard MacCutchan 15-Jan-17 9:37am    
That code still looks confusing, and I cannot figure out where you call the database to add a record, without creating a new database. I recommend you work through the article that Peter wrote (see his link), as it explains it in excellent detail.
Member 12853279 15-Jan-17 9:45am    
It's inside the onCreate Method. Just below the context = this. But can I ask you. If I have more methods inside the one that holds the sqlite constructor, wouldn't I need to call the constructor always before I can access the other methods?
Richard MacCutchan 15-Jan-17 9:53am    
Yes, you always call the constructor as part of initialising your database class. What I am having trouble with is seeing where in your main program you actually invoke any of the database methods. I see the comment //Save the Data to Database, but I cannot understand what the code following it is supposed to do.

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900