lundi 14 mars 2016

Android how to insert data into database outside of the database helper class

I have set up a SQLite database which is working fine in terms of creating the tables that i need. What i have been trying to do now is insert into the database but from another class (Signup.java). I want to grab text input into edittext and insert this into the database,but only when a button is clicked.

See my DatabaseHelper class below:

package com.example.testerrquin.euro2016fanguide;

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

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Euro2016.db";
public static final String TABLE_USERS = "Users_table";
public static final String TABLE_CAPACITY = "Capacity_table";
public static final int CapacityOne = 1;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    SQLiteDatabase db = this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("Create table " + TABLE_USERS +" (UserID INTEGER PRIMARY KEY AUTOINCREMENT, Forename TEXT, Surname TEXT, Email TEXT, Password TEXT, Country TEXT)");
    db.execSQL("Create table " + TABLE_CAPACITY +" (CapacityID INTEGER PRIMARY KEY AUTOINCREMENT, Capacity INTEGER)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CAPACITY);
    onCreate(db);
}
}

Basically i need to run the line starting with "db.execSQL". I probably need to reference 'db' somewhere to link up to Databasehelper class but not sure. At the moment i am getting 'Cannot resolve symbol 'db'.

CompleteB.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            String grabFirstname = UsernameET.getText().toString();
            String grabSurname = SurnameET.getText().toString();
            String grabEmail = EmailET.getText().toString();
            String grabPassword = PasswordET.getText().toString();
            String grabCountry = CountryDrop.getSelectedItem().toString();

            db.execSQL("Insert into Users_table (Forename, Surname, Email, Password, Country) values ((" + grabFirstname +"),(" + grabSurname +"),(" + grabEmail +"), (" + grabPassword +"), (" + grabCountry +"))");

            Intent i=new Intent(Signup.this,Login.class);
            startActivity(i);
        }
    });

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire