I'm trying to implement a database on an android app, but don't really know how to. I've studied one class about databases, so I know some about how these work, but it's coding I'm not very good at. I've been following a tutorial and my question is what is my code so far doing, just making tables and inserting right? And what would the code I'm not using below do? Also if someone has a nice tutorial for how to continue?
package com...;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Date;
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper sInstance;
public static final String DATABASE_NAME = "data.db";
// Table names
public static final String TABLE_MAP = "map_data";
public static final String TABLE_CONTACT = "contact_data";
public static final String TABLE_USER = "user_data";
public static final String TABLE_GROUP = "group_data";
//public static final String TABLE_MESSAGES = "messages_data";
// Map columns
public static final String KEY_MAP_ID = "id";
public static final String KEY_MAP_LONG = "longitude";
public static final String KEY_MAP_LAT = "latitude";
public static final String KEY_MAP_GROUP = "group";
public static final String KEY_MAP_PRIO = "prio";
public static final String KEY_MAP_STATUS = "status";
public static final String KEY_MAP_TEXT = "text";
// Contact columns
public static final String KEY_CONTACT_ID = "id";
public static final String KEY_CONTACT_NAME = "name";
public static final String KEY_CONTACT_SURNAME = "surname";
public static final String KEY_CONTACT_PHONE = "phone";
public static final String KEY_CONTACT_USER = "user";
public static final String KEY_CONTACT_LONG = "longitude";
public static final String KEY_CONTACT_LAT = "latitude";
public static final String KEY_CONTACT_ADRESS = "adress";
public static final String KEY_CONTACT_ZIPCODE = "zipcode";
public static final String KEY_CONTACT_TOWN = "town";
public static final String KEY_CONTACT_TIMESTAMP = "when_created";
// User columns
public static final String KEY_USER_ID = "id";
public static final String KEY_USER_USER = "user";
public static final String KEY_USER_CRYPTOKEY = "cryptokey";
public static final String KEY_USER_PHONE = "phone_unit";
public static final String KEY_USER_UPDATED = "updated_at";
public static final String KEY_USER_CREATED = "created_at";
// Group columns
public static final String KEY_GROUP_ID = "id";
public static final String KEY_GROUP_NAME = "name";
public static final String KEY_GROUP_USERS = "users";
public static final String KEY_GROUP_INCHARGE = "incharge";
// Message columns
//public static final String KEY_MESSAGES_SENDER = "sender";
//public static final String KEY_MESSAGES_RECIEVER = "reciever";
//public static final String KEY_MESSAGES_MESSAGE = "message";
public static synchronized DatabaseHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
if (sInstance == null) {
sInstance = new DatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_MAP_TABLE = "CREATE TABLE" + TABLE_MAP + "(" +
KEY_MAP_ID + "INTEGER PRIMARY KEY," + // Defines a primary key
KEY_MAP_GROUP + "INTEGER REFERENCES" + TABLE_GROUP + "," + //Defines a foreign key
KEY_MAP_LAT + "DOUBLE" +
KEY_MAP_LONG + "DOUBLE" +
KEY_MAP_PRIO + "INTEGER" +
KEY_MAP_STATUS + "TEXT" +
KEY_MAP_TEXT + "TEXT" +
")";
String CREATE_CONTACT_TABLE = "CREATE TABLE" + TABLE_CONTACT + "(" +
KEY_CONTACT_ID + "INTEGER PRIMARY KEY," + // Defines a primary key
KEY_CONTACT_USER + "INTEGER REFERENCES" + TABLE_GROUP + "," + // Defines a foreign key
KEY_CONTACT_LAT + "DOUBLE" +
KEY_CONTACT_LONG + "DOUBLE" +
KEY_CONTACT_NAME + "TEXT" +
KEY_CONTACT_SURNAME + "TEXT" +
KEY_CONTACT_PHONE + "INTEGER" +
KEY_CONTACT_TIMESTAMP + "DATE" +
KEY_CONTACT_TOWN + "TEXT" +
KEY_CONTACT_ZIPCODE + "INTEGER" +
KEY_CONTACT_ADRESS + "TEXT" +
")";
String CREATE_USER_TABLE = "CREATE TABLE" + TABLE_USER + "(" +
KEY_USER_ID + "INTEGER PRIMARY KEY," + // Defines a primary key
KEY_USER_USER + "INTEGER" +
KEY_USER_CREATED + "DATE" +
KEY_USER_UPDATED + "DATE" +
KEY_USER_CRYPTOKEY + "TEXT" +
KEY_USER_PHONE + "INTEGER" +
")";
String CREATE_GROUP_TABLE = "CREATE TABLE" + TABLE_GROUP + "(" +
KEY_GROUP_ID + "INTEGER PRIMARY KEY," + // Defines a primary key
KEY_GROUP_NAME + "TEXT" +
KEY_GROUP_USERS + "INTEGER" +
KEY_GROUP_INCHARGE + "INTEGER" +
")";
/*
String CREATE_MESSAGES_TABLE = "CREATE TABLE" + TABLE_MESSAGES + "(" +
KEY_MESSAGES_SENDER + "INTEGER" +
KEY_MESSAGES_RECIEVER + "INTEGER" +
KEY_MESSAGES_MESSAGE + "TEXT" +
")";
*/
db.execSQL(CREATE_MAP_TABLE);
db.execSQL(CREATE_CONTACT_TABLE);
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_GROUP_TABLE);
//db.execSQL(CREATE_MESSAGES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MAP);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_GROUP);
//db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
onCreate(db);
}
}
// Insert a mapData into the database
public void addMapData(mapData map) {
// Create and/or open the database for writing
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
// The user might already exist in the database (i.e. the same user created multiple posts).
//int userId = (int) addOrUpdateUser(post.user);
ContentValues values = new ContentValues();
values.put(KEY_MAP_ID, map.getId());
values.put(KEY_MAP_LAT, map.getLatitude());
values.put(KEY_MAP_LONG, map.getLongitude());
values.put(KEY_MAP_GROUP, map.getGroup());
values.put(KEY_MAP_PRIO, map.getPrio());
values.put(KEY_MAP_STATUS, map.getStatus());
values.put(KEY_MAP_TEXT, map.getText());
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
db.insertOrThrow(TABLE_MAP, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("Debug TAG", "Error while trying to add mapData to database");
} finally {
db.endTransaction();
}
}
// Insert a mapData into the database
public void addContactData(contactData contact) {
// Create and/or open the database for writing
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
// The user might already exist in the database (i.e. the same user created multiple posts).
//int userId = (int) addOrUpdateUser(post.user);
ContentValues values = new ContentValues();
values.put(KEY_CONTACT_ID, contact.getId());
values.put(KEY_CONTACT_LAT, contact.getLatitude());
values.put(KEY_CONTACT_LONG, contact.getLongitude());
values.put(KEY_CONTACT_NAME, contact.getName());
values.put(KEY_CONTACT_SURNAME, contact.getSurname());
values.put(KEY_CONTACT_PHONE, contact.getPhone());
values.put(KEY_CONTACT_ADRESS, contact.getAdress());
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
db.insertOrThrow(TABLE_CONTACT, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("Debug TAG", "Error while trying to add contactData to database");
} finally {
db.endTransaction();
}
}
// Insert a User into the database
public void addUser(User user) {
// Create and/or open the database for writing
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
// The user might already exist in the database (i.e. the same user created multiple posts).
//int userId = (int) addOrUpdateUser(post.user);
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user.getId());
values.put(KEY_USER_USER, user.getUser());
values.put(KEY_USER_PHONE, user.getPhoneUnit());
values.put(KEY_USER_CRYPTOKEY, user.getCryptoKey());
values.put(KEY_USER_CREATED, String.valueOf(user.getCreated_at()));
values.put(KEY_USER_UPDATED, String.valueOf(user.getCreated_at()));
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
db.insertOrThrow(TABLE_USER, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("Debug TAG", "Error while trying to add user to database");
} finally {
db.endTransaction();
}
}
public void addGroup(Group group) {
// Create and/or open the database for writing
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
// The user might already exist in the database (i.e. the same user created multiple posts).
//int userId = (int) addOrUpdateUser(post.user);
ContentValues values = new ContentValues();
values.put(KEY_GROUP_ID, group.getId());
values.put(KEY_GROUP_USERS, group.getUser());
values.put(KEY_GROUP_INCHARGE, group.getIncharge());
values.put(KEY_GROUP_NAME, group.getName());
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
db.insertOrThrow(TABLE_GROUP, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("Debug TAG", "Error while trying to add group to database");
} finally {
db.endTransaction();
}
}
Not using the code below, cuz I don't know what it does.
/*
// Insert or update a user in the database
// Since SQLite doesn't support "upsert" we need to fall back on an attempt to UPDATE (in case the
// user already exists) optionally followed by an INSERT (in case the user does not already exist).
public long addOrUpdateContact(contactData contact) {
// The database connection is cached so it's not expensive to call getWriteableDatabase() multiple times.
SQLiteDatabase db = getWritableDatabase();
long userId = -1;
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(KEY_CONTACT_ID, contact.getId());
values.put(KEY_CONTACT_LAT, contact.getLatitude());
values.put(KEY_CONTACT_LONG, contact.getLongitude());
values.put(KEY_CONTACT_NAME, contact.getName());
values.put(KEY_CONTACT_SURNAME, contact.getSurname());
values.put(KEY_CONTACT_PHONE, contact.getPhone());
values.put(KEY_CONTACT_ADRESS, contact.getAdress());
// First try to update the user in case the user already exists in the database
// This assumes userNames are unique
int rows = db.update(TABLE_CONTACT, values, KEY_CONTACT_ID + "= ?", new String[]{String.valueOf(contact.getId())});
// Check if update succeeded
if (rows == 1) {
// Get the primary key of the user we just updated
String usersSelectQuery = String.format("SELECT %s FROM %s WHERE %s = ?",
KEY_USER_ID, TABLE_USER, KEY_USER_ID);
Cursor cursor = db.rawQuery(usersSelectQuery, new String[]{String.valueOf(user.id)});
try {
if (cursor.moveToFirst()) {
userId = cursor.getInt(0);
db.setTransactionSuccessful();
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
} else {
// user with this userName did not already exist, so insert new user
userId = db.insertOrThrow(TABLE_USER, null, values);
db.setTransactionSuccessful();
}
} catch (Exception e) {
Log.d("TAG", "Error while trying to add or update user");
} finally {
db.endTransaction();
}
return userId;
} */
}
Aucun commentaire:
Enregistrer un commentaire