I've founde already a few answers to this topic (for example this), but it is not working. I only get the warning, that it cannot resolve the method 'openOrCreateDatabase(java.lang.String, int, null)'.
Here is my sourcecode:
public class DBHandler
{
SQLiteDatabase database;
DBHandler()
{
database = openOrCreateDatabase("DatabaseName", Context.MODE_PRIVATE, null);
}
}
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
Please check below links
Android SQLite Database Tutorial
SQLite Database Tutorial
SQLite and Android
Structure
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}
}
As the commenter has given you the example, you will need to create a subclass of SQLiteOpenHelper class and override the onCreate and onUpgrade methods which will create your database and tables. Then you can use the method getReadableDatabase( ) or getWritableDatabase() of this helper class to get copy of a SQLite database. You can execute the queries on this object.
The code snippet below demonstrates it.
public class DBAdapter {
private SQLiteDatabase database;
private Context context;
private DatabaseHelper dbHelper;
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLES_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST "+TABLE_QUERY);
}
}
public DBAdapter(Context ctx) {
this.context = ctx;
}
public DBAdapter open() throws SQLException {
dbHelper = new DatabaseHelper(context, DBNAME, null,DBVERSION);
database = dbHelper.getWritableDatabase();
return this;
}
public Cursor executeQuery() {
Cursor result = database.rawQuery(YOUR_QUERY, null);
return result;
}
}
Use SQLite Open Helper developers guide for more help.
public class Sqlhelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
public static final String KEY_ROWID = "_id";
public static final String KEY_FNAME = "firstname";
Sqlhelper DB = null;
private static final String DATABASE_NAME = "dbname.db";
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_TABLE_NAME = "db";
private static final String DATABASE_TABLE_CREATE =
"CREATE TABLE " + DATABASE_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"firstname TEXT NOT NULL);";
public Sqlhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_TABLE_CREATE);
Log.d("DATABASE", "Table Was Created");
}catch(Exception e){
e.printStackTrace();
}
}
public void open() {
getWritableDatabase();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
Log.d("DATABASE", "Table Was UPDATED");
}
Create "database" name package and include it
Create SQLitHelper name class
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLitHelper extends SQLiteOpenHelper {
public static final String DataBase_Name = "ABC";
public static final int Version = 1;
public static final String TblUser = "TblUser";
public static final String TblClassList = "TblClassList";
public static final String TblStudentList = "TblStudentList";
public SQLitHelper(Context context) {
super(context, DataBase_Name, null, Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TblUser +
"(id INTEGER PRIMARY KEY," +
"uid INTEGER," +
"fname TEXT," +
"lname TEXT," +
"email TEXT," +
"password TEXT," +
"teacher TEXT," +
"student TEXT," +
"parent TEXT," +
"status TEXT," +
"landing_page TEXT," +
"createdate TEXT," +
"birthdate TEXT," +
"profilepic TEXT," +
"phone TEXT," +
"address TEXT," +
"gender TEXT," +
"age TEXT," +
"googleid TEXT," +
"facebookid TEXT," +
"alert_time TEXT," +
"sch_name TEXT,"+
"login_with TEXT,"+
"default_zone TEXT)");
db.execSQL("Create table " + TblClassList +
"(id INTEGER PRIMARY KEY," +
"cid INTEGER," +
"uid INTEGER," +
"title TEXT," +
"color TEXT," +
"startdate TEXT," +
"enddate TEXT," +
"qrcode TEXT," +
"createdate TEXT," +
"not_submitted_count TEXT," +
"status TEXT," +
"extra1 TEXT," +
"extra2 TEXT)");
db.execSQL("Create table " + TblStudentList +
"(id INTEGER PRIMARY KEY," +
"uid INTEGER," +
"cid INTEGER," +
"fname TEXT," +
"lname TEXT," +
"email TEXT," +
"profilepic TEXT," +
"student_name TEXT," +
"isleader TEXT," +
"add_homework TEXT," +
"track_submission TEXT," +
"status TEXT," +
"edit_homework TEXT," +
"del_homework TEXT," +
"last_access TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Create DataHelper class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
public class DataHelper {
SQLitHelper sqLitHelper;
SQLiteDatabase sqLiteDatabase;
Context context;
final String TAG = "DataHelper";
public DataHelper(Context context) {
sqLitHelper = new SQLitHelper(context);
this.context = context;
sqLiteDatabase = sqLitHelper.getWritableDatabase();
}
public void open() {
try {
sqLiteDatabase = sqLitHelper.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
sqLiteDatabase.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void insertUser(HashMap<String, String> list) {
ContentValues values = new ContentValues();
open();
try {
for (String str : list.keySet())
values.put(str, list.get(str));
long rowId = sqLiteDatabase.insert(SQLitHelper.TblUser, null, values);
} catch (Exception e) {
Log.e(TAG, "insertUser " + e.toString());
} finally {
close();
}
}
public void updateUser(HashMap<String, String> list, int uid) {
ContentValues values = new ContentValues();
open();
try {
for (String str : list.keySet())
values.put(str, list.get(str));
long rows = sqLiteDatabase.update(SQLitHelper.TblUser, values, "uid=" + uid, null);
} catch (Exception e) {
Log.e(TAG, "insertUser " + e.toString());
} finally {
close();
}
}
public int getUserRecordCount() {
int count = 0;
try {
open();
Cursor cursor = sqLiteDatabase.rawQuery("Select * from " + SQLitHelper.TblUser, null);
count = cursor.getCount();
cursor.close();
} catch (Exception e) {
Logger.debugLog(TAG, "userCount : " + e.toString());
} finally {
close();
}
return count;
}
public HashMap<String,String> getUserDetail(){
HashMap<String, String> list = new HashMap<>();
Cursor cursor = null;
try {
open();
cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + SQLitHelper.TblUser, null);
if (cursor.getColumnCount() > 0) {
while (cursor.moveToNext()) {
list.put("uid", cursor.getString(cursor.getColumnIndex("uid")));
list.put("fname", cursor.getString(cursor.getColumnIndex("fname")));
list.put("lname", cursor.getString(cursor.getColumnIndex("lname")));
list.put("default_zone", cursor.getString(cursor.getColumnIndex("default_zone")));
list.put("teacher", cursor.getString(cursor.getColumnIndex("teacher")));
list.put("student", cursor.getString(cursor.getColumnIndex("student")));
list.put("parent", cursor.getString(cursor.getColumnIndex("parent")));
list.put("email", cursor.getString(cursor.getColumnIndex("email")));
list.put("gender", cursor.getString(cursor.getColumnIndex("gender")));
list.put("birthdate", cursor.getString(cursor.getColumnIndex("birthdate")));
list.put("profilepic", cursor.getString(cursor.getColumnIndex("profilepic")));
list.put("sch_name", cursor.getString(cursor.getColumnIndex("sch_name")));
list.put("login_with", cursor.getString(cursor.getColumnIndex("login_with")));
}
}
} catch (Exception e) {
Logger.debugLog(TAG, "getUserDetail : " + e.toString());
} finally {
close();
if (cursor != null)
if (!cursor.isClosed())
cursor.close();
}
return list;
}
public boolean deleteUserList() {
try {
open();
if (sqLiteDatabase.delete(SQLitHelper.TblUser, null, null) > 0){
return true;
}else {
return false;
}
} catch (Exception e) {
Logger.debugLog(TAG, "deleteUserList : " + e.toString());
} finally {
close();
}
return false;
}
public boolean insertClassList(MClassList mClassList) {
try {
open();
ContentValues contentValues = new ContentValues();
contentValues.put("cid", mClassList.getId());
contentValues.put("uid", mClassList.getUid());
contentValues.put("title", mClassList.getTitle());
contentValues.put("color", mClassList.getColor());
contentValues.put("startdate", mClassList.getStartdate());
contentValues.put("enddate", mClassList.getEnddate());
contentValues.put("qrcode", mClassList.getQrcode());
contentValues.put("createdate", mClassList.getCreatedate());
contentValues.put("status", mClassList.getStatus());
contentValues.put("not_submitted_count", mClassList.getNot_sub_count());
long id = sqLiteDatabase.insert(SQLitHelper.TblClassList, null, contentValues);
Logger.debugLog(TAG, "insertClassList : Sus");
return true;
} catch (Exception e) {
Logger.debugLog(TAG, "insertClassList : " + e.toString());
} finally {
close();
}
return false;
}
public ArrayList<MClassList> getClassList() {
ArrayList<MClassList> clssArrayList = new ArrayList<>();
Cursor cursor = null;
try {
open();
String Query = QueryBuilder.classListQuery();
cursor = sqLiteDatabase.rawQuery(Query, null);
if (cursor.getColumnCount() > 0) {
while (cursor.moveToNext()) {
MClassList mClassList = new MClassList();
mClassList.setId(cursor.getInt(cursor.getColumnIndex("cid")));
mClassList.setUid(cursor.getInt(cursor.getColumnIndex("uid")));
mClassList.setTitle(cursor.getString(cursor.getColumnIndex("title")));
mClassList.setColor(cursor.getString(cursor.getColumnIndex("color")));
mClassList.setStartdate(cursor.getString(cursor.getColumnIndex("startdate")));
mClassList.setEnddate(cursor.getString(cursor.getColumnIndex("enddate")));
mClassList.setQrcode(cursor.getString(cursor.getColumnIndex("qrcode")));
mClassList.setCreatedate(cursor.getString(cursor.getColumnIndex("createdate")));
mClassList.setStatus(cursor.getString(cursor.getColumnIndex("status")));
mClassList.setNot_sub_count(cursor.getString(cursor.getColumnIndex("not_submitted_count")));
clssArrayList.add(mClassList);
}
}
} catch (Exception e) {
Logger.debugLog(TAG, "getClassList : " + e.toString());
} finally {
close();
if (cursor != null)
if (!cursor.isClosed())
cursor.close();
}
return clssArrayList;
}
public boolean deleteClassList() {
try {
open();
if (sqLiteDatabase.delete(SQLitHelper.TblClassList, null, null) > 0){
return true;
}else {
return false;
}
} catch (Exception e) {
Logger.debugLog(TAG, "deleteClassList : " + e.toString());
} finally {
close();
}
return false;
}
public boolean deleteStudentList() {
try {
open();
if (sqLiteDatabase.delete(SQLitHelper.TblStudentList, null, null) > 0){
return true;
}
else{
return false;
}
} catch (Exception e) {
Logger.debugLog(TAG, "deleteStudentList : " + e.toString());
} finally {
close();
}
return false;
}
public void deleteStudent(int cid,int uid) {
try {
open();
sqLiteDatabase.delete(SQLitHelper.TblStudentList, "uid=" + uid + " AND cid=" + cid, null);
} catch (Exception e) {
Logger.debugLog(TAG, "deleteStudent : " + e.toString());
} finally {
close();
}
}
}
Create class QueryBuilder
public class QueryBuilder {
public static String teacherABCList(int cid) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formatDate = df.format(c.getTime()).toString();
String Query = "SELECT * FROM " + SQLitHelper.TblTeacherHomeworkAll + " WHERE cid='" + cid + "'" + " AND duedate>= " +"'"+ formatDate+"'" + " ORDER BY duedate DESC ";
return Query;
}
==============================
public static String studentXXXListQuery(int uid,String status) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formatDate = df.format(c.getTime()).toString();
String Query = "SELECT * FROM " + SQLitHelper.TblStudentHomeworkAll + " WHERE uid='" + uid + "'" + " AND status= " +"'"+ status+"'"+" AND isDone='N'" + " ORDER BY duedate DESC ";
return Query;
}
===========================================
public static String studentListQuery(String questionID) {
String query = "SELECT * FROM " + SQLitHelper.TblStudentCheckAnswer + " WHERE qid=" + questionID;
return query;
}
}
use below example to create database
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ayconsultancy.sumeshmedicals.SumeshMedicalContext;
import com.ayconsultancy.sumeshmedicals.model.PlaceModel;
import com.ayconsultancy.sumeshmedicals.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Admin33 on 16-02-2016.
*/
public class DBHelper extends SQLiteOpenHelper {
static String DATABASE_NAME = "sumesh_medicals";
static int DATABASE_VERSION = 1;
static DBHelper dbHelperInstance;
static SQLiteDatabase db;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance() {
if (dbHelperInstance == null) {
dbHelperInstance = new DBHelper(SumeshMedicalContext.getContext());
}
return dbHelperInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
Utils.ShowLogD("in sqlite oncreate");
try {
db.execSQL(DBQueries.CREATE_OTC_TABLE);
db.execSQL(DBQueries.CREATE_SHOP_DETAILS_TABLE);
db.execSQL(DBQueries.CREATE_USER_DETAILS_TABLE);
db.execSQL(DBQueries.CREATE_CITY_TABLE);
} catch (Exception e) {
e.printStackTrace();
}
// insertIntoShopDetails(db);
// insertIntoOTcPrescrion(db);
}
public synchronized SQLiteDatabase getDababase() {
if (db == null || (db != null && !db.isOpen())) {
db = this.getWritableDatabase();
}
return db;
}
public synchronized void close() {
super.close();
if (db != null)
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
to save data into sqlite use following first in main
public class MainActivity extends AppCompatActivity {
String one,two;
EditText name,phone;
Button saveButton;
List<StudentModel> list = new ArrayList<StudentModel>();
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(getApplicationContext());
saveButton=(Button)findViewById(R.id.submit);
name=(EditText)findViewById(R.id.textName);
phone=(EditText)findViewById(R.id.textPhone);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StudentModel student = new StudentModel();
student.name = name.getText().toString();
student.phone_number = phone.getText().toString();
db.addStudentDetail(student);
list = db.getAllStudentsList();
print(list);
}
});
}
private void print(List<StudentModel> list) {
String value = "";
for(StudentModel sm : list){
value = value+"id: "+sm.id+", name: "+sm.name+" Ph_no: "+sm.phone_number+"\n";
}
Log.i("<<<<<<<<<<",value);
}
}
then create handler class
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Name
public static String DATABASE_NAME = "student_database";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_STUDENTS = "students";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PHONENUMBER = "phone_number";
public static String TAG = "tag";
private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE "
+ TABLE_STUDENTS + "(" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ KEY_PHONENUMBER + " TEXT );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENTS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_STUDENTS);
onCreate(db);
}
public long addStudentDetail(StudentModel student) {
SQLiteDatabase db = this.getWritableDatabase();
// Creating content values
ContentValues values = new ContentValues();
values.put(KEY_NAME, student.name);
values.put(KEY_PHONENUMBER, student.phone_number);
// insert row in students table
long insert = db.insert(TABLE_STUDENTS, null, values);
return insert;
}
public int updateEntry(StudentModel student) {
SQLiteDatabase db = this.getWritableDatabase();
// Creating content values
ContentValues values = new ContentValues();
values.put(KEY_NAME, student.name);
values.put(KEY_PHONENUMBER, student.phone_number);
return db.update(TABLE_STUDENTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(student.id) });
}
public void deleteEntry(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_STUDENTS, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
}
public StudentModel getStudent(long id) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_STUDENTS + " WHERE "
+ KEY_ID + " = " + id;
Log.d(TAG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
StudentModel students = new StudentModel();
students.id = c.getInt(c.getColumnIndex(KEY_ID));
students.phone_number = c.getString(c.getColumnIndex(KEY_PHONENUMBER));
students.name = c.getString(c.getColumnIndex(KEY_NAME));
return students;
}
public List<StudentModel> getAllStudentsList() {
List<StudentModel> studentsArrayList = new ArrayList<StudentModel>();
String selectQuery = "SELECT * FROM " + TABLE_STUDENTS;
Log.d(TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
StudentModel students = new StudentModel();
students.id = c.getInt(c.getColumnIndex(KEY_ID));
students.phone_number = c.getString(c
.getColumnIndex(KEY_PHONENUMBER));
students.name = c.getString(c.getColumnIndex(KEY_NAME));
studentsArrayList.add(students);
} while (c.moveToNext());
}
return studentsArrayList;
}
}
then set and get the values
public class StudentModel {
public int id;
public String name;
public String phone_number;
public StudentModel(int id, String name, String phone_number) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
this.phone_number = phone_number;
}
public StudentModel(){
}
}
try it
Here is my code how to use sqlite database
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "loginDB.db", null, 1);
getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String query = "create table registration (id INTEGER,Image BLOB,firstname VARCHAR,Lastname VARCHAR,DateOfBirth VARCHAR,Phone VARCHAR,Gender VARCHAR, Email VARCHAR primary key,Password VARCHAR);";
sqLiteDatabase.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
//method for insert data
public boolean insertRecord(byte[] imageInByte,String fn) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Image", imageInByte);
contentValues.put("Firstname", fn);
db.insert("signup", null, contentValues);
return true;
}
public boolean updaterecord(String fn,String ln,String unme){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Firstname", fn);
contentValues.put("Lastname", ln);
contentValues.put("Username", unme);
return db.update(TABLE_NAME, contentValues, "Username = ?", new String[]{(unme)}) > 0;
}
public boolean deleterecord(String FirstName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "Firstname = ?", new String[]{FirstName}) > 0;
}
public int displayDetail(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from registration where Email='" + email + "'AND Password='" + password + "'", null);
return cursor.getCount();
}
public ArrayList displayDetails(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from registration where Email='" + email + "'AND Password='" + password + "'", null);
ArrayList<ModelClass> arrayList = new ArrayList();
ModelClass model;
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
model = new Model();
model.setFirstname(cursor.getString(cursor.getColumnIndex("Firstname")));
model.setLastname(cursor.getString(cursor.getColumnIndex("Lastname")));
arrayList.add(model);
}
}
}
return arrayList;
}
}
Here is complete code for SQLite database and basic query.
public class SqliteHelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
private Context mContext;
public static final String DATABASE_NAME = "DemoDB";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_USERS = "users";
public static final String USER_ID = "id";
public static final String USER_NAME = "username";
public static final String USER_EMAIL = "email";
public static final String USER_PASSWORD = "password";
public static final String CREATE_QUERY_USER_TABLE = " CREATE TABLE " + TABLE_USERS
+ " ( "
+ USER_ID + " INTEGER PRIMARY KEY, "
+ USER_NAME + " TEXT, "
+ USER_EMAIL + " TEXT, "
+ USER_PASSWORD + " TEXT"
+ " ) ";
public SqliteHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
}
// Method to openthe Database
public void openDataBase() throws SQLException {
db = getWritableDatabase();
}
// Method to close the Database
public void close() {
if (db != null && db.isOpen()) {
db.close();
}
}
public boolean isEmailExists(String email) {
boolean isUserFound = false;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users WHERE email = ?", new String[]{email.trim()});
if (cursor != null) {
if(cursor.getCount() > 0) {
isUserFound = true;
}
cursor.close();
}
return isUserFound;
}
public void addUser(User user) {
ContentValues values = new ContentValues();
values.put(USER_NAME, user.userName);
values.put(USER_EMAIL, user.email);
values.put(USER_PASSWORD, user.password);
long todo_id = db.insert(TABLE_USERS, null, values);
}
public boolean login(User user) {
boolean isLogin = false;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users WHERE email = ?", new String[]{user.email.trim()});
if (cursor != null) {
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
String pass = cursor.getString(cursor.getColumnIndex(USER_PASSWORD));
if (pass != null && user.password.equalsIgnoreCase(pass.trim())) {
isLogin = true;
}
}
cursor.close();
}
return isLogin;
}
}
I am trying to create a SQLite DB for my android app. I have all the code but I am getting an error in the logcat saying that the no such table. I think I have the correct code but would appreciate it if you could take a look and see if I am missing something.
package com.example.rory.dbtest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_ITEM = "item";
public static final String KEY_LITRES = "litres";
//public static final String KEY_COURSE = "course";
//public static final String KEY_NOTES = "notes";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "DripDrop";
private static final String DATABASE_TABLE = "table1";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "item VARCHAR not null, litres date );";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String item, String litres)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM, item);
initialValues.put(KEY_LITRES, litres);
//initialValues.put(KEY_COURSE, course);
//initialValues.put(KEY_NOTES, notes);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records---
public Cursor getAllRecords()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_ITEM,
KEY_LITRES}, null, null, null, null, null);
}
//---retrieves a particular record---
public Cursor getRecord(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_ITEM, KEY_LITRES},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a record---
public boolean updateRecord(long rowId, String item, String litres)
{
ContentValues args = new ContentValues();
args.put(KEY_ITEM, item);
args.put(KEY_LITRES, litres);
//args.put(KEY_COURSE, course);
//args.put(KEY_NOTES, notes);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
And the logcat error after the app crashes is: (Sorry about the formatting I couldn't get it right at all).
package com.pinchtapzoom;
Caused by: android.database.sqlite.SQLiteException: no such table: table1 (code 1): , while compiling: SELECT id, item, litres FROM table1
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
It seems that you want to create table name as assignments and accessing data from table1.So change
private static final String DATABASE_TABLE = "table1";
to
private static final String DATABASE_TABLE = "assignments";
Take a look at your table's name :
private static final String DATABASE_TABLE = "table1";
And your query :
"create table if not exists assignments bla bla"
They are not same, thats why you get this error.
You will need to change one of them so the name will be same.
I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.
I am using SQLite in Android eclipse, however it gives me a java.lang.nullpointerexception in the function createEntry. I tried using Questoid SQLite manager to view the database file and it does show up with the table created. Where's the bug?
public class Transact {
public static final String KEY_ROWID = "_id";
public static final String KEY_TAG = "saved_tag";
private static final String DATABASE_NAME = "MyDatabaseName";
private static final String DATABASE_TABLE = "tagsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TAG + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Transact(Context c ){
ourContext = c;
}
public Transact open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String tagword) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TAG, tagword);
return ourDatabase.insert(DATABASE_TABLE, "", cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_TAG};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTag = c.getColumnIndex(KEY_TAG);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iTag) + "\n";
}
return null;
}
}
Code for the add button from Main.java class:
case R.id.addDB:
boolean doneAdd = true;
try{
String tag = textTag.getText().toString();
Transact entry = new Transact(Main.this);
entry.open();
entry.createEntry(tag);
entry.close();
}catch(Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
doneAdd = false;
}finally{
if(doneAdd){
Dialog d = new Dialog(this);
d.setTitle("Addition done");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
You are using ourDatabase variable without initializing it. So not only insert you will get nullpointerexception everywhere where you are using ourDatabase variable
you can use something like following in constructor.
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
used this code in sq light java file
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
Cursor cursor;
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 2;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
public static final String KEY_CONTENT4 = "Content4";
public static final String KEY_CONTENT5 = "Content5";
public static final String KEY_CONTENT6 = "Content6";
public static final String KEY_CONTENT7 = "Content7";
public static final String KEY_CONTENT8 = "Content8";
public static final String KEY_CONTENT9 = "Content9";
public static final String KEY_CONTENT10 = "Content10";
public static final String KEY_CONTENT11 = "Content11";
public static final String KEY_CONTENT12 = "Content12";
// create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_CONTENT1
+ " text not null, " + KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + " text not null, " + KEY_CONTENT4
+ " text not null, " + KEY_CONTENT5 + " text not null, "
+ KEY_CONTENT6 + " text not null, " + KEY_CONTENT7
+ " text not null, " + KEY_CONTENT8 + " text not null, "
+ KEY_CONTENT9 + " text not null, " + KEY_CONTENT10
+ " text not null, " + KEY_CONTENT11 + " blob not null, "
+ KEY_CONTENT12 + " long not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c) {
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("PRAGMA foreign_keys=ON");
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
I was wondering how i would search for specific information stored into my database. Lets say i wanted to search for the information stored in iName, how would i do so? would i need to do some sort of sql query.
Sorry for such a basic question but im new to the whole android scene . Thank You
package f.s.l;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class HotOrNot {
public static final String KEY_ROWID ="_id";
public static final String KEY_NAME ="persons_name";
public static final String KEY_HOTNESS ="persons_hotness";
private static final String DATABASE_NAME ="HotOrNotdb";
private static final String DATABASE_TABLE ="peopleTable";
private static final int DATABASE_VERSION =1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public HotOrNot(Context c){
ourContext =c;
}
public HotOrNot open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String [] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " "+ c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
You need to write a function like the getData() you already have, but pass it the name... For example:
public Cursor getData(String name) {
...
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=?", new String[] { name }, null, null, null);
...
}