I'm trying to insert data into a database on android studio, the code runs through with no errors, however, the data doesn't get added into the database table.
The data I need to pass through is the title of a movie, Avengers and a showtime 10:00
here is my database helper class
package com.missouristate.bryson.finalp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DABASE_NAME = "Movies.db";
public static final String TABLE_NAME = "movies_table";
public static final String ID = "_ID";
public static final String NAME = "Movie_Name";
public static final String SHOWTIME = "Showtime";
public DatabaseHelper(#Nullable Context context) {
super(context, DABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sqlCreate = "CREATE TABLE " + TABLE_NAME + "( " + ID;
sqlCreate += " integer primary key autoincrement, " + NAME;
sqlCreate += "text, " + SHOWTIME + " text, )";
db.execSQL(sqlCreate);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
onCreate(db);
}
public boolean addMovie( String name, String showtime) {
ContentValues contentValues = new ContentValues();
contentValues.put("MOVIE", name);
contentValues.put("SHOWTIME", showtime);
long result = getWritableDatabase().insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
}
here is my showtime class
package com.missouristate.bryson.finalp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class showtimes extends Activity {
DatabaseHelper myDB;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showtimesview);
myDB= new DatabaseHelper(this);
myDB.addMovie(" Avengers", " 1000");
}
}
Any help/advice will be appreciated. Thank you!
UPDATE FOR LOG-- CHANGED THE addMovie method to
public void addMovie( String name, String showtime) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues contentValues = new ContentValues();
contentValues.put("MOVIE", name);
contentValues.put("SHOWTIME", showtime);
db.insertOrThrow(TABLE_NAME, null, contentValues);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("insert", "Error while trying to add post to database");
} finally {
db.endTransaction();
}
The log is still showing the data isn't being added into the database
You have a few issues.
First you have :-
String sqlCreate = "CREATE TABLE " + TABLE_NAME + "( " + ID;
sqlCreate += " integer primary key autoincrement, " + NAME;
sqlCreate += "text, " + SHOWTIME + " text, )";
There is a comma at the end, so a syntax error will arise when the table is created.
Second you have omitted the space between NAME and text, thus the column name will be Movie_Nametext not Movie_Name.
You should instead have :-
String sqlCreate = "CREATE TABLE " + TABLE_NAME + "( " + ID;
sqlCreate += " integer primary key autoincrement, " + NAME;
sqlCreate += " text, " + SHOWTIME + " text /*<<<<< spurious comma removed */ )";
The comment can be removed.
If the unfixed version above has been run then the database itself will have been created and thus the onCreate method will not run and you would get a table not found error. You should delete the App's data or uninstall the App to delete the database, fix the errors and then rerun the App.
Third you have :-
contentValues.put("MOVIE", name);`
This will be converted into saying to insert the value held in the variable name into the column called "MOVIE".
According to the table definition there is no such column called MOVIE.
I beleieve that you need to use
contentValues.put("Movie_Name", name);
or better still
contentValues.put(NAME, name);
and likewise for all column and table names.
After making the changes and deleting the database and rerunning using the following to test :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB= new DatabaseHelper(this);
myDB.addMovie(" Avengers", " 1000");
DatabaseUtils.dumpCursor(
myDB.getWritableDatabase().query(DatabaseHelper.TABLE_NAME,null,null,null,null,null,null)
);
}
}
The log contains :-
2019-12-05 19:01:21.441 13419-13419/? I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor#44be644
2019-12-05 19:01:21.442 13419-13419/? I/System.out: 0 {
2019-12-05 19:01:21.442 13419-13419/? I/System.out: _ID=1
2019-12-05 19:01:21.442 13419-13419/? I/System.out: Movie_Name= Avengers
2019-12-05 19:01:21.442 13419-13419/? I/System.out: Showtime= 1000
2019-12-05 19:01:21.442 13419-13419/? I/System.out: }
2019-12-05 19:01:21.442 13419-13419/? I/System.out: <<<<<
Related
I've been stuck on this problem for a while now, and I can't seem to figure out what's wrong. I'm trying to create a database table, insert values into the table, and check to see if the email already exists. At first, it was at least telling me that the values were being inserted, now, the app only stops.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "People.db";
public static final String TABLE_NAME = "user";
public static final String COL1 = "email";
public static final String COL2 = "password";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +
COL1 + "TEXT PRIMARYKEY," +
COL2 + "TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
/*Inserting into database*/
public boolean add(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
to database
contentValues.put(COL1, email);
contentValues.put(COL2, password);
long ins = db.insert(TABLE_NAME, null, contentValues);
if (ins == -1) return false;
else return true;
}
/*checking if email exist*/
public Boolean chkemail(String email) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * from TABLE_NAME where email = ?",
new String[]{email});
if (cursor.getCount() > 0) return false;
else return true;
}
}
This is the SignUp activity that inserts and checks the information.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.powell.randomeats.MainActivity;
import com.powell.randomeats.R;
public class SignUp extends AppCompatActivity {
DatabaseHelper db;
EditText email, pass, pass1;
Button sign;
boolean optionsSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
db = new DatabaseHelper(this);
email = (EditText) findViewById(R.id.Email);
pass = (EditText) findViewById(R.id.Password);
pass1 = (EditText) findViewById(R.id.Confirm);
sign = (Button) findViewById(R.id.Signup);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = email.getText().toString();
String s2 = pass.getText().toString();
String s3 = pass1.getText().toString();
if (s1.equals("") || s2.equals("") || s3.equals("")) {
Toast.makeText(getApplicationContext(), "Fields are empty",
Toast.LENGTH_SHORT).show();
} else {
if (s2.equals(s3)) {
Boolean chkemail = db.chkemail(s1);
if (chkemail == true) {
Boolean insert = db.add(s1, s2);
if (insert == true) {
Toast.makeText(getApplicationContext(),
"Registered Succesfully",
Toast.LENGTH_SHORT).show();
Log();
if (optionsSwitch == true) {
openLog();
}
}
} else {
Toast.makeText(getApplicationContext(), "Email
Already exists,", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Passwords do
not match", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void Log() {
optionsSwitch = true;
}
public void openLog() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
Your issue(s)
I believe that the table is being created. However, not with the expected column names.
That is due to spaces being admitted the create statement resolves to :-
CREATE TABLE user (emailTEXT PRIMARYKEY, passwordTEXT);
As such the table will have columns emailTEXT rather than email and passwordText rather than password.
This will cause issues when attempt to use columns email and password as those columns do not exist.
Additional PRIMARYKEY is not a valid keyword so changing the create statement to
CREATE TABLE user (email TEXT PRIMARYKEY, password TEXT);
Will create the table with the correct columns BUT the email column would not reject duplicate values.
So you'd need to add a space between PRIMARY and KEY thus the create should be :-
CREATE TABLE user (email TEXT PRIMARY KEY, password TEXT);
Suggested Fix
Your code could be changed to :-
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +
COL1 + " TEXT PRIMARY KEY," +
COL2 + " TEXT)");
}
Note that onCreate will not be invoked unless the database is deleted or it is forced to be invoked, so you could do one of the following :-
Delete the App's data (deletes the database).
uninstall the App (deletes the database).
Increase the database version (4th parameter of the call to the super e.g. use super(context, DATABASE_NAME, null, 2); (1 changed to 2)) (causes the onUpgrade method to be invoked and thus the table is dropped and then onCreate is invoked.).
Change this line:
Cursor cursor = db.rawQuery("SELECT * from TABLE_NAME where email = ?", new String[]{email});
to
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " where email = ?", new String[]{email});
so that the name of the table in the sql statement is users and not TABLE_NAME.
I already know how to create new databases using MySQL command line .
Is there a tool provided by Eclipse Luna for creating MySQL databases ?
Thanks in advance .
Why would you need a tool, when it's this simple to create a database and tables with a Java application?
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateDatabase implements Runnable {
private Connection connection;
private Statement statement;
private String databaseAddress;
private String logon;
private String password;
public CreateDatabase(String logon, String password) {
this.logon = logon;
this.password = password;
this.databaseAddress = "localhost:3306";
}
#Override
public void run() {
try {
connect();
createDatabase();
// dropTable("user_account");
createUserAccountTable();
commit();
disconnect();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void connect() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://"
+ databaseAddress + "/?" + "user=" + logon + "&password="
+ password);
statement = connection.createStatement();
}
private void createDatabase() throws SQLException {
String sql = "create database if not exists accounts";
statement.execute(sql);
displayUpdateCount(sql);
sql = "use accounts";
statement.execute(sql);
displayUpdateCount(sql);
sql = "set names 'utf8'";
statement.execute(sql);
displayUpdateCount(sql);
}
private void createUserAccountTable() throws SQLException {
String sql = "create table if not exists user_account ( " +
"user_account_number integer not null auto_increment, " +
"user_account_name varchar(40) not null, " +
"created_timestamp timestamp not null default current_timestamp, " +
"last_used_timestamp timestamp not null, " +
"primary key (user_account_number)) " +
"engine=InnoDB, " +
"character set=utf8, " +
"auto_increment=10000000 ";
statement.execute(sql);
displayUpdateCount(sql);
}
void dropTable(String tableName) throws SQLException {
String sql = "drop table if exists " + tableName;
statement.execute(sql);
displayUpdateCount(sql);
}
private void commit() throws SQLException {
String sql = "commit";
statement.execute(sql);
displayUpdateCount(sql);
}
private void displayUpdateCount(String sql) throws SQLException {
int count = statement.getUpdateCount();
StringBuilder builder = new StringBuilder();
builder.append("Executing SQL \"");
if (sql.length() > 40) builder.append(sql.substring(0, 40));
else builder.append(sql);
builder.append("\" resulted in ");
builder.append(count);
builder.append(" row");
if (count != 1) builder.append("s");
builder.append(" changed");
System.out.println(builder.toString());
}
private void disconnect() throws SQLException {
statement.close();
connection.close();
}
public static void main(String[] args) {
if (args.length != 2) {
String s = "The logon and password for the database " +
"must be provided.";
System.err.println(s);
} else {
new CreateDatabase(args[0], args[1]).run();
}
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have created a database table where I have id, username, password and email as columns. My xml has 3 elements, Username, password edittexts and a signin button.
Method validateLogin in DatabaseActivity.java does the validation.
Error
The method getWritableDatabase() is undefined for the type DbHelper
in line ----- SQLiteDatabase db = mydb.getWritableDatabase();----
This is my DatabaseActivity.java file
package com.login.recscores;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint("Registered")
public class DatabaseActivity extends Activity implements OnClickListener {
Button mLogin;
Button mNewUser;
Button mShowAll;
EditText mUsername;
EditText mPassword;
DbHelper mydb = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mNewUser = (Button)findViewById(R.id.sign_in_button);
mNewUser.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.sign_in_button:
mUsername = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, DatabaseActivity.this);
if(validLogin){
System.out.println("In Valid");
Intent i = new Intent(DatabaseActivity.this, UserHome.class);
startActivity(i);
finish();
}
}
break;
}
}
// #SuppressWarnings("deprecation")
public boolean validateLogin(String uname, String pass, Context context) {
mydb = new DbHelper(this);
SQLiteDatabase db = mydb.getWritableDatabase();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "username=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uname,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE username=uname AND password=pass
cursor = db.query(DbHelper.RECSCORES_TABLE_NAME, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Wha Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onDestroy(){
super.onDestroy();
mydb.close();
}
}
The DbHelper.java is
package com.login.recscores;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper {
private static final String DATABASE_NAME = "recscores.db";
public static final String KEY_ROWID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";
private static final String TAG = "DbHelper";
private static final int DATABASE_VERSION = 1;
public static final String RECSCORES_TABLE_NAME = "users";
private static final String RECSCORES_TABLE_CREATE =
"CREATE TABLE " + RECSCORES_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"username VARCHAR NOT NULL, password VARCHAR NOT NULL, email VARCHAR NOT NULL);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DbHelper(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(RECSCORES_TABLE_CREATE);
}
#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 titles");
onCreate(db);
}
}
//---opens the database---
public DbHelper open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertTitle(String Id, String username, String password, String email)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ROWID, Id);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_EMAIL, email);
return db.insert(RECSCORES_TABLE_NAME, null, initialValues);
}
//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return db.delete(RECSCORES_TABLE_NAME, KEY_ROWID +
"=" + rowId, null) > 0;
}
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(RECSCORES_TABLE_NAME, new String[] {
KEY_ROWID,
KEY_USERNAME,
KEY_PASSWORD,
KEY_EMAIL},
null,null,null,null,null);
}
//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, RECSCORES_TABLE_NAME, new String[] {
KEY_ROWID,
KEY_USERNAME,
KEY_PASSWORD,
KEY_EMAIL
},
KEY_ROWID + "=" + rowId,
null,null,null,null,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a title---
public boolean updateTitle(long rowId, String isbn,
String title, String publisher)
{
ContentValues args = new ContentValues();
args.put(KEY_USERNAME, isbn);
args.put(KEY_PASSWORD, title);
args.put(KEY_EMAIL, publisher);
return db.update(RECSCORES_TABLE_NAME, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
getWritableDatabase is a method on DatabaseHelper, not DbHelper. For example:
In your DbHelper.java, you use get getWritableDatabase as follows:
db = DBHelper.getWritableDatabase();
where you are declaring:
private DatabaseHelper DBHelper;
So you are calling getWritableDatabase on an instance of DatabaseHelper
However on the problem line you have this:
mydb = new DbHelper(this);
SQLiteDatabase db = mydb.getWritableDatabase();
This is attempting to call getWritableDatabase on an instance of DbHelper, which you haven't declared.
Note that you're use of a DBHelper variable within your declaration of a class called DbHelper is confusing in the extreme, and likely is the cause of the misunderstanding.
Im just starting to learn how to create and use a database.
Here is the error I get:03-23 01:34:35.861: E/AndroidRuntime(613): Caused by: android.database.sqlite.SQLiteException: near "in": syntax error: , while compiling: create table payouts(_id integer primary key autoincrement, date text not null, casino text not null, game text not null, in text not null, out text not null, gain text not null);
I have gone over it, and I cant seem to figure out why it will not work.
Any help would be much appreciated.
package kris.databasetester;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_CASINO = "casino";
public static final String KEY_GAME = "game";
public static final String KEY_IN = "in";
public static final String KEY_OUT = "out";
public static final String KEY_GAIN = "gain";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "casinodb";
private static final String DATABASE_TABLE = "payouts";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table payouts(_id integer primary key autoincrement, " + "date text not null, casino text not null, " + "game text not null, in text not null, out text not null, gain text not null);";
// private static final String date = null;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
} //DBAdapter Closer
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
} //onCreate Closer
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destory all old data");
db.execSQL("DROP TABLE IF EXISTS payouts");
onCreate(db);
} //onUpgrade Closer
} //DatabaseHelper Closer
//Opens the Database
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//DBAdapter Open Closer
//Closes the Database
public void close()
{
DBHelper.close();
} //DBAdapter Close Closer
//Insert a GamePlay into Database
public long insertTitle(String date, String casino, String game, String in, String out, String gain)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_CASINO, casino);
initialValues.put(KEY_GAME, game);
initialValues.put(KEY_IN, in);
initialValues.put(KEY_OUT, out);
initialValues.put(KEY_GAIN, gain);
return db.insert(DATABASE_NAME, null, initialValues);
} //Insert Title Closer
// Deletes a particular title
public boolean deleteTitle(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
} //Delete Title Closer
//Retrieves all titles
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID, KEY_DATE, KEY_CASINO, KEY_GAME, KEY_IN, KEY_OUT, KEY_GAIN
},null, null, null, null, null);
} //Gets all titles closer
//Retrieves a particular Title
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[]
{KEY_ROWID, KEY_DATE, KEY_CASINO, KEY_GAME, KEY_IN, KEY_OUT, KEY_GAIN},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
} //getTitle Closer
//Updates a title
// public boolean updateTitle(long rowId, String KEY_DATE, String KEY_CASINO, String KEY_GAME, String KEY_IN, String KEY_OUT, String KEY_GAIN)
// {
// ContentValues args = new ContentValues();
// args.put(KEY_DATE, date);
// args.put(KEY_CASINO, casino);
// args.put(KEY_GAME, game);
// args.put(KEY_IN, in);
// args.put(KEY_OUT, out);
// args.put(KEY_GAIN, gain);
// return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// } //Update Title Closer
} //Class Closer
-----------------------------
package kris.databasetester;
import android.app.Activity;
import android.os.Bundle;
public class DatabaseTesterActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
#SuppressWarnings("unused")
DBAdapter db = new DBAdapter(this);
//---add 2 titles---
db.open();
// long id;
// id = db.insertTitle("09/08/2012","The Sands","BlackJack", "400", "500", "100");
// db.close();
}
}
-------------------------------
it's telling you that in is not an allowable name for a column, which is because it's reserved for other uses in the SQL language.
i am having this problem with the android database. I adopted the DBAdapter file the NotepadAdv3 example from the google android page.
DBAdapter.java
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "PasswordDb";
private static final String DATABASE_TABLE = "myuserdata";
private static final String DATABASE_USERKEY = "myuserkey";
private static final int DATABASE_VERSION = 2;
public static final String KEY_USERKEY = "userkey";
public static final String KEY_TITLE = "title";
public static final String KEY_DATA = "data";
public static final String KEY_ROWID = "_id";
private final Context mContext;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DB_CREATE_KEY =
"create table " + DATABASE_USERKEY
+ " ("
+ "userkey text not null"
+");";
private static final String DB_CREATE_DATA =
"create table " + DATABASE_TABLE
+ " ("
+ "_id integer primary key autoincrement, "
+ "title text not null"
+ "data text"
+");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE_KEY);
db.execSQL(DB_CREATE_DATA);
}
#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 myuserkey");
db.execSQL("DROP TABLE IF EXISTS myuserdata");
onCreate(db);
}
}
public DBAdapter(Context ctx)
{
this.mContext = ctx;
}
public DBAdapter Open() throws SQLException{
try {
mDbHelper = new DatabaseHelper(mContext);
}
catch(Exception e){
Log.e(TAG, e.toString());
}
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
mDbHelper.close();
}
public Long storeKey(String userKey){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERKEY, userKey);
try {
mDb.delete(DATABASE_USERKEY, "1=1", null);
}
catch(Exception e)
{
Log.e(TAG, e.toString());
}
return mDb.insert(DATABASE_USERKEY, null, initialValues);
}
public String retrieveKey() {
final Cursor c;
try {
c = mDb.query(DATABASE_USERKEY, new String[] {
KEY_USERKEY},
null,
null,
null,
null,
null);
}catch(Exception e){
Log.e(TAG, e.toString());
return "";
}
if(c.moveToFirst()){
return c.getString(0);
}
else{
Log.d(TAG, "UserKey Empty");
}
return "";
}
//not including any function related to "myuserdata" table
}
Class1.java
{
mUserKey = mDbHelper.retrieveKey();
mDbHelper.storeKey(Key);
}
the error that i am receiving is from Log.e(TAG, e.toString()) in the methods retrieveKey() and storeKey()
"no such table: myuserkey: , while compiling: SELECT userkey FROM myuserkey"
Did you pop the DB version so onUpgrade fires? You're at version 2 in the example above but if you changed the schema since version 2 then you need to pop the version again.
i think you are not mention your provider tag in AndroidManifest.xml .Check it.
u have to mention the tag like
<provider android:name=".name of providerclass"
android:authorities="authority path" />