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;
}
}
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 have entities like this : User->Blague->Score where an user have numerous blagues(childs) and a blague have one score.
I'm trying to get the score from a blague, but when I write this :
User userPoster = ofy().load().type(User.class).id(5066549580791808L).now();
Blague blague = ofy().load().type(Blague.class).parent(userPoster).id(4609152743636992L).now();
Score score = ofy().load().type(Score.class).parent(blague).id(5735052650479616L).now();
resp.getWriter().println(userPoster);
resp.getWriter().println(blague);
resp.getWriter().println(score);
(The ids are corrects) score is null, unlike blague and userPoster. Why is it null ?
The entities are created like that :
#ApiMethod(
name = "addBlague",
path = "addBlague",
httpMethod = ApiMethod.HttpMethod.POST)
public void addBlague(
#Named("category") EnumCategory category,
#Named("type") EnumType type,
#Named("lenght") EnumLenght lenght,
#Named("keywords") List<String> keywords,
#Named("text") String text,
#Named("userId") Long userId){
Key<User> userKey = Key.create(User.class, userId);
Blague blague = new Blague(category, type, lenght, text, userKey);
ofy().save().entity(blague).now();
Key<Blague> blagueKey = Key.create(Blague.class, blague.getId());
Score score = new Score(0, 0, blagueKey);
ofy().save().entity(score).now();
for (String word : keywords) {
KeyWord keyword = new KeyWord(word, blagueKey);
ofy().save().entity(keyword);
}
}
and of course, the classes are registered.
How can I get the score from a blague ?
Thanks
Edit :
The Socre code :
package blagueur;
import java.util.HashMap;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Parent;
#Entity
#Index
#Cache
public class Score {
#Id
private Long id;
private int likes;
private int dislikes;
private HashMap<String, Boolean> voters;
#Parent
private Key<Blague> blagueKey;
private Score() {}
public Score(int likes, int dislikes, Key<Blague> blague) {
this.likes = likes;
this.dislikes = dislikes;
this.blagueKey = blague;
this.voters = new HashMap<String, Boolean>();
}
public Long getId() {
return id;
}
public int getLikes() {
return likes;
}
public int getDislikes() {
return dislikes;
}
public void addVote(Long userId, boolean like){
voters.put(String.valueOf(userId), like);
if (like){
likes++;
}
else{
dislikes++;
}
}
public void removeVote(Long userId){
String id = String.valueOf(userId);
boolean like = voters.get(String.valueOf(userId));
voters.remove(String.valueOf(userId));
if (like){
likes--;
}
else{
dislikes--;
}
}
public Key<Blague> getBlagueKey() {
return blagueKey;
}
}
You need to be very careful to maintain the key hierarchy.
You state that your intended entity hierarchy is User -> Blague -> Score, but this code below does not do that:
Key<User> userKey = Key.create(User.class, userId);
Blague blague = new Blague(category, type, lenght, text, userKey);
ofy().save().entity(blague).now();
Key<Blague> blagueKey = Key.create(Blague.class, blague.getId());
Score score = new Score(0, 0, blagueKey);
ofy().save().entity(score).now();
When you create the blagueKey, you do not use the userKey as the parent.
While I do not encourage the code style you have written, if you wanted to do so, you need to do this:
...
Key<Blague> blagueKey = Key.create(userKey, Blague.class, blague.getId());
...
In general, you should let objectify handle this for you by using Ref<User>, Ref<Blague> as the #Parent objects, or if you must create Key objects, use Key.create(T pojo) rather than managing Keys yourself.
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.