Android NullPointerExceptions in inserting data - java

i follow this example
it works fine, but as i modified the inserting methode, i got NullpointerException in this line:
return DB.insert(tableName, null, initialValues);
tableName is assigned and initialValues also. i don't know why i got NullpointerException.
my code:
public class MainActivity extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
InsertTheData();
openAndQueryDatabase();
displayResultList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void InsertTheData()
{
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
dbHelper.insertSomeItmes();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(getClass().getSimpleName(), "Could not Insert data");
}
finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
and DbHelper class:
public class DBHelper extends SQLiteOpenHelper {
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "sample";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "Resource";
public static final String KEY_LastName = "LastName";
public static final String KEY_FirstName = "FirstName";
public static final String KEY_Country = "Country";
public static final String KEY_Age = "Age";
private static final String TAG = "Create_The_DB";
private static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " +
tableName + " ( "+ KEY_LastName + " VARCHAR, "+ KEY_FirstName +" VARCHAR," + KEY_Country + " VARCHAR,"+ KEY_Age +" INT(3))";
public DBHelper(Context context) {
//super(context, name, factory, version);
// TODO Auto-generated constructor stub
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.w(TAG, TABLE_CREATE);
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
} else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL(TABLE_CREATE);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CREATE);
onCreate(db);
}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public long createItmes(String LeLastName, String LeFirstName, String LeCountry, int LeAge) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_LastName, LeLastName);
initialValues.put(KEY_FirstName, LeFirstName);
initialValues.put(KEY_Country, LeCountry);
initialValues.put(KEY_Age, LeAge);
return DB.insert(tableName, null, initialValues);
}
public void insertSomeItmes() {
createItmes("AFG","Afghanistan","Asia",5);
createItmes("ALB","Albania","Europe",9);
createItmes("DZA","Algeria","Africa",52);
createItmes("AND","Andorra","Europe",55);
createItmes("AGO","Angola","Africa",63);
createItmes("AIA","Anguilla","North America",75);
}
}

I'm just guessing, but when you reach DBHelper#onCreate and if the DBHelper#checkDbExists returns true there might be possibility that the DB field is still unassigned.
You should have provided stack trace.

I have been read in somewhere is primary key is mandatory

Related

SQL Lite Data not being inserted (Android Studio in java)

I want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 + " TEXT" + COL3 + " ,TEXT)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!

How do I use SQLite in android?

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;
}
}

sqlite.SQLiteException: no such column. I checked on commas and spaces [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 7 years ago.
I cannot find the problem in my (Android) Java code.
The problem (according the logcat) is that there is no such column as reminder_date.
This is the error:
09-19 21:27:24.440 23689-23689/com.example.sanne.reminderovapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.sanne.reminderovapplication, PID: 23689
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sanne.reminderovapplication/com.example.sanne.reminderovapplication.MainActivity}: android.database.sqlite.SQLiteException: no such column: reminder_date (code 1): , while compiling: SELECT reminder_id AS _id , reminder_title , reminder_description , reminder_date FROM reminder
I checked for the commas and spaces.
I hope there is a solution for this problem.
This is my code of the MySQLiteHelper:
public class MySQLiteHelper extends SQLiteOpenHelper{
// Database info
private static final String DATABASE_NAME = "reminderOVApp.db";
private static final int DATABASE_VERSION = 8;
// Assignments
public static final String TABLE_REMINDER = "reminder";
public static final String COLUMN_REMINDER_ID = "reminder_id";
public static final String COLUMN_REMINDER_TITLE = "reminder_title";
public static final String COLUMN_REMINDER_DESCRIPTION = "reminder_description";
public static final String COLUMN_REMINDER_DATE = "reminder_date";
// Creating the table
private static final String DATABASE_CREATE_REMINDERS =
"CREATE TABLE " + TABLE_REMINDER +
"(" +
COLUMN_REMINDER_ID + " integer primary key autoincrement , " +
COLUMN_REMINDER_TITLE + " text not null , " +
COLUMN_REMINDER_DESCRIPTION + " text not null , " +
COLUMN_REMINDER_DATE + " text not null " +
");";
// Mandatory constructor which passes the context, database name and database version and passes it to the parent
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database)
{
// Execute the sql to create the table assignments
database.execSQL(DATABASE_CREATE_REMINDERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// When the database gets upgraded you should handle the update to make sure there is no data loss.
// This is the default code you put in the upgrade method, to delete the table and call the oncreate again.
if(oldVersion == 8)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDER);
onCreate(db);
}
}
And this is the code of the DataSource Class:
public class DataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] assignmentAllColumns = {MySQLiteHelper.COLUMN_REMINDER_ID, MySQLiteHelper.COLUMN_REMINDER_TITLE, MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION, MySQLiteHelper.COLUMN_REMINDER_DATE};
public DataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
database = dbHelper.getWritableDatabase();
dbHelper.close();
}
// Opens the database to use it
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
// Closes the database when you no longer need it
public void close() {
dbHelper.close();
}
//Add a reminder to the database
public long createReminder(String reminder_title, String reminder_description, String reminder_date) {
// If the database is not open yet, open it
if (!database.isOpen()) {
open();
}
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_REMINDER_TITLE, reminder_title);
values.put(MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION, reminder_description);
values.put(MySQLiteHelper.COLUMN_REMINDER_DATE, reminder_date);
// values.put(MySQLiteHelper.COLUMN_REMINDER_TIME, reminder_time);
long insertId = database.insert(MySQLiteHelper.TABLE_REMINDER, null, values);
// If the database is open, close it
if (database.isOpen()) {
close();
}
return insertId;
}
//Change data of the specific reminder
public void updateReminder(Reminder reminder) {
if (!database.isOpen()) {
open();
}
ContentValues args = new ContentValues();
args.put(MySQLiteHelper.COLUMN_REMINDER_TITLE, reminder.getTitle());
args.put(MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION, reminder.getDescription());
args.put(MySQLiteHelper.COLUMN_REMINDER_DATE, reminder.getDate());
database.update(MySQLiteHelper.TABLE_REMINDER, args, MySQLiteHelper.COLUMN_REMINDER_ID + "=?", new String[] { Long.toString(reminder.getId()) });
if (database.isOpen()) {
close();
}
}
//Delete a reminder from the database
public void deleteReminder(long id) {
if (!database.isOpen()) {
open();
}
database.delete(MySQLiteHelper.TABLE_REMINDER, MySQLiteHelper.COLUMN_REMINDER_ID + " =?", new String[]{Long.toString(id)});
if (database.isOpen()) {
close();
}
}
//Delete all reminders
public void deleteReminders() {
if (!database.isOpen()) {
open();
}
database.delete(MySQLiteHelper.TABLE_REMINDER, null, null);
if (database.isOpen()) {
close();
}
}
//This way you can get the id and the reminder from the cursor.
private Reminder cursorToReminder(Cursor cursor) {
try {
Reminder reminder = new Reminder();
reminder.setId(cursor.getLong(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_ID)));
reminder.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_TITLE)));
reminder.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION)));
reminder.setDate(cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_DATE)));
return reminder;
}catch(CursorIndexOutOfBoundsException exception) {
exception.printStackTrace();
return null;
}
}
//Get all the reminders to populate the listView --> ArrayList
public List<Reminder> getAllReminders() {
if (!database.isOpen()) {
open();
}
List<Reminder> reminders = new ArrayList<Reminder>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_REMINDER, assignmentAllColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Reminder assignment = cursorToReminder(cursor);
reminders.add(assignment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
if (database.isOpen()) {
close();
}
return reminders;
}
//A SimpleCursorAdapter requires a Cursor to get the data from the database instead of an ArrayList.
public Cursor getAllAssignmentsCursor()
{
if (!database.isOpen()) {
open();
}
Cursor cursor = database.rawQuery(
"SELECT " +
MySQLiteHelper.COLUMN_REMINDER_ID + " AS _id , " +
MySQLiteHelper.COLUMN_REMINDER_TITLE + " , " +
MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION + " , " +
MySQLiteHelper.COLUMN_REMINDER_DATE +
" FROM " + MySQLiteHelper.TABLE_REMINDER, null);
if (cursor != null) {
cursor.moveToFirst();
}
if (database.isOpen()) {
close();
}
return cursor;
}
//Get one reminder
public Reminder getReminder(long columnId) {
if (!database.isOpen()) {
open();
}
Cursor cursor = database.query(MySQLiteHelper.TABLE_REMINDER, assignmentAllColumns, MySQLiteHelper.COLUMN_REMINDER_ID + "=?", new String[] { Long.toString(columnId)}, null, null, null);
cursor.moveToFirst();
Reminder assignment = cursorToReminder(cursor);
cursor.close();
if (database.isOpen()) {
close();
}
return assignment;
}}
And my MainActivity Class:
public class AddActivity extends AppCompatActivity {
private DataSource datasource;
private EditText addReminderEditText;
private EditText descriptionEditText;
private EditText dateEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
datasource = new DataSource(this);
addReminderEditText = (EditText) findViewById(R.id.add_reminder_editText);
descriptionEditText = (EditText) findViewById(R.id.description_reminder_editText);
dateEditText = (EditText) findViewById(R.id.date_reminder_editText);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.add_assignment_menu_save) {
//Sending the data back to MainActivity
long reminderId = datasource.createReminder(addReminderEditText.getText().toString(), descriptionEditText.getText().toString(), dateEditText.getText().toString());
Intent resultIntent = new Intent();
resultIntent.putExtra(MainActivity.EXTRA_REMINDER_ID, reminderId);
setResult(Activity.RESULT_OK, resultIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}}
Well, it seems like reminder_date has been added after the first code execution.
Simply uninstall and reinstall your app.

Database values retrieval error - regarding

I am new to android, I am trying to retrieve values from a sqlite database based on the listview values. I tried to retrieve values using string variable. I can do this if I directly substitute the value in the place of variable.
Following this I post my codes kindly help me to sort out this.
DBhelper.java
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "VERIFY ME1.sqlite3";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "FORM2";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
Oninsert(DB);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
}
else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +tableName +" (AppNo VARCHAR, AppName VARCHAR," +
" Area VARCHAR, FHcode INT(3));");
}}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void Oninsert(SQLiteDatabase dB2) {
// TODO Auto-generated method stub
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("INSERT INTO " +
tableName +
" Values ('M001','shumi','India',250);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C002','sarah','India',251);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D003','Lavya','USA',252);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('V004','Avi','EU',253);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('T005','Shenoi','Bangla',254);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('L006','Lamha','Australia',255);");
DB.close();
}
}
ListActivity.java
public class login2 extends ListActivity implements OnItemClickListener {
private static final login2 ListActivity = null;
private static final AdapterView<?> parent = null;
private static int mPosition = 0;
private static final long id = 0;
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
private String AppName1,ApplID,FHcode,Area;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(this);
}
private String openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " +tableName +"", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
AppName1 = c.getString(c.getColumnIndex("AppName"));
results.add(AppName1 );
}while (c.moveToNext());
}
}
c.close();
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
// newDB.execSQL("DELETE FROM " + tableName);
//newDB.close();
}
return AppName1;
}
public void onClick(View arg0) {
login2 det = (login2)ListActivity;
det.onItemClick(parent, arg0, mPosition, id);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String data=(String)parent.getItemAtPosition(position);
//showMessage("Successfully", data);
if (data != null ) {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c1 = newDB.rawQuery("SELECT DISTINCT AppNo, AppName, FHcode, Area FROM "
+tableName +" where AppName ="+data+"" ,null);
if (c1 != null ) {
if (c1.moveToFirst()) {
do {
ApplID= c1.getString(c1.getColumnIndex("AppNo"));
String AppName =c1.getString(c1.getColumnIndex("AppName"));
Area = c1.getString(c1.getColumnIndex("Area"));
FHcode =c1.getString(c1.getColumnIndex("FHcode"));
Intent intent = new Intent(getApplicationContext(), form.class);
//Create a bundle object
Bundle b = new Bundle();
//Inserts a String value into the mapping of this Bundle
b.putString("AppName", AppName.toString());
b.putString("Apprefno", ApplID.toString());
b.putString("FHcode", FHcode.toString());
b.putString("Area", Area.toString());
//Add the bundle to the intent.
intent.putExtras(b);
//start the DisplayActivity
startActivity(intent);
}
while (c1.moveToNext());
}
}
}
catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
//newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
public void showMessage (String title, String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
You have taken this column as an integer FHcode INT(3)
and trying to fetch values as an string that is wrong
c1.getString(c1.getColumnIndex("FHcode")
change to c1.getInt**(c1.getColumnIndex("FHcode")

My program can not find tables in sqlite database on Android

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.

Categories

Resources