Android studio SQLite database data retrieval for specific entires - java

So I am making an itinerary type application where the user makes an itinerary and has multiple entries in one itinerary. So i need to be able to retrieve all the data from one itinerary. For example if the Itinerary is called Monday, and the user selected that one to view, i would want all the data from that. I've done this by having the ItineraryName, e.g. Monday, be passed through to another activity, which works but i've only seen through print statements to check the value has passed through correctly.
Currently i can view the data for a specific Itinerary, e.g. Monday, only if i manually input into the selection args variable(see below) but if i try pass it by a variable it wont work and i get an error, also i have tried putting "%" + ItineraryName + "%" into the selection args but i am presented with a blank activity. Error for just variable:
Process: com.example.chiraag.qavel, PID: 10198
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chiraag.qavel/com.example.chiraag.qavel.ItineraryDetails}: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.example.chiraag.qavel.DBManager.Query(DBManager.java:101)
at com.example.chiraag.qavel.ItineraryDetails.loadItinerary(ItineraryDetails.java:47)
at com.example.chiraag.qavel.ItineraryDetails.onCreate(ItineraryDetails.java:34)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Code for ItineraryDetails:
public class ItineraryDetails extends AppCompatActivity {
DBManager db;
myAdapter myAdapter;
ListView ls;
private String ItineraryName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_itinerary_details);
db = new DBManager(this);
ls = (ListView)findViewById(R.id.ItineraryDetails_listview);
loadItinerary();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Name");
System.out.println("Name " + ItineraryName);
}
public void loadItinerary(){
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
String []selectionargs = {ItineraryName};
Cursor cursor = db.Query("Itinerary",null, "ItineraryName like ?", selectionargs , DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
null
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, null
, null
, null
,cursor.getString(cursor.getColumnIndex(DBManager.ColTime))
,null,null, null, null
,null
,null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ls.setAdapter(myAdapter);
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
Adapter ac;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_items_itinerary_details, null);
ac = listItem.get(position);
TextView ItineraryName = (TextView) myView.findViewById(R.id.tvItineraryDetailsEntryName);
ItineraryName.setText(ac.Name);
TextView ItineraryLocation = (TextView) myView.findViewById(R.id.tvItineraryDetailsEntryLocation);
ItineraryLocation.setText(ac.Location);
TextView ItineraryTime = (TextView)myView.findViewById(R.id.tvItineraryDetailsEntryTime);
ItineraryTime.setText(ac.Time);
return myView;
}
}
}
Code for DBManager:
public class DBManager {
private SQLiteDatabase sqlDB;
static final String ColId = "ID";
static final String DBName = "InternalDB";
static final String TableName = "BookmarkAttraction";
static final String TableName2 = "BookmarkTransport";
static final String TableName3 = "Itinerary";
static final String ColItineraryName = "ItineraryName";
static final String ColDate = "Date";
static final String ColType = "Type";
static final String ColName = "Name";
static final String ColLocation = "Location";
static final String ColOpening = "OpeningTime";
static final String ColClosing = "ClosingTime";
static final String ColNearbyStop = "NerbyStop1";
static final String ColTime = "Time";
static final String ColNextStop = "NextStop";
static final String ColPhoneNumber = "PhoneNumber";
static final int DBVersion = 1;
static final String CreateTable = "CREATE TABLE IF NOT EXISTS " + TableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColType+ " TEXT," +
ColName+ " TEXT," + ColLocation+ " TEXT," + ColOpening+ " TEXT," +ColClosing+ " TEXT," + ColNearbyStop+ " TEXT);";
static final String CreateTabe2 = "CREATE TABLE IF NOT EXISTS " +TableName2 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ColType + " TEXT,"
+ ColName + " TEXT,"
+ ColLocation + " TEXT,"
+ ColTime+ " TEXT,"
+ ColNextStop + " TEXT,"
+ ColPhoneNumber + " TEXT);";
static final String CreateTable3 = "CREATE TABLE IF NOT EXISTS " + TableName3 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColItineraryName + " TEXT,"
+ ColDate + " TEXT," + ColName + " TEXT," + ColLocation + " TEXT," + ColTime + " TEXT);";
static class DBHelper extends SQLiteOpenHelper{
Context context;
DBHelper(Context context){
super(context, DBName, null, DBVersion);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
Toast.makeText(context,DBName,Toast.LENGTH_LONG).show();
db.execSQL(CreateTable);
Toast.makeText(context,"Table is created ", Toast.LENGTH_LONG).show();
db.execSQL(CreateTabe2);
Toast.makeText(context,"Transport table created", Toast.LENGTH_LONG).show();
db.execSQL(CreateTable3);
Toast.makeText(context,"Itin table created", Toast.LENGTH_LONG).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TableName);
db.execSQL("DROP TABLE IF EXISTS" + TableName2);
db.execSQL("DROP TABLE IF EXISTS" + TableName3);
onCreate(db);
}
}
public DBManager(Context context){
DBHelper db = new DBHelper(context);
sqlDB = db.getWritableDatabase();
}
public long Insert(String tablename,ContentValues values){
long ID = sqlDB.insert(tablename,"",values);
return ID;
}
public Cursor Query(String tablename, String [] projection, String selection, String [] selectionArgs, String sortOrder){
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tablename);
Cursor cursor = qb.query(sqlDB,projection, selection, selectionArgs,null,null,sortOrder);
return cursor;
}
public int Delete(String tablename,String selection, String[] selectionArgs){
int count = sqlDB.delete(tablename,selection,selectionArgs);
return count;
}
}
The error points to my query method in my DBManager class, I may have structured it wrong, i'm not sure because i first created it to retrieve all data from a table. Any help with this would be great thank you.

Looks like you're trying to bind the variable ItineraryName before it's been defined. You call loadItinerary before you define ItineraryName but try to use it in the query were you create your cursor. I think this is causing the error you're seeing

Related

Forgot password in android using SQLite

I implemented forgot password but i am getting an error. My db contains data.
Here is the logcat:
"E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.myapplication, PID: 8265
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.example.admin.myapplication.DatabaseHelper.updatepwd(java.lang.String, java.lang.String)' on a null object reference
at com.example.admin.myapplication.Reset$1.onClick(Reset.java:39)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)"
Below is the following code i have used:
Reset.java
public class Reset extends AppCompatActivity {
TextView phone;
EditText pwd,cpwd;
Button resetbtn;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset);
phone = (TextView)findViewById(R.id.Phonenumber);
pwd = (EditText) findViewById(R.id.pssword);
cpwd = (EditText) findViewById(R.id.pwdreenter);
resetbtn = (Button) findViewById(R.id.btnReset);
Intent intent = getIntent();
phone.setText(intent.getStringExtra("phone"));
resetbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = phone.getText().toString();
String pswd = pwd.getText().toString();
String repswd = cpwd.getText().toString();
if (pswd.equals(repswd)) {
Boolean pwd = db.updatepwd(user, pswd);
if (pwd) {
Intent intent1 = new Intent(getApplicationContext(), Login.class);
startActivity(intent1);
Toast.makeText(Reset.this, "Password Updated Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Reset.this, "Password NotUpdated Successfully", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getApplicationContext(), "Password Don't Match", Toast.LENGTH_SHORT).show();
}
}
});
//new code
public class MyTestDatabaseInstanceHolder {
public MyTestDBHandler DBHelper;
public static SQLiteDatabase m_ObjDataBase;
public static void createDBInstance(Context pContext){
if(DBHelper == null) {
DBHelper = new WLDBHandler(pContext);
m_cObjDataBase = DBHelper.openAndCreateDataBase();
}
}
}
Db.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "application.db";
public static final String TABLE_SIGNUP = "Signup";
public static final String COL_ID = "USER_ID";
public static final String COL_NAME = "NAME";
public static final String COL_PHONE = "PHONE_NUMBER";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";
public static final String COL_CONFIRMPASSWORD = "CONFIRMPASSWORD";
public static final String COL_NAMEone_CON = "NAMEONE";
public static final String COL_NUMBERone_CON = "NUMBERONE";
public static final String COL_NAMEtwo_CON = "NAMETWO";
public static final String COL_NUMBERtwo_CON = "NUMBERTWO";
public static final String COL_NAMEthree_CON = "NAMETHREE";
public static final String COL_NUMBERthree_CON = "NUMBERTHREE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
// SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_SIGNUP + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ COL_NAME + " VARCHAR(255) , " + COL_PHONE + " VARCHAR (255) UNIQUE ," + COL_EMAIL + " VARCHAR (255) UNIQUE," + COL_PASSWORD + " VARCHAR (255), "
+ COL_CONFIRMPASSWORD + " VARCHAR (255)," + COL_NAMEone_CON + " VARCHAR (255), "
+ COL_NUMBERone_CON + " VARCHAR (255) UNIQUE ," + COL_NAMEtwo_CON + " VARCHAR (255)," + COL_NUMBERtwo_CON + " VARCHAR (255) UNIQUE , "
+ COL_NAMEthree_CON + " VARCHAR (255)," + COL_NUMBERthree_CON + " VARCHAR (255) UNIQUE " + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGNUP);
onCreate(db);
}
Boolean updatepwd(String PHONE_NUMBER, String PASSWORD) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("PASSWORD", PASSWORD);
long res= db.update("Signup", contentValues, "PHONE_NUMBER = ?", new String[]{PHONE_NUMBER});
db.close();
if(res == -1)
return false;
else
return true;
}

SQLite Save Error NOT NULL Constraint

I have a local database in my app for storing user profiles from input fields. I have created the database using SQLiteOpenHelper class but after running my app, this error appears. I have been through the DatabaseHelper class but can't find what's wrong with it. I hope someone points out my mistake. Thanks.
my db class file here:
public class DBHelper {
private static final String DATABASE_NAME = "UsersDemo.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
//private static final String COL_PROFILE_PHOTO = "profilePhoto";
private Context mCtx;
private DatabaseManager databaseManager;
private SQLiteDatabase db;
public DBHelper(Context context){
this.mCtx = context;
databaseManager = new DatabaseManager(mCtx);
}
public DBHelper open() throws SQLException{
db = databaseManager.getWritableDatabase();
return this;
}
public void close(){
databaseManager.close();
}
public boolean saveInputField(TingTingUser user){
SQLiteDatabase userDb = databaseManager.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FULL_NAME, user.getDisplayName());
values.put(COL_USER_ID, user.getUserId());
values.put(COL_GENDER, user.getGender());
values.put(COL_DOB, user.getDob());
values.put(COL_MOBILE_NUM, user.getMobileNumber());
values.put(COL_ORGANIZATION, user.getOrganization());
values.put(COL_OCCUPATION, user.getOccupation());
long result = userDb.insert(TABLE_NAME, null, values);
userDb.close();
if (result == -1){
return false;
} else {
return true;
}
}
public TingTingUser getCurrentUser(int id){
SQLiteDatabase currDB = databaseManager.getWritableDatabase();
Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7));
return user;
}
return null;
}
public void saveCameraImage(byte[] imageBytes){
SQLiteDatabase camDb = databaseManager.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
camDb.insert(TABLE_NAME, null, contentValues);
}
public void saveGalleryImage(byte[] imageBytes){
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
db.insert(TABLE_NAME, null, contentValues);
}
public class DatabaseManager extends SQLiteOpenHelper {
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
}
The error occurs in my MainActivity when I call saveInputField() method of DBHelper, shown below:
JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
Log.d("OTPDialogFragment", "OTP Verified Successfully");
try {
JSONObject verifyObject = new JSONObject(response.toString());
JSONObject userObject = verifyObject.getJSONObject("user");
userId = userObject.getString("_id");
Log.d(TAG, "Retrieved user id is:\t" + userId);
TingTingUser user = new TingTingUser();
user.setDisplayName(fullName);
user.setMobileNumber(num);
user.setGender(genderVal);
user.setDob(dob);
user.setOccupation("default");
user.setOrganization("default");
user.setUserId(userId);
if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId)){
if (dbHelper.saveInputField(user) == true){ // error occurs here
Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show(); // Toast shows cos save failed, dont know why
}
}
Sorry guys, my mainactivity is too long, only showed what is necessary.
Error message in logcat:
android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.billionusers.tingting.db.DBHelper$DatabaseManager.onCreate(DBHelper.java:131)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:53)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:466)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:443)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
From the logcat
near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
and DBHelper.onCreate
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
Your create statement is invalid because you have put into comments the last line so it terminates in + COL_ORGANIZATION + " TEXT, "; which is not correct. The ending should be:
+ COL_ORGANIZATION + " TEXT ); ";

Android SQLite first use: Error java.lang.IllegalArgumentException: column '_id' does not exist

I know, there are a lot of answers already. But I'm a newbie on using SQLite yet and I tried what those answers say but nothing works.
It says my column id doesn't exist but it does exist:
public class SQLite extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "OMDBAPI";
// Films table name
static final String TABLE_FILMS = "films";
// Contacts Table Columns names
static final String KEY_TITLE = "Title";
static final String KEY_YEAR = "Year";
static final String KEY_RELEASED = "Released";
static final String KEY_RUNTIME = "Runtime";
static final String KEY_GENRE = "Genre";
static final String KEY_DIRECTOR = "Director";
static final String KEY_WRITER = "Writer";
static final String KEY_ACTORS = "Actors";
static final String KEY_PLOT = "Plot";
static final String ID = "_id";
public SQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FILMS_TABLE = "CREATE TABLE " + TABLE_FILMS +"(" +
ID + "integer primary key autoincrement," +
KEY_TITLE + " TEXT, " +
KEY_YEAR + " TEXT, " +
KEY_RELEASED + " TEXT, " +
KEY_RUNTIME + " TEXT, " +
KEY_GENRE + " TEXT, " +
KEY_DIRECTOR + " TEXT, " +
KEY_WRITER + " TEXT, " +
KEY_ACTORS + " TEXT, " +
KEY_PLOT + " TEXT" +
");";
db.execSQL(CREATE_FILMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FILMS);
// Create tables again
onCreate(db);
}
}
And I try to populate this on a listview:
public class Query extends Activity {
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBController crud = new DBController(getBaseContext());
Cursor cursor = crud.loadData();
String[] titles = new String[] {SQLite.ID, SQLite.KEY_TITLE};
int[] idViews = new int[] {R.id.idnumber, R.id.grid_title};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.adapter_layout,cursor,titles,idViews, 0);
list = (ListView)findViewById(R.id.listView);
list.setAdapter(adapter);
}
}
This is my DB CONTROLLER (Newbie mistake? Should I put the ID here too?):
public class DBController {
private SQLiteDatabase db;
private SQLite bank;
String success = "Film saved.";
String failed = "There was a problem saving the movie.";
public DBController(Context context){
bank = new SQLite(context);
}
public String insertData(String title, String release, String year, String writers, String actors, String director, String genre, String plot, String runtime){
ContentValues values;
long result;
db = bank.getWritableDatabase();
values = new ContentValues();
// Insert values
values.put(SQLite.KEY_TITLE, title);
values.put(SQLite.KEY_YEAR, release);
values.put(SQLite.KEY_RELEASED, release);
values.put(SQLite.KEY_YEAR, year);
values.put(SQLite.KEY_GENRE, genre);
values.put(SQLite.KEY_DIRECTOR, director);
values.put(SQLite.KEY_WRITER, writers);
values.put(SQLite.KEY_ACTORS, actors);
values.put(SQLite.KEY_PLOT, plot);
values.put(SQLite.KEY_RUNTIME, runtime);
result = db.insert(SQLite.TABLE_FILMS, null, values);
db.close();
if (result ==-1)
return failed;
else
return success;
}
public Cursor loadData(){
Cursor cursor;
String[] fields = {bank.KEY_TITLE,bank.KEY_RELEASED};
db = bank.getReadableDatabase();
cursor = db.query(bank.TABLE_FILMS, fields, null, null, null, null, null, null);
if(cursor!=null){
cursor.moveToFirst();
}
db.close();
return cursor;
}
}
Can someone help me find out why it says I don't have an ID column?
(Why are ppl downvote the post? I thought Stack Overflow was to help idiots like me =P)
You don't have _id column, you have _idinteger because you forgot to put a space in the CREATE query. Change the line
ID + "integer primary key autoincrement," +
to
ID + " integer primary key autoincrement," +
You can use baseColums interface that provides a primary key field (called _ID)
An example from google

SQLIte database not able to delete entries

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

SQLiteException: no such column error [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
I have looked through SO and found many people having this same error, but they seem to be forgetting to add the column into the create statement or missing whitespace, neither of which I believe I did.
My logcat is as follows:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmd.referenceapplication, PID: 31988
android.database.sqlite.SQLiteException: no such column: QUANTITY (code 1): , while compiling: SELECT * FROM FTS WHERE (QUANTITY MATCH ?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.gmd.referenceapplication.DatabaseTable.query(DatabaseTable.java:187)
at com.gmd.referenceapplication.DatabaseTable.getWordMatches(DatabaseTable.java:179)
at com.gmd.referenceapplication.SearchableActivity$1.onQueryTextChange(SearchableActivity.java:70)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1150)
at android.support.v7.widget.SearchView.access$2000(SearchView.java:103)
at android.support.v7.widget.SearchView$12.onTextChanged(SearchView.java:1680)
at android.widget.TextView.sendOnTextChanged(TextView.java:7991)
at android.widget.TextView.handleTextChanged(TextView.java:8053)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10157)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1033)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:559)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:492)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:491)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
DatabaseTable class:
public static final String TAG = "ConstantDatabase";
//the columns included in the table
public static final String COL_QUANTITY = "QUANTITY";
public static final String COL_VALUE = "VALUE";
public static final String COL_UNCERTAINTY = "UNCERTAINTY";
public static final String COL_UNIT = "UNIT";
public static final String _id = "_id";
//name, tbale name, version
private static final String DATABASE_NAME = "CONSTANTS";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
private final Context mcontext;
public DatabaseTable(Context context){
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
mcontext = context;
}
private class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private final MyDataProvider dp = new MyDataProvider(mcontext);
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +_id+ " INTEGER PRIMARY KEY,"+
COL_QUANTITY + " TEXT, " +
COL_VALUE + " TEXT," +
COL_UNCERTAINTY + " TEXT," +
COL_UNIT + " TEXT " + ")";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
loadConstants();
Log.e("Database Operation", "DatabaseOpenHelper constructor called, constants loaded?");
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(FTS_TABLE_CREATE);
Log.e("Database Operation", "Constants Table Created ...");
loadConstants();
}
#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 " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
public SQLiteDatabase getmDatabase(){
return mDatabase;
}
private void loadConstants() {
new Thread(new Runnable() {
public void run() {
try {
loadConstantss();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
Log.e("Loading", "Constants Table Populated ...");
}
private void loadConstantss() throws IOException {
HashMap map = dp.getAllMap();
Iterator<Map.Entry<String, ListViewItem>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, ListViewItem> entry = entries.next();
Log.d("thing:", entry.getKey());
//addConstant(entry.getKey(), entry.getValue(), entry.getUncertainty(), entry.getUnit());
}
}
public long addConstant(String quantity, String value, String uncertainty, String unit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(COL_QUANTITY, quantity);
initialValues.put(COL_VALUE, value);
initialValues.put(COL_UNCERTAINTY, uncertainty);
initialValues.put(COL_UNIT, unit);
db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
return db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
//database openhelper ends
}
public Cursor getWordMatches(String query, String[] columns) {
String selection = COL_QUANTITY + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
public Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
public Cursor getAllTitles(){
return mDatabaseOpenHelper.getmDatabase().query(FTS_VIRTUAL_TABLE, new String[] {
COL_QUANTITY,
COL_UNCERTAINTY,
COL_UNIT,
COL_VALUE},
null,
null,
null,
null,
null);
}
Thank you to anyone who can tell me why it is telling me the column "QUANTITY" is not being created, I really don't know.
If you change the schema you should increment DATABASE_VERSION so the database is upgraded.

Categories