I have this piece of code, that helps me to manage the db, but I do not know when a data base is created
package es.aadesigners.pruebabd;
/**
* Created by Andrea on 29/2/16.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {
public AdminSQLiteOpenHelper(Context context, String nombre, SQLiteDatabase.CursorFactory factory, int version) {
super(context, nombre, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//aquĆ creamos la tabla de usuario (dni, nombre, ciudad, numero)
db.execSQL("create table usuario(dni integer primary key, nombre text, ciudad text, numero integer)");
}
}
I also have a doubt on the Super sentence
Super creates a helper object to create, open, and/or manage a database. The database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.
Source:https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
Related
I am trying to open a database in Android Studio using the line:
SQLiteDatabase gardenDatabase = openOrCreateDatabase("myDatabase",MODE_PRIVATE,null);
but it gives me the error Cannot resolve symbol 'MODE_PRIVATE'. I don't understand what is wrong as have used the exact same line of code elsewhere in my project in different classes and it has worked fine before.
My full code:
public class MyWorker extends Worker {
public MyWorker (#NonNull Context context, #NonNull WorkerParameters params) {
super(context, params);
}
#Override
public Result doWork() {
SQLiteDatabase myDatabase = openOrCreateDatabase("myDatabase",MODE_PRIVATE,null);
//Do stuff
return Result.success();
}
}
Imports:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import androidx.work.Result;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import static android.database.sqlite.SQLiteDatabase.openOrCreateDatabase;
I have been using this site to help write my database code: https://www.tutorialspoint.com/android/android_sqlite_database.htm
As you can see in the comments under your question, #BarryFruitman pointed out that:
SQLiteDatabase. openOrCreateDatabase() doesn't even take a "mode" as a
second param
and after that I commented:
this openOrCreateDatabase() is a method of the ContextWrapper class
and we are both right.
The problem is revealed now after you posted the link of the tutorial you follow.
Indeed in this tutorial, this method is proposed:
SQLiteDatabase myDatabase = openOrCreateDatabase("myDatabase",MODE_PRIVATE,null);
and this belongs to ContextWrapper class,
but in the same tutorial the mentioned signatures of openOrCreateDatabase() are:
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
and
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
which are both members of the SQLiteDatabase class.
I believe that this is the tutorial's mistake.
So change to this:
SQLiteDatabase gardenDatabase = SQLiteDatabase.openOrCreateDatabase(databaseNameWithPath, null);
which uses the method from SQLiteDatabase class.
EditOf course you have to provide for the variable databaseNameWithPath a fully qualified path and database name, like:
String databaseNameWithPath = "/data/data/" + <yourpackagename> + "/databases/" + "myDatabase";
and create the directory if it does not already exist.
You haven't imported that constant:
import static android.content.Context.MODE_PRIVATE;
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();
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.