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.
Related
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: <<<<<
Helli! I encountered a database problem. I myself am an inexperienced programmer, I ask your help. when I run the game quiz game loaded long, that is, long loads of questions database. Here here the database structure:
DROP TABLE IF EXISTS QUESTION;
DROP TABLE IF EXISTS ANSWER;
CREATE TABLE ANSWER (id_answer INTEGER PRIMARY KEY, id_question NUMERIC, answer_text TEXT, correct NUMERIC);
INSERT INTO ANSWER VALUES(1,1,'Murmillo',0);
INSERT INTO ANSWER VALUES(2,1,'Retiarius',0);
INSERT INTO ANSWER VALUES(3,1,'Rudiarius',1);
INSERT INTO ANSWER VALUES(4,1,'Secutor',0);
INSERT INTO ANSWER VALUES(5,2,'Augustus',0);
INSERT INTO ANSWER VALUES(6,2,'Caligula',0);
INSERT INTO ANSWER VALUES(7,2,'Caracalla',0);
INSERT INTO ANSWER VALUES(8,2,'Felix',1);
.......
CREATE TABLE QUESTION (id_question INTEGER PRIMARY KEY, text TEXT, difficulty NUMERIC, topic TEXT);
INSERT INTO QUESTION VALUES(1,'How were the gladiators in ancient Rome, who earned freedom but decided to remain gladiators, called? ',10,'history');
INSERT INTO QUESTION VALUES(2,'Which agnomen did Lucius Cornelius Sulla acquire?',7,'history');
Class DataBaseHelper code:
package db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static int DB_VERSION = 1;
private static String DB_NAME = "quiz";
//tables' variables descriptions
public static final String TABLE_QUESTION = "Question";
public static final String TABLE_ANSWER = "Answer";
public boolean _should_fill = false;
private SQLiteDatabase myDataBase;
public boolean shouldFill(){
return _should_fill;
}
private DatabaseHelper(Context context){
super(context, DB_NAME, null, (DB_VERSION+1));
}
private static DatabaseHelper instance = null;
public static DatabaseHelper getInstance(Context context)
{
if (instance == null)
instance = new DatabaseHelper(context);
return instance;
}
public void setDataBase(SQLiteDatabase db)
{
myDataBase = db;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
_should_fill = true;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+ TABLE_QUESTION);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_ANSWER);
onCreate(sqLiteDatabase);
}
// TODO: select a question randomly
// hint: SELECT * FROM table ORDER BY RANDOM() LIMIT 1;
// more TODO: retrieve a question which id is not equal to a specified id
public TestQuestion getQuestionWithAnswers(String topic, long quest_number, long curQuestId)
{
//quest_number is the number of the question or difficulty(in db)
//first we will select the important question
Cursor cursor = null;
if (curQuestId == -1)
{
if (topic != null)
cursor = myDataBase.rawQuery(
"SELECT * FROM Question WHERE difficulty=? AND topic=? ORDER BY RANDOM() LIMIT 1",
new String[] { String.valueOf(quest_number), topic });
else
cursor = myDataBase.rawQuery(
"SELECT * FROM Question WHERE difficulty=? ORDER BY RANDOM() LIMIT 1",
new String[] { String.valueOf(quest_number)});
cursor.moveToFirst();
}
else
{
if (topic != null)
cursor = myDataBase.rawQuery(
"SELECT * FROM Question WHERE difficulty=? AND topic=? ORDER BY RANDOM()",
new String[] { String.valueOf(quest_number), topic });
else
cursor = myDataBase.rawQuery(
"SELECT * FROM Question WHERE difficulty=? ORDER BY RANDOM()",
new String[] { String.valueOf(quest_number)});
cursor.moveToFirst();
long qId = cursor.getLong(cursor.getColumnIndex("id_question"));
while (curQuestId == qId)
{
if (cursor.moveToNext())
qId = cursor.getLong(cursor.getColumnIndex("id_question"));
else
{
cursor.moveToFirst();
break;
}
}
}
//let's get the selected question
Question question = new Question(
cursor.getLong(cursor.getColumnIndex("id_question")),
cursor.getString(cursor.getColumnIndex("text")),
quest_number,
cursor.getString(cursor.getColumnIndex("topic"))
);
System.out.println(question.getText()+" ; "+question.get_difficulty());
//this is the id of the question
long id = cursor.getLong(cursor.getColumnIndex("id_question"));
cursor.close();
//let's select the answers for this question
Cursor curs = myDataBase.rawQuery(
"SELECT * FROM Answer WHERE id_question=?",
new String[] { String.valueOf(id) }
);
Answer[] answers = new Answer[4];
if(curs != null){
if (curs.moveToFirst()){
int i = 0;
do{
answers[i++] = new Answer(
curs.getLong(curs.getColumnIndex("id_answer")),
curs.getString(curs.getColumnIndex("answer_text")),
id,
curs.getLong(curs.getColumnIndex("correct"))
);
} while(curs.moveToNext());
}
};
LinkedHashMap<Question, ArrayList<Answer>>();
TestQuestion tQuestion = new TestQuestion(question,answers);
return tQuestion;
}
}
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.
I made an application with an SQLite database. I want to show the data in a listview, but I don't want to show all the data from the database, but just some data. So, I want to add a condition. I only want to show the data where string 'dag' is 'maandag'.
Can anyone help me?
This is the code from my DatabaseHelper, where the database is created:
package com.persoonlijk.rooster.test2;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.util.ArrayList;
import java.util.List;
//A helper class to manage database creation and version management.
public class DataManipulator
{
//Database attributes
private static final String DATABASE_NAME = "mydatabase.db";
static final String TABLE_NAME = null;
private static final int DATABASE_VERSION = 12;
//Table attributes
public static final String KEY_ROWID = "id";
public static final String KEY_DAG = "dag";
public static final String KEY_UUR = "uur";
public static final String KEY_VAK = "vak";
public static final String KEY_LOKAAL = "lokaal";
private static Context context;
static SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME + " (dag,uur,vak,lokaal) values (?,?,?,?)";
public DataManipulator(Context context) {
DataManipulator.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulator.context);
DataManipulator.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulator.db.compileStatement(INSERT);
}
public long insert(String dag,String uur,String vak,String lokaal) {
this.insertStmt.bindString(1, dag);
this.insertStmt.bindString(2, uur);
this.insertStmt.bindString(3, vak);
this.insertStmt.bindString(4, lokaal);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","dag","uur","vak","lokaal" }, null, null, null, null, "dag asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long id) {
return db.delete(TABLE_NAME, KEY_ROWID + "=" + id, null) > 0;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, dag TEXT, uur TEXT, vak TEXT, lokaal TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
This is the code from the Activity where I want to display the specific data. Right now, all the data from the database is displayed.
package com.persoonlijk.rooster.test2;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RoosterMaandag extends ListActivity{
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
/** Called when the activity is first created. */
//zorgt voor het overzicht van de gegevens uit de database
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.rooster);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] dag : names2) {
stg = dag[1]+" - "+dag[2]+ " - "+dag[3]+" - "+dag[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
//menuknoppen
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, 0, 0, "Voeg gegevens toe");
menu.add(Menu.NONE, 1, 1, "Verwijder gegevens");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, SaveData.class));
return true;
case 1:
startActivity(new Intent(this, VerwijderData.class));
return true;
}
return false;
}
}
Please let me know when my question isn't clear enough. I really hope someone can help me!
I added this code in my DataManipulator.java:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
and this code in my RoosterMaandag.java:
public void onCreate(Bundle savedInstanceState){
....
dm.selectSome("maandag");
....
}
I don't know about android but for sql
try this
select data_to_print from table_name where REGEXP_LIKE(column_name_where_to_match,'dag$');
more info here http://docs.oracle.com/cd/B12037_01/server.101/b10759/ap_posix001.htm#i690819
Example:
SQL> select job_id from jobs where regexp_like(job_id,'N$');
JOB_ID
----------
MK_MAN
PU_MAN
SA_MAN
ST_MAN
you need a new method in your DataManipulator class:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
I'll say it again. consider using a CursorAdapter for these tasks.
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.