Access SQLiteOpenHelper onCreate Method from wrapping class - java

Right now i am calling an insertSomeContacts() function in the onCreate method of the MainActivity which obviously adds the given contacts every time the app is restarted (including screen roation)...since my SQLiteOpenHelper Sub-Class is part of my ContactsDBAdapter Class (which carries the insertSomeContacts() method) - how do i get this function to execute in the SQLiteOpenHelper onCreate so that it only executes once at creation of the database?
Really having problems understanding the scope of this and passing that scope around properly.
MainActivity.java:
public class MainActivity extends Activity {
Intent intent;
private ContactsDBAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new ContactsDBAdapter(this);
dbHelper.open();
//dbHelper.deleteAll();
//dbHelper.insertSomeContacts();
displayListView();
}
private void displayListView(){
Cursor cursor = dbHelper.getAll();
String[] fromColumns = new String[]{
ContactsDBAdapter.COLUMN_TYPE,
ContactsDBAdapter.COLUMN_CLTYP,
ContactsDBAdapter.COLUMN_NAME,
ContactsDBAdapter.COLUMN_VNAME
};
int[] toViews = new int[]{
R.id.contactType,
R.id.contactCltype,
R.id.contactName,
R.id.contactVname
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor, fromColumns, toViews, 0);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(dataAdapter);
}
ContactsDBAdapter.java:
public class ContactsDBAdapter{
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_CLTYP = "cltyp";
public static final String COLUMN_MDT = "mdt";
public static final String COLUMN_OBJ = "obj";
public static final String COLUMN_VTR = "vtr";
public static final String COLUMN_FKZ = "fkz";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VNAME = "vname";
public static final String COLUMN_TEL = "tel";
public static final String COLUMN_FAX = "fax";
public static final String COLUMN_MOBIL = "mobil";
public static final String COLUMN_EMAIL = "email";
private static final String TAG = "ContactsDBAdapter";
private DBTools mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "hvkontakte.db";
private static final String DATABASE = "hvkontakte";
private static final String TABLE_NAME = DATABASE;
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TYPE + ", " + COLUMN_CLTYP + ", " + COLUMN_MDT + ", " + COLUMN_OBJ + ", "
+ COLUMN_VTR + ", " + COLUMN_FKZ + ", " + COLUMN_NAME + ", " + COLUMN_VNAME + ", "
+ COLUMN_TEL + ", " + COLUMN_FAX + ", " + COLUMN_MOBIL + ", " + COLUMN_EMAIL + ")";
private static class DBTools extends SQLiteOpenHelper{
public DBTools(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
Log.w(TAG, DATABASE_CREATE);
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS" + DATABASE);
onCreate(database);
}
}
public ContactsDBAdapter(Context ctx){
this.mCtx = ctx;
}
public ContactsDBAdapter open() throws SQLException{
mDbHelper = new DBTools(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
if(mDbHelper != null){
mDbHelper.close();
}
}
public long createContact(String type, String cltyp, String mdt, String obj, String vtr,
String fkz, String name, String vname, String tel, String fax,
String mobil, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_TYPE, type);
initialValues.put(COLUMN_CLTYP, cltyp);
initialValues.put(COLUMN_MDT, mdt);
initialValues.put(COLUMN_OBJ, obj);
initialValues.put(COLUMN_VTR, vtr);
initialValues.put(COLUMN_FKZ, fkz);
initialValues.put(COLUMN_NAME, name);
initialValues.put(COLUMN_VNAME, vname);
initialValues.put(COLUMN_TEL, tel);
initialValues.put(COLUMN_FAX, fax);
initialValues.put(COLUMN_MOBIL, mobil);
initialValues.put(COLUMN_EMAIL, email);
return mDb.insert(TABLE_NAME, null, initialValues);
}
public boolean deleteAll() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_NAME, null , null);
return doneDelete > 0;
}
public Cursor getAll() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID,
COLUMN_TYPE, COLUMN_CLTYP, COLUMN_NAME, COLUMN_VNAME},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSomeContacts(){
createContact("vtr","Tenant","1","82","1","2","Bennett","Tony","0911-123456","0911-123457","01577-12345678","info#email.com");
createContact("vtr","Owner","1","82","","","Smith","Brad","0911-1234567","0911-1234567","01577-84368365","info#email.com");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
}
}

work with SharedPreferences. Set a init boolean. if init is false insert the contacts -> set the init to true. after restarting do noting when init is true.
But this is maybe not the best solution for your usecase...

Related

Creating SQLite database for Live magnetic sensor data

I am new in Android platform. I want to record the live magnetic sensor data directly to sQLite database in storage. I wrote code to get magnetic data but i am not able to create the database. I have pasted code below. Any help would be great.
Thank you in advance.
// code for Database Helper
public class DBHelper extends SQLiteOpenHelper{
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
private static final String COL_ID = "ID";
private static final String COL_XAXIS = "X-AXIS";
private static final String TABLE_NAME = "MAP_COORDINATES";
private static final String COL_YAXIS = "Y-AXIS";
private static final String COL_ZAXIS = "Z-AXIS";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_XAXIS + " INTEGER," + COL_YAXIS + " INTEGER," + COL_ZAXIS + " INTEGER" + " )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void insert(Integer xaxis, Integer yaxis, Integer zaxis){
SQLiteDatabase db = this.getWritableDatabase();
}
}
// code for getting magnetic sensor data
// Its just fragment of code
public class MainActivity extends AppCompatActivity implements SensorEventListener {
Sensor magnetometer;
SensorManager sm;
TextView magnetismx;
TextView magnetismy;
TextView magnetismz;
DBHelper dbHelper;
public float a;
public float b;
public float c;
boolean recording = false;
boolean stoprecord = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
// I have declared some button here...
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
a = event.values[0];
b = event.values[1];
c = event.values[2];
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetismx.setText(Float.toString(event.values[0]));
magnetismy.setText(Float.toString(event.values[1]));
magnetismz.setText(Float.toString(event.values[2]));
if (!recording) {
return;
}
if(stoprecord){
return;
}
}
try {
writeToCsv(Float.toString(a), Float.toString(b), Float.toString(c));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps: The code for database is not working too.. The table is not created.
I sorted out the problem myself. There was some problem in database class. I have used the below code for database helper class.
ublic class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
//Table for measurement
private static final String ID = "id";
private static final String MAP_ID = "Mapid";
private static final String COLXAXIS = "X_AXIS";
private static final String TABLENAME = "Fingerprint";
private static final String COLYAXIS = "Y_AXIS";
private static final String COLZAXIS = "Z_AXIS";
private static final String MAPX = "X_CORD";
private static final String MAPY = "Y_CORD";
private static final String DIFF = "Diff";
private static final String FINAL = "FINAL";
private static final String KEY_FINGERPRINT_ID = "id";
private static final String KEY_MAP_NAME = "map_name";
private static final String KEY_POSITION_X = "position_x";
private static final String KEY_POSITION_Y = "position_y";
private static DBHelper mInstance;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static DBHelper getInstance() {
if (mInstance == null) {
synchronized (DBHelper.class) {
if (mInstance == null) {
mInstance = new DBHelper(BaseApp.getApp());
}
}
}
return mInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLENAME + "("
+ ID + " INTEGER PRIMARY KEY,"
+ MAP_ID + " INTEGER ," +
MAPX + " INTEGER, " +
MAPY + " INTEGER, " +
COLXAXIS + " REAL, " +
COLYAXIS + " REAL, " +
COLZAXIS + " REAL, " +
FINAL + " REAL )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
onCreate(db);
}
public void insert(int a, int b, int c, float x, float y, float z, float d) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
contentvalues.put("Mapid", a);
contentvalues.put("X_CORD", b);
contentvalues.put("Y_CORD", c);
contentvalues.put("X_AXIS", x);
contentvalues.put("Y_AXIS", y);
contentvalues.put("Z_AXIS", z);
contentvalues.put("FINAL", d);
db.insert("Fingerprint", null, contentvalues);
db.close();
}
public void deleteAllFingerprints() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLENAME, null, null); // delete all fingerprints
db.close();
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cur = db.rawQuery("select * from " + TABLENAME, null);
return cur;
}
}

SQLIte database not able to delete entries

I have a SQLdatabase and I want to delete entries that are displayed in a list view using a button that is next to each entry on the list view. But currently it is not letting me delete.
This problem is located in the selectionargs variable as shown below. If I put a number e.g. 1, into the selectionargs manually it will work, but I have been trying to do it through the a variable that represents each entry. This does not result in an error but just goes straight to the toast message cannot delete. ac.ID refers to the adapter class and the ID of the list item entries.
Bookmark class:
public class Bookmark extends AppCompatActivity {
myAdapter myAdapter;
DBManager db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookmark);
db = new DBManager(this);
onLoadAttraction();
// onLoadTransport();
}
public void onLoadAttraction() {
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkAttraction",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, cursor.getString(cursor.getColumnIndex(DBManager.ColOpening))
, cursor.getString(cursor.getColumnIndex(DBManager.ColClosing))
, cursor.getString(cursor.getColumnIndex(DBManager.ColNearbyStop))
,null,null,null, null, null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
public void onLoadTransport(){
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkTransport",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, null
, null
, null
,cursor.getString(cursor.getColumnIndex(DBManager.ColTime))
,cursor.getString(cursor.getColumnIndex(DBManager.ColNextStop))
, cursor.getString(cursor.getColumnIndex(DBManager.ColPhoneNumber))
,null,null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
Adapter ac;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_bookmark, null);
ac = listItem.get(position);
TextView Type = (TextView) myView.findViewById(R.id.BMType);
Type.setText(ac.Type);
TextView Name = (TextView) myView.findViewById(R.id.BMName);
Name.setText(ac.Name);
TextView Location = (TextView) myView.findViewById(R.id.BMLocation);
Location.setText(ac.Location);
TextView Opening = (TextView) myView.findViewById(R.id.BMOpen);
Opening.setText(ac.Opening);
TextView Closing = (TextView) myView.findViewById(R.id.BMClose);
Closing.setText(ac.Closing);
TextView NearbyStop1 = (TextView) myView.findViewById(R.id.BMNearbyStop);
NearbyStop1.setText(ac.NearbyStop);
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] selectionArgs = {ac.ID};
int count = db.Delete("BookmarkAttraction","ID=? ",selectionArgs);
if (count > 0) {
onLoadAttraction();
Toast.makeText(getApplicationContext(),"Data deleted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Cannnot delete", Toast.LENGTH_LONG).show();
}
}
});
return myView;
}
}
}
DBManager class:
public class DBManager {
private SQLiteDatabase sqlDB;
static final String ColId = "ID";
static final String DBName = "InternalDB";
static final String TableName = "BookmarkAttraction";
static final String TableName2 = "BookmarkTransport";
static final String TableName3 = "Itinerary";
static final String ColItineraryName = "ItineraryName";
static final String ColDate = "Date";
static final String ColType = "Type";
static final String ColName = "Name";
static final String ColLocation = "Location";
static final String ColOpening = "OpeningTime";
static final String ColClosing = "ClosingTime";
static final String ColNearbyStop = "NerbyStop1";
static final String ColTime = "Time";
static final String ColNextStop = "NextStop";
static final String ColPhoneNumber = "PhoneNumber";
static final int DBVersion = 1;
static final String CreateTable = "CREATE TABLE IF NOT EXISTS " + TableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColType+ " TEXT," +
ColName+ " TEXT," + ColLocation+ " TEXT," + ColOpening+ " TEXT," +ColClosing+ " TEXT," + ColNearbyStop+ " TEXT);";
static final String CreateTabe2 = "CREATE TABLE IF NOT EXISTS " +TableName2 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ColType + " TEXT,"
+ ColName + " TEXT,"
+ ColLocation + " TEXT,"
+ ColTime+ " TEXT,"
+ ColNextStop + " TEXT,"
+ ColPhoneNumber + " TEXT);";
static final String CreateTable3 = "CREATE TABLE IF NOT EXISTS " + TableName3 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColItineraryName + " TEXT,"
+ ColDate + " TEXT," + ColName + " TEXT," + ColLocation + " TEXT," + ColTime + " TEXT);";
static class DBHelper extends SQLiteOpenHelper{
Context context;
DBHelper(Context context){
super(context, DBName, null, DBVersion);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
Toast.makeText(context,DBName,Toast.LENGTH_LONG).show();
db.execSQL(CreateTable);
Toast.makeText(context,"Table is created ", Toast.LENGTH_LONG).show();
db.execSQL(CreateTabe2);
Toast.makeText(context,"Transport table created", Toast.LENGTH_LONG).show();
db.execSQL(CreateTable3);
Toast.makeText(context,"Itin table created", Toast.LENGTH_LONG).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TableName);
db.execSQL("DROP TABLE IF EXISTS" + TableName2);
db.execSQL("DROP TABLE IF EXISTS" + TableName3);
onCreate(db);
}
}
public DBManager(Context context){
DBHelper db = new DBHelper(context);
sqlDB = db.getWritableDatabase();
}
public long Insert(String tablename,ContentValues values){
long ID = sqlDB.insert(tablename,"",values);
return ID;
}
public Cursor Query(String tablename, String [] projection, String selection, String [] selectionArgs, String sortOrder){
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tablename);
Cursor cursor = qb.query(sqlDB,projection, selection, selectionArgs,null,null,sortOrder);
return cursor;
}
public int Delete(String tablename,String selection, String[] selectionArgs){
int count = sqlDB.delete(tablename,selection,selectionArgs);
return count;
}
}
Adapter class:
public class Adapter {
public String ID;
public String Type;
public String Name;
public String Location;
public String Opening;
public String Closing;
public String NearbyStop;
public String Time;
public String NextStop;
public String PhoneNumber;
public String Latitude;
public String Longitude;
public Adapter(String type, String name, String location, String opening, String closing,
String nearbyStop, String time, String nextStop, String phoneNumber, String Latitude,
String Longitude) {
this.Type = type;
this.Name = name;
this.Location = location;
this.Opening = opening;
this.Closing = closing;
this.NearbyStop = nearbyStop;
this.Time = time;
this.NextStop = nextStop;
this.PhoneNumber = phoneNumber;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
}
The code for the delete button is in my bookmark class with the DBManager holding the actual delete code. If anyone can help with this it would be greatly appreciated.
Remove the ac field of your myAdapter class, and use it as a method variable inside the getView method.
Then use the ListView.setOnItemClickListener method to add an on click listener with positional awareness. (do this only once after you set the adapter) This way you can do listItem.get(position) to get the item in that position.

join tables sqlite android [duplicate]

This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
I have two tables: user and balance.
User DAO:
public class NewUserDAO {
public static final String TAG = "NewUserDAO";
public static final String TABLE_NEWUSER = "newUser";
//database fields
private SQLiteDatabase mDataBase;
private DatabaseHandler mDbHelper;
private Context mContext;
private String [] mAllColumns = {
DatabaseHandler.COLUMN_NEWUSER_ID,
DatabaseHandler.COLUMN_NEWUSER_NAME, DatabaseHandler.COLUMN_NEW_USER_PASSWORD,
DatabaseHandler.COLUMN_NEW_USER_AGE };
public NewUserDAO(Context context){
this.mContext = context;
mDbHelper = new DatabaseHandler(context);
try{
open();
} catch (SQLException e){
Log.e(TAG,"SQLexception on opening database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException{
mDataBase = mDbHelper.getWritableDatabase();
}
public void close(){
mDbHelper.close();
}
public void createNewUser(NewUserTable newUserTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_NEWUSER_NAME,newUserTable.getName());
values.put(DatabaseHandler.COLUMN_NEW_USER_PASSWORD, newUserTable.getPassword());
values.put(DatabaseHandler.COLUMN_NEW_USER_AGE, newUserTable.getAge());
mDataBase.insert(TABLE_NEWUSER, null, values);
mDataBase.close();
}
}
balance DAO:
public class BalanceDAO {
public static final String TAG = "BalanceDAO";
public static final String TABLE_BALANCE = "balanceOfUser";
private Context mContext;
//Database fields
private SQLiteDatabase mDatabase;
private DatabaseHandler mDhelper;
private String[] mAllColumns = {
DatabaseHandler.COLUMN_BALANCE_ID,
DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,
DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,
DatabaseHandler.COLUMN_BALANCE_NEW_USER_ID
};
public BalanceDAO (Context context){
mDhelper = new DatabaseHandler(context);
this.mContext = context;
try{
open();
}
catch (SQLException e){
Log.e(TAG, "SQLException on openning database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDhelper.getWritableDatabase();
}
public void close(){
mDhelper.close();
}
public void createBalance (BalanceTable balanceTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,balanceTable.getDollarBalance());
values.put(DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,balanceTable.getRubBalance());
mDatabase.insert(TABLE_BALANCE, null, values);
mDatabase.close();
}
}
And SQLiteOpenHelper class:
public class DatabaseHandler extends SQLiteOpenHelper {
//COLUMNS OF THE NEW USER TABLE
public static final String TABLE_NEWUSER = "newUser";
public static final String COLUMN_NEWUSER_ID = "id";
public static final String COLUMN_NEWUSER_NAME = "name";
public static final String COLUMN_NEW_USER_PASSWORD = "password";
public static final String COLUMN_NEW_USER_AGE = "age";
//COLUMNS OF THE BALANCE TABLE
public static final String COLUMN_BALANCE_ID = "id";
public static final String TABLE_BALANCE = "balanceOfUser";
public static final String COLUMN_BALANCE_DOLLARBALANCE = "dollarBalance";
public static final String COLUMN_BALANCE_RUBBALANCE = "rubBalance";
public static final String COLUMN_BALANCE_NEW_USER_ID = "newUserId";
private static final String DATABASE_NAME = "webStore";
private static final int DATABASE_VERSION = 1;
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_NEWUSER = "CREATE TABLE " + TABLE_NEWUSER + "("
+ COLUMN_NEWUSER_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_NEWUSER_NAME + " TEXT not null,"
+ COLUMN_NEW_USER_PASSWORD + " TEXT not null,"
+ COLUMN_NEW_USER_AGE + " INTEGER"
+ ")";
db.execSQL(SQL_CREATE_NEWUSER);
String SQL_CREATE_BALANCE = "CREATE TABLE " + TABLE_BALANCE + "("
+ COLUMN_BALANCE_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_BALANCE_DOLLARBALANCE + " INTEGER,"
+ COLUMN_BALANCE_RUBBALANCE + " INTEGER,"
+ COLUMN_BALANCE_NEW_USER_ID + " INTEGER," + "FOREIGN KEY("+COLUMN_BALANCE_NEW_USER_ID+") REFERENCES "
+ TABLE_NEWUSER + "(id) "+ ")" ;
db.execSQL(SQL_CREATE_BALANCE);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWUSER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BALANCE);
}
}
I want to join user and balance tables. How can i do? When i call Create Method, i have exception.
public void CreateUser(View view) {
etName = (EditText)findViewById(R.id.etName);
etPassword = (EditText)findViewById(R.id.etPassword);
etAge = (EditText)findViewById(R.id.etAge);
String name = String.valueOf(etName.getText());
String password = String.valueOf(etPassword.getText());
int age = Integer.parseInt(String.valueOf(etAge.getText()));
BalanceTable balanceTable = new BalanceTable(0,0);
NewUserTable newUserTable = new NewUserTable(name,password,age);
//write to database of user from our edit texts
DatabaseHandler databaseHandler = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
NewUserDAO dbForUser = new NewUserDAO(this);
dbForUser.createNewUser(newUserTable);
BalanceDAO balanceDAO = new BalanceDAO(this);
balanceDAO.createBalance(balanceTable);
}
From edit text i take data. Help please
There are a few types if join, inner (which I think is what you want) which shows the data that matches, left showing all data from the first table and any additional data from the second table that meets the on condition or right which is shows all from the second table and any form the right that matches.
to Join two table you must use a statement such as
"SELECT <all the values you want> "+
" FROM users" +
" left join balance" +
" ON users.id=balance.userid " +
" where <some condition> "+
" order by gmttimestamp ;"; "
this will give you result set of mixed tables

User Login with SQLite database java.lang.NullPointerException

I'm having a problem using my database to check the username and password of the user. I'm using a query to select the specific row and then check the password against what was entered by the user. The error I am getting is a java.lang.NullPointerException in my login page when i call the
Users userlogin = db.userlogin(usernameinput);
After looking at the method I'm thinking its the first cursor that causes it to fail
cursor.getInt(0);
What I'm wondering is am I right in thinking this and what can I do to change it?
I've tried changing the if statement to
If(cursor.getcount() > 0)
and still no luck.
public class LoginPage extends ActionBarActivity {
Button loginbutton;
EditText usernameuser, passworduser;
DatabaseHandler db;
String usernameinput, passwordinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
loginbutton = (Button) findViewById(R.id.loginbtn);
usernameuser = (EditText) findViewById(R.id.usernameInsert);
passworduser = (EditText) findViewById(R.id.passwordInsert);
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usernameinput = usernameuser.getText().toString();
passwordinput = passworduser.getText().toString();
Users userlogin = db.userLogin(usernameinput);
if (usernameinput.equals(userlogin.get_username()) && passwordinput.equals(userlogin.get_password())) {
startActivity(new Intent(getApplicationContext(), Home_Page.class));
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
Database handler Query used to check login:
public Users userLogin(String username) {
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, projection, selection, selectionargs, null, null,null );
if (cursor != null)
cursor.moveToFirst();
Users users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getDouble(6),
cursor.getDouble(7),
cursor.getDouble(8),
cursor.getDouble(9),
cursor.getDouble(10),
cursor.getDouble(11),
cursor.getDouble(12),
cursor.getDouble(13),
cursor.getDouble(14),
cursor.getDouble(15),
cursor.getDouble(16),
cursor.getDouble(17),
cursor.getDouble(18),
cursor.getDouble(19));
cursor.close();
return users;
}
04-08 13:05:33.194 2565-2565/com.example.john.fitnessapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.john.fitnessapp, PID: 2565
java.lang.NullPointerException
at com.example.john.fitnessapp.LoginPage$1.onClick(LoginPage.java:42)
at android.view.View.performClick(View.java:4569)
at android.view.View$PerformClick.run(View.java:18553)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:718)
at dalvik.system.NativeStart.main(Native Method)
user class:
public class Users {
int _id, _age;
String _username, _password, _email, _gender;
double _startWeight, _currentWeight, _weightChange, _height, _BMI, _BMR, _reqCal, _monCal, _tuesCal, _wedCal, _thurCal, _friCal, _satCal, _sunCal;
public Users(){}
public Users(int _id, String _username, String _password, int _age, String _email, String _gender, double _height, double _startWeight,
double _currentWeight, double _weightChange, double _BMI, double _BMR, double _reqCal, double _monCal, double _tuesCal, double _wedCal,
double _thurCal, double _friCal, double _satCal, double _sunCal){
this._id = _id;
this._username = _username;
this._password = _password;
this._age = _age;
this._email = _email;
this._gender = _gender;
this._height = _height;
this._startWeight = _startWeight;
this._currentWeight = _currentWeight;
this._weightChange = _weightChange;
this._BMI = _BMI;
this._BMR = _BMR;
this._reqCal = _reqCal;
this._monCal = _monCal;
this._tuesCal = _tuesCal;
this._wedCal = _wedCal;
this._thurCal = _thurCal;
this._friCal = _friCal;
this._satCal = _satCal;
this._sunCal = _sunCal;
}
public int get_id(){
return this._id;
}
public void set_id(int id){
this._id = id;
}
public String get_username(){
return this._username;
}
public void set_username(String username){
this._username = username;
}
public String get_password(){
return this._password;
}
public void set_password(String password){
this._password = password;
}
public int get_age(){
return this._age;
}
public void set_age(int age){
this._age = age;
}
public String get_email(){
return this._email;
}
public void set_email(String email){
this._email = email;
}
public String get_gender(){
return this._gender;
}
public void set_gender(String gender){
this._gender = gender;
}
public double get_height(){
return this._height;
}
public void set_height(double height){
this._height = height;
}
public double get_startWeight(){
return this._startWeight;
}
public void set_startWeight(double startWeight){
this._startWeight = startWeight;
}
public double get_currentWeight(){
return this._currentWeight;
}
public void set_currentWeight(double currentWeight){
this._currentWeight = currentWeight;
}
public double get_weightChange(){
return this._weightChange;
}
public void set_weightChange(){
this._weightChange = _currentWeight - _startWeight;
}
public double get_BMI(){
return this._BMI;
}
public void set_BMI(double BMI){
this._BMI = BMI;
}
public double get_BMR(){
return this._BMR;
}
public void set_BMR(double BMR){
this._BMR = BMR;
}
public double get_reqCal(){
return this._reqCal;
}
public void set_reqCal(double reqCal){
this._reqCal = reqCal;
}
public double get_monCal(){
return this._monCal;
}
public void set_monCal(double monCal){
this._monCal = monCal;
}
public double get_tuesCal(){
return this._tuesCal;
}
public void set_tuesCal(double tuesCal){
this._tuesCal = tuesCal;
}
public double get_wedCal(){
return this._wedCal;
}
public void set_wedCal(double wedCal){
this._wedCal = wedCal;
}
public double get_thurCal(){
return this._thurCal;
}
public void set_thurCal(double thurCal){
this._thurCal = thurCal;
}
public double get_friCal(){
return this._friCal;
}
public void set_friCal(double friCal){
this._friCal = friCal;
}
public double get_satCal(){
return this._satCal;
}
public void set_satCal(double satCal){
this._satCal = satCal;
}
public double get_sunCal(){
return this._sunCal;
}
public void set_sunCal(double sunCal){
this._sunCal = sunCal;
}
}
Databasehandler:
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String TAG = "DBHelper";
//DATABASE VERSION
private static int DATABASE_VERSION = 1;
//DATABASE NAME
private static final String DATABASE_NAME = "AppDatabase";
//TABLE NAMES
private static final String TABLE_USERS = "Users_Table";
private static final String TABLE_PRODUCTS = "Products_Table";
//COMMON COLUMN NAMES
private static final String KEY_USER_ID = "User_ID";
private static final String KEY_PRODUCT_ID = "Product_ID";
//USER TABLE
private static final String KEY_USERNAME = "Username";
private static final String KEY_PASSWORD = "Password";
private static final String KEY_AGE = "Age";
private static final String KEY_EMAIL = "Email";
private static final String KEY_GENDER = "Gender";
private static final String KEY_HEIGHT = "Height";
private static final String KEY_CURRENT_WEIGHT = "Current_Weight";
private static final String KEY_START_WEIGHT = "Start_Weight";
private static final String KEY_WEIGHT_CHANGE = "Weight_Change";
private static final String KEY_BMI = "BMI";
private static final String KEY_BMR = "BMR";
private static final String KEY_REQ_CAL = "Required_Calories";
private static final String KEY_MON_CAL = "Monday_Calories";
private static final String KEY_TUES_CAL = "Tuesday_Calories";
private static final String KEY_WED_CAL = "Wednesday_Calories";
private static final String KEY_THUR_CAL = "Thursday_Calories";
private static final String KEY_FRI_CAL = "Friday_Calories";
private static final String KEY_SAT_CAL = "Saturday_Calories";
private static final String KEY_SUN_CAL = "Sunday_Calories";
//PRODUCT TABLE
private static final String KEY_ITEMNAME = "Item_name";
private static final String KEY_ITEMCALORIES = "Item_Calories";
//
private static final String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "( "
+ KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT, "
+ KEY_AGE + " INTEGER, "
+ KEY_EMAIL + " TEXT, "
+ KEY_GENDER + " TEXT, "
+ KEY_HEIGHT + " DOUBLE, "
+ KEY_START_WEIGHT + " DOUBLE, "
+ KEY_CURRENT_WEIGHT + " DOUBLE, "
+ KEY_WEIGHT_CHANGE + " DOUBLE, "
+ KEY_BMI + " DOUBLE, "
+ KEY_BMR + " DOUBLE, "
+ KEY_REQ_CAL + " DOUBLE, "
+ KEY_MON_CAL + " DOUBLE, "
+ KEY_TUES_CAL + " DOUBLE, "
+ KEY_WED_CAL + " DOUBLE, "
+ KEY_THUR_CAL + " DOUBLE, "
+ KEY_FRI_CAL + " DOUBLE, "
+ KEY_SAT_CAL + " DOUBLE, "
+ KEY_SUN_CAL + " DOUBLE ); ";
private static final String CREATE_PRODUCT_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "( " + KEY_PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_ITEMNAME + " TEXT, "
+ KEY_ITEMCALORIES + " DOUBLE );";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_PRODUCT_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG,
"Upgrading the database from version " + oldVersion + " to " + newVersion);
DATABASE_VERSION = 2;
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
Edit: Make sure you initialize your class that extends SQLiteOpenHelper.
Make sure you call:
db = new DatabaseHandler(this);
If you don't initialize db then it will be null when you call db.userLogin(usernameinput);, and that might be the cause of the NullPointerException that you're getting.
You could just call it in `onCreate()' like this:
public class LoginPage extends ActionBarActivity {
Button loginbutton;
EditText usernameuser, passworduser;
DatabaseHandler db;
String usernameinput, passwordinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
db = new DatabaseHandler(this); //initialize the DatabaseHandler
//........
In addition, it looks like you're only querying three columns of the database, and trying to access twenty columns in the cursor.
Also, you should check the return value of cursor.moveToFirst().
In general, the cursor will never be null.
This will probably make it work short term, but you might want to consider re-factoring your code such that you don't have to query all rows to make it work:
public Users userLogin(String username) {
Users users = null;
SQLiteDatabase db = this.getReadableDatabase();
//String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, null, selection, selectionargs, null, null,null );
if (cursor.moveToFirst()){
users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getDouble(6),
cursor.getDouble(7),
cursor.getDouble(8),
cursor.getDouble(9),
cursor.getDouble(10),
cursor.getDouble(11),
cursor.getDouble(12),
cursor.getDouble(13),
cursor.getDouble(14),
cursor.getDouble(15),
cursor.getDouble(16),
cursor.getDouble(17),
cursor.getDouble(18),
cursor.getDouble(19));
}
cursor.close();
return users;
}
Ideally you would create another constructor for your Users class that could just take the three parameters that you need in this case.
Your modified code would be something like this:
public Users userLogin(String username) {
Users users = null;
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, projection, selection, selectionargs, null, null,null );
if (cursor.moveToFirst()){
users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2))
}
cursor.close();
return users;
}
Also, it would be good to check for null return value from your userLogin() function:
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usernameinput = usernameuser.getText().toString();
passwordinput = passworduser.getText().toString();
Users userlogin = db.userLogin(usernameinput);
if (userlogin != null && usernameinput.equals(userlogin.get_username()) && passwordinput.equals(userlogin.get_password())) {
startActivity(new Intent(getApplicationContext(), Home_Page.class));
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});

Why I am not getting any result from rawQuery method in android

I am doing a simple SQlite Apps where I want to save group name in a table and show it on a listview as soon as user click on the add button.
Can any body help me why I am not getting null value from rawQuery result?
public class AddData {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "Grup.db";
public static final int DB_VERSION = 1;
public static final String TABLE = "Grups";
public static final String C_ID = BaseColumns._ID;
public static final String C_CREATED_AT = "easy_ass_created_At";
public static final String C_NAME = "name";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper {
// public static final String TAG = DbHelper.class.getSimpleName();
// public static final String DB_NAME = "Grup.db";
// public static final int DB_VERSION = 1;
// public static final String TABLE = "Grups";
// public static final String C_ID = BaseColumns._ID;
// public static final String C_CREATED_AT = "easy_ass_created_At";
// public static final String C_NAME = "name";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = ("create table " + TABLE + " ( " + C_ID
+ " integer primary key autoincrement, " + C_NAME
+ " text not null" + ");");
db.execSQL(sql);
Log.d(TAG, "OnCreate sql" + sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE);
this.onCreate(db);
Log.d("TAG", "********On Upgrate Drop Table*****");
}
}
public AddData(Context context) {
ourContext = context;
}
public AddData open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getReadableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name) {
ContentValues cv = new ContentValues();
cv.put(C_NAME, name);
return ourDatabase.insert(TABLE, null, cv);
}
public String getData() {
String[] columns = new String[] { C_ID, C_NAME };
Cursor c = ourDatabase.query(TABLE, columns, null, null, null, null,
null);
String result = "";
// int iRow=c.getColumnIndex(C_ID);
int iName = c.getColumnIndex(C_NAME);
// for(c.moveToFirst();!c.isAfterLast();c.moveToLast()){
for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c
.moveToNext()) {
result = result + " " + c.getString(iName) + "\n";
c.moveToNext();
}
c.close();
return result;
}
public ArrayList<String> fatchData() {
ArrayList<String> results = new ArrayList<String>();
try {
Cursor c = ourDatabase.rawQuery("SELECT * from Grups;", null);
if (c != null) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("name"));
results.add("Project: " + firstName);
} while (c.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (ourDatabase != null)
ourDatabase.execSQL("DELETE FROM Grups");
ourDatabase.close();
}
return results;
}
}
Try removing c.close() and use startManagingCursor(c) (after creating the cursor) in your getData() method

Categories