Hi I have been working on a project that requires a database to store answers, hints, etc and I have added one row into the database using a method. I also made a getAnswer method that uses a rawQuery() to get the answer in the specified row (1) for the first and only item added in the database.
So the database class is all finished and I want to use the database for my game. I'm assuming it has to run the method once to fill the database (couldn't figure out better way to do an internal database so it will run every time the game is opened, if you know a better way I'm all ears). However in my Main Activity I can't seem to call the method that fills the database or the method to retrieve an item from the database. I have been looking and I don't understand why it is not working.
I am posting the Main Activity first and then the Game Database. Any help on how to use my database is greatly appreciated.
Main Activity Class
package tekvision.codedecrypter;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import gameInfo.GameDatabase;
public class MainActivity extends ActionBarActivity {
//Runs before the application is created
public Button mCampaignButton;
//When the application is created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
// I wanted to call it heat and use it in a toast to make sure its working
//Gamedatabase. does not work to find my method
//
//Keeps screen on so it doesn't fall asleep
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//Finding button by button id after application is created
mCampaignButton = (Button)findViewById(R.id.campaignButtonID);
//Checks if the campaign button is clicked
mCampaignButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast pop up message
Toast toast = Toast.makeText(getApplicationContext(),
"campaign select",
Toast.LENGTH_SHORT);
toast.show();
//Intent to go from main activity to campaign Level Select Activity
Intent intent = new Intent(MainActivity.this, CampaignSelectLevel.class);
startActivity(intent);
}
});
}
}
Game Database Class
package gameInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by User on 06/06/2015.
*/
//Extends the sql database open helper it will be error until the 2 methods are added plus the constructor
//the database is saved to a text file
public class GameDatabase extends SQLiteOpenHelper {
//Version number of the database
//Every update to the database will result in going up in the database version number
private static final int DATABASE_VERSION = 1;
//Private set of final strings, for the column names in the database
private static final String DATABASE_NAME =
"Database",
TABLE_1 = "Answers and Hints",
TABLE_2 = "classical",
TABLE_3 = "ancient",
KEY_ID = "id",
KEY_HINT = "hint",
KEY_ANSWER = "answer",
KEY_QUESTION = "question",
KEY_INFO = "info",
KEY_IMAGE = "image";
//Database Constructor, sets the databases named and the version of the database
public GameDatabase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Whenever database is created
//Creating a table with each column and specify each columns type such as text or integer that is the primary key
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE_1 + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_QUESTION + " TEXT" + KEY_ANSWER + " TEXT" + KEY_IMAGE + "IMAGEVIEW" + KEY_HINT + " TEXT" + KEY_INFO + " TEXT)");
}
//When the database is upgraded
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MODERN);
onCreate(db);
}
//Currently should have ONE row for level on in modern
public void fillGameDatabase(){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
//Fills information for the first row by a few columns
//Modern ERA
values.put(KEY_QUESTION, "US President");
values.put(KEY_ANSWER, "Barack Obama");
values.put(KEY_HINT, "He is the first African American president");
values.put(KEY_INFO, "Barack Obama is the 44th President of the United States, and the first African American to hold the office. Born in Honolulu, Hawaii, Obama is a graduate of Columbia University and Harvard Law School, where he served as president of the Harvard Law Review. He was a community organizer in Chicago before earning his law degree. He worked as a civil rights attorney and taught constitutional law at University of Chicago Law School from 1992 to 2004. He served three terms representing the 13th District in the Illinois Senate from 1997 to 2004, running unsuccessfully for the United States House of Representatives in 2000.");
values.put(KEY_IMAGE, "R.drawable.obama.jpg");
db.insert(TABLE_MODERN, null, values); //inserted a new row into the database
db.close();
}
//Gets the answers based on the era nd level provided,
//db is database extension dont need to pass it
public Cursor getAnswer(String table, int level){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor;
//All one row of data
String[] projections = {KEY_QUESTION, KEY_ANSWER, KEY_HINT, KEY_INFO, KEY_IMAGE};
//Calling query method
//Pass table name, the projections(names of columns), selection (data argument), selection arguments, group rows
//filter by row groups, sort order, you can pass null for ones you dont want to enter
cursor = db.rawQuery("SELECT " + KEY_ANSWER + " FROM " + TABLE_MODERN + " WHERE " + KEY_ID + "=" + level, null);
db.close();
return cursor;
}
/*
public Cursor getKeyHint(String era, int level{
SQLiteDatabase db = getReadableDatabase();
}
public Cursor getKeyQuestion(String era, int level{
}
public Cursor getKeyInfo(String era, int level{
}
public Cursor getKeyInfo(String era, int level{
}
*/}
I made the database from watching videos and reading documentation, but I have no clue how to actually "use" it. Thank you for reading, hope you can help.
I would recommend you to learn some basic SQL queries. Find some lessons like here. It shouldn't take you more than an hour or two to get the hang of it.
For your code specifically, the getAnswer() is good, it generates a valid query to access the database. You never actually use this method anywhere though. Put it in your MainActivity, probably in some onClick() method where the user asks for the answer to the question. I don't think you have started implementing this yet.
Related
I am creating an android based Appointment management system. For storing appointments I'm using an SQLite database. The application works flawlessly but the only problem is that the Database gets recreated every time I restart the application it self. Following is my onCreate and onUpgrade methods. (PS. I used a video tutorial on creating and connecting the database. This worked fine on him. Only difference is I'm using a Mac and he was using Windows)
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, DATE TEXT, TIME TEXT, TITLE TEXT, DETAIL TEXT, UNIQUE(DATE, TITLE))");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXITS" + TABLE_NAME);
onCreate(db);
}
Just in case I have uploaded my full database connection code here, Database.java
Hard to tell without seeing the entire class, but you may be inadvertently deleting the database somewhere? Look for calls to deleteDatabase that may be buried somewhere, particularly if you based your code of a tutorial that may have left bits and pieces of code in place.
I am working in android app project in which I am storing data into a local db which is sqlite for store data offline.Data size is minimal which is basically like name,mobile no etc.I store those data into sqlite because i consider that app client don't have internet connection or he store multiple data so he can store data locally,and the next part is send data into a sql server with a button click.I can't work with synchronization because of sql server (Central remote server) have lot's of table and lot's data,i don't want to rush my local android app db.I am tryed to fetch data with while loop and then fetch data from sqlite and then send data sql server directly(i don't use api because security is not a concern here)
enter code here
package com.ohnnu.myofficetool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by joy on 11/4/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="myofficetool.db";
public static final String TABLE_NAME="orderChalan_table";
public static final String COL_1="ID";
public static final String COL_2="ProdNo";
public static final String COL_3="Qtn";
public static final String COL_4="CusID";
public String delete;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT,ProdNo TEXT,Qtn TEXT,CusID TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
public Cursor getAllData(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
}
What i am trying now to fetch information in asynctask after that send the fetch data into sql server.Please suggest me how to fetch information in aynctask,
you need to use webservices to send data to webserver.
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I'm try to create a new database and table in my constructor class, but I find in this line error:
db.execSQL("CREATE TABLE IF NOT EXIST tblApp ( _ID INTEGER PRIMARY kEY AUTOINCREMENT UNION, Title TEXT )",null);
and crashed my app.
This is my class:
package ir.rezvania.modirbash;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class db {
Context ctx;
Cursor crs;
private SQLiteDatabase db;
public db(Context ctx){
this.ctx=ctx;
db = ctx.openOrCreateDatabase("`dbApp`", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXIST `tblApp` ( _ID Integer Primary key autoincrement union, Title Text )",null);
}
public void Insert(String FILDS,String VALUES){
db.execSQL("INSERT INTO `tblApp` ("+FILDS+")VALUES("+VALUES+");");
}
public void Update(String ID,String COLUMN,String VALUE){
db.execSQL("UPDATE `tblAPP` SET"+COLUMN+"="+VALUE+"WHERE _ID="+ID+";");
}
public void Delete(String ID){
db.execSQL("DELETE FROM `tblApp` WHERE _ID="+ID+";");
}
public Cursor Show(){
crs=db.rawQuery("SELECT * FROM `tblApp`",null);
return crs;
}
public void finalize(){
db.close();
}
}
Your table creation fails, because you're using the wrong wording. It's IF NOT EXISTS you need to use. For simplicity you should use caps for all keys. Also you don't need to use ` since tblApp is not a keyword, union doesn't make any sense where you put it and AUTOINCREMENT is not needed.
db.execSQL("CREATE TABLE IF NOT EXISTS tblApp (_ID INTEGER PRIMARY KEY, Title TEXT)", null);
In SQLite a column declared INTEGER PRIMARY KEY will autoincrement. There is no autoincrement keyword in SQLite, that is why you are getting an error.
You can find out more on SQLite FAQ.
I have created a database named "company" using android studio. When I want to view the database I created, I can't find it.
I follow the step below
Open DDMS via Tools > Android > Android Device Monitor
and see my project name on the left.
However, when I go to File Explorer,go to /data/data/com.example.project.project, I didn't see the database created which should under database package. There only have two folder there, one is cache and another is code_cache. What steps I have missed out? Hope someone can help me to figuring out the problem. Thanks
MyDataBaseHelper.java
package com.example.project.project.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME="Company.db";
public final static String TABLE_NAME="TimeSheet";
public static final String ID="id";
public static final String Name="name";
public static final String Weather="weather";
// public static final String DATABASE_CREATE_TIME_SHEET="create table"+TABLE_NAME+"(+ Name+"TEXT,"+ Weather+"TEXT)";
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table "+TABLE_NAME+"(name text,weather text)");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion)
{
Log.w(MyDatabaseHelper.class.getName(),"Upgrading database from version"+oldVersion+"to"+newVersion+",which will destroy all old data");
db.execSQL("Drop TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public MyDatabaseHelper(Context context)
{
super(context, DATABASE_NAME,null,1);
}
}
Step 1] Download SQLite Manager in Mozilla Fire Fox.
Step 2] Open Android Device Monitor.
Step 3] Find your Database .
Step 4] Pull your database file to desktop or anywhere.
step 5] Start SQlite Manager from Mozilla.
step 6] Import your database in SQLite Manager.
In SQLite Manager you can see your database ,database table ,records,etc.
Missed out this
database=dbHelper.getWritableDatabase();
I have my database created in event onCreate, in which I have a lot of tables, but I need add 1 more table, and I can't lose any data, So I need to use the event onUpgrade, So I hope you guys help me because I don't know how to use it.
Example :
public void onCreate(SQLiteDatabase db) {
sql = "CREATE TABLE IF NOT EXISTS funcionarios"
+"(codigo INTEGER PRIMARY KEY, funcionario TEXT, apelido TEXT , functionTEXT, cartao TEXT , foto TEXT , tipo_foto TEXT);";
db.execSQL(sql);
}
what i need is
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion < 2){
db.execSQL("CREATE TABLE IF NOT EXISTS calibrar_aceleracao"+
"(limiteMaximo INTEGER, limiteMinimo INTEGER);");
}
}
but it doesn't work.
thanks.
You do not need to change you applications version to update your database - not saying it is incorrect but there is a more efficient way of doing it. And that is through the use of the super's constructor of your helper it would look something like the following:
public class MyDatabaseHelper extends SQLiteOpenHelper {
public MyDatabaseHelper(Context context) {
super(context, "My.db", null, 1 /* This is the version of the database*/);
}
#Override
public void onCreate(SQLiteDatabase database) {
sql = "CREATE TABLE IF NOT EXISTS funcionarios (codigo INTEGER PRIMARY KEY, funcionario TEXT, apelido TEXT , functionTEXT, cartao TEXT , foto TEXT , tipo_foto TEXT);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
if(oldVersion < 2){
db.execSQL("CREATE TABLE IF NOT EXISTS calibrar_aceleracao (limiteMaximo INTEGER, limiteMinimo INTEGER);");
}
}
}
The method onUpgrade is called when your version database is incremented. Verify in your class where you define your database version and increment this value.
Run application. Your method onUpgrade is called.
For onUpgrade to get called you must increase the database version that you supply to the SqliteOpenHelper implementation constructor.
Use a field in your class to store the same and increment it when you change your database schema.
This is not the way onUpgrade works.This is a method which will be called when you release some new version of your application and make it available for download in google play(and which may be requiring some updations to the database of the application already installed on users' devices').For your problem's solution
Just add the query of CREATE TABLE IF NOT EXISTS in your onCreate() as you did for the creation of the other table in your onCreate() method already
public void onCreate(SQLiteDatabase db) {
sql = "CREATE TABLE IF NOT EXISTS funcionarios"
+"(codigo INTEGER PRIMARY KEY, funcionario TEXT, apelido TEXT , functionTEXT, cartao TEXT , foto TEXT , tipo_foto TEXT);";
///HERE YOUR Create Table QUERY and call db.execSQL
db.execSQL(sql);
}
The method is onUpgrade is not being called probably because there are errors in the sql code, for example in the onCreate:
functionTEXT
is missing a space before TEXT.
Also after,
calibrar_aceleracao"+ "(limiteMaximo
is missing a space before the bracket.
I had the same problem, I was caching the SQLiteException so I didn't see the error was there.
Put some logcat at the beginning and at the end of the method body and you'll see where the error is.
EDIT: another thing, why did you put that if?
if (oldVersion < 2)
It's not necessary at all.