I was trying to insert data on an SQLITE database but it is not there when I open the database.
I am trying to do an application that is able to store data on a database. But when I try to add data, it doesn't get added to the table. Here's the code for the database helper and for the activity in which I call the insert data function:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Channels.db" ;
public static final String TABLE_NAME = "Channels_table" ;
public static final String COL_1 = "Channel_number" ;
public static final String COL_2 = "Channel_name" ;
public DatabaseHelper(Context context){
super(context, DATABASE_NAME , null , 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (Channel_number INTEGER PRIMARY KEY , Channel_name TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(int c_number , String c_name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1 , c_number);
contentValues.put(COL_2 , c_name);
long result = db.insert(TABLE_NAME , null , contentValues);
if (result == -1){
return false;
}
else
return true;
}
public class Add_Activity extends AppCompatActivity {
DatabaseHelper db;
EditText channel_name , channel_number ;
Button Add_button;
protected void onCreate (Bundle savedInstanceBundle) {
super.onCreate(savedInstanceBundle);
setContentView(R.layout.add_view);
channel_name = findViewById(R.id.channel_name_textview);
channel_number = findViewById(R.id.channel_number_textview);
Add_button = (Button) findViewById(R.id.add_button);
db = new DatabaseHelper(this);
Button_tapped();
}
public void Button_tapped(){
Add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(channel_name.getText().toString().isEmpty() || channel_number.getText().toString().isEmpty()){
Toast.makeText(Add_Activity.this , getText(R.string.empty_fields) , Toast.LENGTH_LONG).show();
}
else if (Integer.parseInt(channel_number.getText().toString()) < 0 || Integer.parseInt(channel_number.getText().toString()) > 84){
Toast.makeText(Add_Activity.this , getText(R.string.invalid_channel_numb) , Toast.LENGTH_LONG).show();
channel_number.setText("");
}
else {
boolean insertdata = db.insertData(Integer.parseInt(channel_number.getText().toString()) , channel_name.getText().toString());
if (insertdata){
Toast.makeText(Add_Activity.this , getText(R.string.successfull_insertion) , Toast.LENGTH_LONG).show();
}
else
Toast.makeText(Add_Activity.this , getText(R.string.unsuccessfull_insertion) , Toast.LENGTH_LONG).show();
channel_number.setText("");
channel_name.setText("");
}
}
});
}
}
When I tap the button, I get the toast for the unsuccessful insertion and the data is not being inserted into the database. What I need is to be able to see the successful insertion toast and to find the data in the database.
Try this
db.execSQL("CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY, " + COL_2 + " TEXT )");
instead of
db.execSQL("create table " + TABLE_NAME + " (Channel_number INTEGER PRIMARY KEY , Channel_name TEXT )");
Related
I am trying to save the Latitude and Longitude to my SQLite database. However it is not saving it and not getting any error messages.
This is my code I have so far:
dbHandler = new DBHandler(MapsActivity.this);
googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
String latLong = latLng.latitude + " : " + latLng.longitude;
dbHandler.addNewLocation(latLong);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.addMarker(markerOptions);
Toast.makeText(MapsActivity.this, "Location has been added.", Toast.LENGTH_SHORT).show();
}
});
And then the DBHandler class:
public class DBHandler extends SQLiteOpenHelper {
private static final String DB_NAME = "locationsdb";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "mylocations";
private static final String ID_COL = "id";
private static final String NAME_LAT = "lat";
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_LAT + " TEXT)";
db.execSQL(query);
}
public void addNewLocation(String latLong) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_LAT, latLong);
db.insert(TABLE_NAME, null, values);
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Then when I check the database there is nothing saved in it?
Can someone please let me know what I am doing wrong here?
Thanks
Try db.beginTransaction() after calling getWritableDatabase() and use db.endTransaction() instead of db.close() in addNewLocation(...).
please help me with this problem. My app keeps crashing because of this. What I want to do is to display the user's information from the SQLite database after they login in a text view on the profile activity. Please help me with my project. I'm still new to android studio.
this is the syntax error in my logcat
android.database.sqlite.SQLiteException: near "null": syntax error (code 1 SQLITE_ERROR): , while compiling: Select * from USER_TABLE where null=?null =?null =?
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
public static String C_EMAIL,C_PREFERENCES,C_PASSWORD;;
public DatabaseHelper(#Nullable Context context) {
super(context, constants.DB_NAME, null, constants.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(constants.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + constants.TABLE_NAME);
onCreate(db);
}
public boolean insertInfo(String email, String preference,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(constants.C_EMAIL, email);
values.put(constants.C_PREFERENCES, preference);
values.put(constants.C_PASSWORD , password);
long id = db.insert(constants.TABLE_NAME, null, values);
if (id == -1) {
return false;
}else {
return true;
}
}
public boolean userExists (String email){
String [] columns = {C_EMAIL};
SQLiteDatabase db = getReadableDatabase();
String selection = C_EMAIL + "=?";
String selectionArgs []= { email };
Cursor cursor = db.query(TABLE_NAME,columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if (count > 0)
return true;
else
return false;
}
public Cursor getData(String email, String Password){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(" Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "=?" + C_PASSWORD + " =?", new String[]{email,Password});
return res;
}
}
This is my login.java
loginacc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor rs = dbHelper.getData(loginemail.getText().toString(),loginpassword.getText().toString());
if(rs.moveToFirst()){
String email = rs.getString(rs.getColumnIndex(DatabaseHelper.C_EMAIL));
String preference = rs.getString(rs.getColumnIndex(DatabaseHelper.C_PREFERENCES));
String password = rs.getString(rs.getColumnIndex(DatabaseHelper.C_PASSWORD));
Toast.makeText(login.this,"Login Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(login.this,profile.class);
intent.putExtra("email", email);
intent.putExtra("preference", preference);
intent.putExtra("password", password);
startActivity(intent);
if(rs != null && rs.isClosed()){
rs.close();
}
}
else{
Toast.makeText(login.this,"Invalid Login", Toast.LENGTH_SHORT).show();
}
}
});
}
This is my profile.java
public class profile extends AppCompatActivity {
DatabaseHelper dbHelper;
TextView pemail,ppreferences, ppassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
dbHelper = new DatabaseHelper(this);
pemail = findViewById(R.id.pemail);
ppreferences = findViewById(R.id.ppreferences);
ppassword = findViewById(R.id.ppassword);
pemail.setText(getIntent().getStringExtra("email"));
ppreferences.setText(getIntent().getStringExtra("preferences"));
ppassword.setText((getIntent().getStringExtra("password")));
Thanks for your help!
You are declaring 3 static variables here:
public static String C_EMAIL,C_PREFERENCES,C_PASSWORD;
without assigning any value to them so they are all null.
When you use them inside getData():
" Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "=?" + C_PASSWORD + " =?"
the result is:
Select * from USER_TABLE where null=?null =?null =?
(it's not clear from your code where the 3d null =? comes from)
What you want is (I guess) to use these variables for the column names of the table.
So change the declarations to:
public static String C_EMAIL = "email"; // change to the actual column name
public static String C_PASSWORD = "password"; // change to the actual column name
public static String C_PREFERENCES = "preferences"; // change to the actual column name
Also add the AND operator in the sql statement:
"Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "= ? AND " + C_PASSWORD + " = ?"
Edit
Inside the method insertInfo() you use constants.C_EMAIL, constants.C_PREFERENCES and constants.C_PASSWORD which it seems are the names of your columns.
If so, then use them also in the sql statement and drop the static variables:
"Select * from "+ TABLE_NAME + " where "+ constants.C_EMAIL + "= ? AND " + constants.C_PASSWORD + " = ?"
Hello I am making a simple note application, using an SQLite database, using a custom arraylist adapter, where the user can save a note having a title, a descriptive text, and the date. Everything works, but I want users to be able to save a new note only if the title is not in the database. How can I do this ?
Here is the edit note
public class Edit_notes extends AppCompatActivity {
private DBOpenHelper dbop;
private SQLiteDatabase sdb;
private EditText title_text;
private EditText note_text;
public boolean SaveNote(){
String note_title_string = title_text.getText().toString();
String note_text_string = note_text.getText().toString();
if (!note_title_string.isEmpty()){
if(!note_text_string.isEmpty()) {
// Need to check if title is not in the database then insert else don't
String date = new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + (new Date().getYear() + 1900);
AddData(note_title_string, note_text_string, date); // Add title to the database
Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(this, "Note text cannot be empty", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show();
}
return true;
}
public void AddData(String title_entry, String text_entry, String date){
dbop = new DBOpenHelper(this);
sdb = dbop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("TITLE", title_entry);
cv.put("TEXT", text_entry);
cv.put("DATE", date);
sdb.insert("note_table", null, cv);
}
}
SQLite database.java:
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "notes.db";
public static final String TABLE_NAME = "note_table";
public static final String ID_COLUMN = "ID";
public static final String TITLE_COLUMN = "TITLE";
public static final String TEXT_COLUMN = "TEXT";
public static final String DATE_COLUMN = "DATE";
SQLiteDatabase db = this.getWritableDatabase();
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 5);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT, " + " TEXT TEXT, " + " DATE STRING)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table note_table");
onCreate(db);
}
}
I guess there is no need to provide the mainactivity.java
Change the table Create to :-
String createTable = "CREATE TABLE " + TABLE_NAME
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT UNIQUE, " + " TEXT TEXT, " + " DATE STRING)";
Uninstall the App, or delete the App's Data, or increase the database version number and rerun the App. Row will not be added UNIQUE constraint conflict (same title) (insert method effectively uses INSERT OR IGNORE).
I am pretty new to Android development and I am trying to implement a database for my app.
I started with only having one column in the database (COLUMN_DATE) and then added another column (COLUMN_REPEAT). This worked fine and printed the results as expected. However, when I tried adding another column (COLUMN_ACCOUNT), printDatabase() in MainActivity did not print anything.
I understand you can view what is in your database by using Android Device Monitor, but I keep getting an error when I click on that so I cannot use it (That is a separate issue which I haven't been able to solve). Hence, I am unsure if it is just an issue with printing the database or if there is actually any data in the database at all.
Any help would be much appreciated
----MainActivity.java----
dbHandler = new DatabaseHandler(this, null, null, 1);
printDatabase();
//Print the database
public void printDatabase() {
String dbString = dbHandler.databaseToString();
recordsTextView.setText(dbString);
}
//Add an item to the database
public void addButtonClicked(View view){
Income date = new Income(dateView.getText().toString());
Income repeat = new Income(repeatSpinner.getSelectedItem().toString());
Income account = new Income(accountSpinner.getSelectedItem().toString());
dbHandler.addData(date, repeat, account);
printDatabase();
}
//Delete items with input date from database
public void deleteButtonClicked(View view){
String inputText = dateView.getText().toString();
dbHandler.deleteData(inputText);
printDatabase();
}
----DatabaseHandler.java----
public class DatabaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "IncomeExpenseDB.db";
public static final String TABLE_NAME = "income_expense";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_REPEAT = "repeat";
public static final String COLUMN_ACCOUNT = "account";
public DatabaseHandler(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_DATE + " TEXT, " + COLUMN_REPEAT + " TEXT, " +
COLUMN_ACCOUNT + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add a new row to the database
public void addData(Income date, Income repeat, Income
account){
ContentValues values = new ContentValues();
values.put(COLUMN_DATE, date.get_item());
values.put(COLUMN_REPEAT, repeat.get_item());
values.put(COLUMN_ACCOUNT, account.get_item());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
//Delete data from the database
public void deleteData(String date){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_DATE + "=\""
+ date + "\";");
}
// Create a string to print out in MainActivity
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
//Cursor points to a location in results
Cursor c = db.rawQuery(query, null);
//Move to first row in results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("date")) != null &&
c.getString(c.getColumnIndex("repeat")) != null &&
c.getString(c.getColumnIndex("account")) != null) {
dbString += c.getString(c.getColumnIndex("date"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("repeat"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("account"));
dbString += "\n";
}
c.moveToNext();
}
db.close();
return dbString;
}
}
----Income.java----
public class Income {
private int _id;
private String _item;
public Income(){
}
public Income(String item) {
this._item = item;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_item() {
return _item;
}
public void set_item(String _item) {
this._item = _item;
}
}
Uninstalling and reinstalling is very naive approach which will only work in development phase. When your app goes on to play store, users are not going to uninstall and reinstall the app.
Correct way to update the database for published apps is to increase your db version and use onUpgrade method to update your database.
look at this method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
In current scenario if you just increase your db version, it will drop existing table and create a new one with new columns and specifications. The downside is that you'll lose all of your existing data.
If you want to save existing data and add new column to db, you have to do something like this -
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//add new column
sqLiteDatabase.execSQL("ALTER TABLE "+ TABLE_NAME + " ADD COLUMN "+ NEW_COLUMN + " INTEGER/TEXT ");
}
}
Just update your version of database when you add any column or make any update in the table. ... this helps me hope it will also work for you.
I can not create a table. It shows that the database is created and I can also insert a row, but the table is not created.
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
You're missing a , between USER_EMAIL and USER_PASS columns in the CREATE TABLE.
After adding it you can uninstall your app to recreate the database. When is SQLiteOpenHelper onCreate() / onUpgrade() run?
You miss comma in USER PASS type.Uninstall the application and install it again each time you add something new to sqlite database because the table structure has been changed.So you need to reinstall the new application .
The code should be like this
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT ,"+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ")";