public void onClick(View v) {
if (btn66 == v) {
ContentValues value = new ContentValues();
value.put(DBhelper.Amount, txtBudget.getText().toString());
value.put(DBhelper.Description, txr.getText().toString());
if(DBhelper.Amount == null)
{
db = helper.getWritableDatabase();
db.insert(DBhelper.TABLE2, null, value);
db.close();
clearfield();
Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show();
fetchData2();
Intent i = new Intent(addbudget.this, MainActivity.class);
startActivity(i);
}
else{
db = helper.getWritableDatabase();
db.update(DBhelper.TABLE2, value, "_id "+"="+1, null);
db.close();
fetchData2();
Toast.makeText(this, "Update Successfully", Toast.LENGTH_LONG).show();
clearfield();
}
}
}
The above one is my code to add and update values to the sqlite database,after I include the Update method in my code,my add function is not working and my update function also not working.Is there any problem with my code,but I didn't get any error message.
This is my Database tables
static final String C_ID = "_id";
static final String Name = "name";
static final String B_ID = "_id";
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE1+ "(" +C_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Name+ " text unique not null)");
db.execSQL("CREATE TABLE " + TABLE2+ "(" +B_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Description+ " text,"
+Amount+ " text, FOREIGN KEY ("+Description+") REFERENCES "+TABLE1+"("+Name+"));");
}
Try using something like this to check if a row with the given name is present in the table1:
public boolean checkIfRowPresent(String name) {
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor =
db.query(DBhelper.TABLE1, null, DBHelper.NAME + "='" + name + "'", null, null, null,
null, null);
boolean ret = false;
if (cursor.getCount() > 0) {
ret = true; // There is a row present in table1 with the given name
}
db.close();
return ret;
}
You should be calling it with this:
checkIfRowPresent(txr.getText().toString())
Let me know if it helps?
Related
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 creating a login app, where a user has an username and a password. I want to save sign up data in my database, but when I want to get access to the elements from database, no one seems to be saved ( it has no user saved in db). I suppose the error comes from db implementation. Any idea?
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "user_table";
public static final String COL1 = "ID";
public static final String COL2 = "user_username";
public static final String COL3 = "user_password";
public DataBaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "( " + COL2 + " TEXT," +
COL3 + "TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void add(String name, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, name);
contentValues.put(COL3, password);
db.insert(TABLE_NAME, null, contentValues);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT *FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
LOGIN Activity:
public void loginSeach(View view) {
EditText password_editText = (EditText) findViewById(R.id.editText_password);
EditText username_editText = (EditText) findViewById(R.id.editText_username);
String currUserName = username_editText.getText().toString();
String currPassWord = password_editText.getText().toString();
DataBaseHelper db = new DataBaseHelper(this);
Cursor data = db.getData();
int Number = 0;
while (data.moveToNext()) {
Number ++;
String userName = data.getString(1);
String passWord = data.getString(2);
}
Toast.makeText(this, Integer.toString(Number), Toast.LENGTH_SHORT).show();
}
Sign up activity:
public void createAccount(View view) {
EditText usernameEditText = (EditText) findViewById(R.id.editText_createUsername);
EditText passwordEditText = (EditText) findViewById(R.id.editText_createPassword);
String userName = usernameEditText.getText().toString();
String passWord = passwordEditText.getText().toString();
dataBaseHelper.add(userName, passWord);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
This statement in onCreate():
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL2 + " TEXT," + COL3 + "TEXT)";
created a table without an ID column.
Uninstall the app from the emulator/device, change your code to this:
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 + " TEXT," + COL3 + " TEXT)";
and rerun the app.
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I have two activities one is Database helper and other is main activity. There is no sytax error but whenever I press Accept button (accButton), my app stops working.
Please help me out thanks.
Code in DBhelper class
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + TABLE_NAME + "create table LMSLiteDB(ID text primary key not null," +
"Password text not null, Name text not null, VU-Email text not null, City text not null," +
"Country text not null, Selected_Course text not null);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean insertValues(String id, String autoPass, String name, String mail, String city, String contry , String selectedCourse) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_ID, id);
values.put(COLUMN_PASSWORD, autoPass);
values.put(COLUMN_Name, name);
values.put(COLUMN_VUEmail, mail);
values.put(COLUMN_CITY, city);
values.put(COLUMN_COUNTRY, contry);
values.put(COLUMN_SELECTEDCOURSE, selectedCourse);
long result = db.insert(TABLE_NAME, null, values);
if (result == -1)
return false;
else
return true;
}
code in Main activity
public void onAccClick(View view) {
TextView tfName = (TextView) findViewById(R.id.fName);
TextView tEmail = (TextView) findViewById(R.id.vuEmail);
TextView tId = (TextView) findViewById(R.id.id);
TextView tPassword = (TextView) findViewById(R.id.password);
TextView tCity = (TextView) findViewById(R.id.city);
TextView tContry = (TextView) findViewById(R.id.contry);
TextView tItem = (TextView) findViewById(R.id.item);
boolean isInserted = db.insertValues(tId.getText().toString(), tPassword.getText().toString(), tfName.getText().toString(),
tEmail.getText().toString(), tCity.getText().toString(), tContry.getText().toString(),
tItem.getText().toString());
if (isInserted = true) {
Toast.makeText(ACCEPT.this, "Data Inserted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ACCEPT.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
}
I guess your TABLE not created properly. Update your create table statement.
Use:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID text primary key not null, " +
"Password text not null, Name text not null, VU-Email text not null, City text not null," +
" Country text not null, Selected_Course text not null);");
}
Instead of:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + TABLE_NAME + "create table LMSLiteDB(ID text primary key not null," +
"Password text not null, Name text not null, VU-Email text not null, City text not null," +
"Country text not null, Selected_Course text not null);");
}
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 "+ ")";
I added 3 new columns to my Database from version 1 so I changed it to version 2 but now when I use an activity that uses my database my app crashes and shows this in the logcat.
04-02 18:41:09.013: E/AndroidRuntime(19171): FATAL EXCEPTION: main
04-02 18:41:09.013: E/AndroidRuntime(19171):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.fullfrontalgames.numberfighter/com.fullfrontalgames.numberfighter.AccountSettings}:
android.database.sqlite.SQLiteException: near "CREATE": syntax error
(code 1): , while compiling: create table NFDB( ID integer primary key
autoincrement,USERNAME text CREATE UNIQUE INDEX idx_keytype ON
tableName (USERNAME);USERNAME text,PASSWORD text,EMAIL
text,NUMBERINPUT text,SCORE text,FRIENDS text);
04-02 18:41:09.013: E/AndroidRuntime(19171): Caused by:
android.database.sqlite.SQLiteException: near "CREATE": syntax error
(code 1): , while compiling: create table NFDB( ID integer primary key
autoincrement,USERNAME text CREATE UNIQUE INDEX idx_keytype ON
tableName (USERNAME);USERNAME text,PASSWORD text,EMAIL
text,NUMBERINPUT text,SCORE text,FRIENDS text);
I can't see the syntax error anywhere and I have my DBHelper helperclass to drop my old table and make the new table.
here is my code of my DBAdapter and DBHelper classes
package com.fullfrontalgames.numberfighter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBAdapter
{
static final String DATABASE_NAME = "NFDB.db";
static final int DATABASE_VERSION = 2;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"NFDB"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text CREATE UNIQUE INDEX idx_keytype ON tableName (USERNAME);" +
"PASSWORD text,EMAIL text,NUMBERINPUT text,SCORE text,FRIENDS text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper DBHelper;
public DBAdapter(Context _context)
{
context = _context;
DBHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password,String email)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("EMAIL", email);
// Insert the row into your table
db.insert("NFDB", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String userName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("NFDB", where, new String[]{userName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("NFDB", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("NFDB",updatedValues, where, new String[]{userName});
}
public String getData() {
String[] columns = new String[] { "ID", "USERNAME"};
Cursor c = db.query("NFDB", columns, null, null, null, null, null, null);
String result ="";
int iRow = c.getColumnIndex("ID");
int iName = c.getColumnIndex("USERNAME");
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName) + "/n";
}
return result;
}
public String getUsername(String searchName) {
Cursor c = db.query("NFDB",
new String[] { "USERNAME" },
"USERNAME = ?",
new String[] { searchName },
null, null, null);
if (c.moveToNext())
return c.getString(0);
else
return "";
}
public void InsertScore(String Username,String Score)
{
ContentValues ScoreValues = new ContentValues();
ScoreValues.put("USERNAME", Username);
ScoreValues.put("SCORE", Score);
db.insert("NFDB", null, ScoreValues);
}
public String GetGameScore(String Username,String Score)
{
Cursor cursor = db.query("NFDB", null, "USERNAME",new String[]{Username,Score}, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllScore()
{
String[] columns = new String[] {"ID","USERNAME","SCORE"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iUsername = cursor.getColumnIndex("USERNAME");
int iScore = cursor.getColumnIndex("SCORE");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iUsername) + " " + cursor.getString(iScore) + "/n";
}
return result;
}
public void InsertNumber(String Username,String Number)
{
ContentValues NumberValues = new ContentValues();
NumberValues.put("USERNAME", Username);
NumberValues.put("NUMBERINPUT", Number);
db.insert("NFDB", null, NumberValues);
}
public String GetNumber(String Username,String Number)
{
Cursor cursor = db.query("NFDB", null, "USERNAME", new String[]{Username,Number}, null, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllNumbers()
{
String[] columns = new String[] {"ID","USERNAME","NUMBERINPUT"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iNumber = cursor.getColumnIndex("NUMBERINPUT");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iName) + " " + cursor.getString(iNumber) + "/n";
}
return result;
}
public void InsertFriends (String Username,String Friends)
{
ContentValues FriendValues = new ContentValues();
FriendValues.put("USERNAME", Username);
FriendValues.put("FRIENDS", Friends);
db.insert("NFDB", null, FriendValues);
}
public int DeleteFriends(String Username,String Friends)
{
String where = "USERNAME=?,FRIENDS=?";
int numberOfEntriesDeleted = db.delete("NFDB", where, new String[]{Username,Friends});
return numberOfEntriesDeleted;
}
public String GetFriend(String Username,String Friend)
{
Cursor cursor = db.query("NFDB", null, "USERNAME", new String[]{Username,Friend}, null, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllFriends()
{
String[] columns = new String[] {"ID","USERNAME","FRIENDS"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iFriends = cursor.getColumnIndex("FRIENDS");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iName) + " " + cursor.getString(iFriends) + "/n";
}
return result;
}
}
package com.fullfrontalgames.numberfighter;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// TODO Auto-generated constructor stub
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(DBAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "NFDB");
// Create a new one.
onCreate(_db);
}
}
Your DML statement is incorrect. Index creation cannot be used in CREATE TABLE statement. It must have its own statement.
You have to correct it like this:
DATABASE_CREATE = "create table NFDB("
+ "ID integer primary key autoincrement, "
+ "USERNAME text, PASSWORD text, "
+ "EMAIL text, NUMBERINPUT text, "
+ "SCORE text, FRIENDS text)";
and second statement:
CREATE_INDEX_KEYTYPE = "CREATE UNIQUE INDEX idx_keytype ON tableName(USERNAME)";
And finally, in your SQLiteOpenHelper subclass implementation perform following actions:
_db.execSQL(DBAdapter.DATABASE_CREATE);
_db.execSQL(DBAdapter.CREATE_INDEX_KEYTYPE);