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();
Related
I'm new to Android Studio and SQLite and wanted to run a query when the app is run for the very first time only, and when the app is run again it wont run the query again.
This will depend upon how you are accessing the database.
The most common way is to utilise the SQLiteOpenHelper class. In which case the onCreate method is called when the database is created. The database only ever being created the once (unless it is deleted e.g. the App uninstalled).
When onCreate is called the database will have been created BUT will not have any components (tables, indexes, views, triggers) other than some system components. Typically this is where the components are created but meets the criteria of your question IF using a class that extends SQLiteOpenHelper. However, unless the query is to store data, it would probably be of little use as there would be no data to query.
However, using a class that extends SQLiteOpenHelper is not the only way in which an SQLite database can be accessed, nor would onCreate be called if you were utilising a pre-existing database copied from the assets folder of the package (e.g. using SQLiteAssetHelper).
In these latter cases, you could test to see if the database actually exists and set a flag/indicator. If it does not and then after opening the database you could then check the indicator and run the query.
Demonstration
Here's a demonstration of two methods.
The first using the more typical SQLiteOpenHelper and thus the onCreate method.
The second using an indicator.
The first method utilises a class that extends SQLiteOpenHelper called DBHelper :-
class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "thedatabase.db";
public static final int DATABASE_VERSION = 1;
private static volatile DBHelper instance;
private DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.getWritableDatabase(); //Force database open
}
public static DBHelper getInstance(Context context) {
if (instance==null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Run the query here AFTER creating the components
Log.d("DBHELPER","First run detected");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Rather than run a query, data is written to the log from within the onCreate method.
The second method utilises the SQLiteDatabase openOrCreateDatabase (i.e. circumventing using the SQLiteOpenHelper). Thus it has to do some of the things that SQLiteOpenHelper conveniently does automatically:-
class OtherDBHelper {
public static final String DATABASE_NAME = "otherdatabase.db";
public static final int DATABASE_VERSION = 1;
private static boolean databaseCreateIndicator = false;
private static boolean databaseVersionChanged = false;
private SQLiteDatabase database;
private static OtherDBHelper instance;
private OtherDBHelper(Context context) {
if (!context.getDatabasePath(DATABASE_NAME).exists()) {
databaseCreateIndicator = true;
File database_dir = context.getDatabasePath(DATABASE_NAME).getParentFile();
if (!database_dir.exists()) {
database_dir.mkdirs();
}
// Copy database from assets
}
database = SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath(DATABASE_NAME),null);
//* Database now open */
// If utilising Version number check and set the version number
// If not copying pre-existing database create components (tables etc)
if (databaseCreateIndicator) {
//<<<<<<<<<< Query here >>>>>>>>>>
Log.d("OTHERDBHELPER","First run detected");
}
}
public SQLiteDatabase getSQLiteDatabase() {
return database;
}
public static OtherDBHelper getInstance(Context context) {
if (instance==null) {
instance = new OtherDBHelper(context);
}
return instance;
}
}
again the instead of running a query outputting to the log is used.
To test both in unison then some activity code:-
public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
OtherDBHelper otherDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("PREDBMSG","Just prior to getting the databases.");
dbHelper = DBHelper.getInstance(this);
otherDBHelper = OtherDBHelper.getInstance(this);
Log.d("POSTDBMSG","Just after getting the databases.");
}
}
Results
When run for the first time then the log includes:-
2022-10-20 07:09:27.633 D/PREDBMSG: Just prior to getting the databases.
2022-10-20 07:09:27.663 D/DBHELPER: First run detected
2022-10-20 07:09:27.697 D/OTHERDBHELPER: First run detected
2022-10-20 07:09:27.697 D/POSTDBMSG: Just after getting the databases.
When run again :-
2022-10-20 07:10:41.258 D/PREDBMSG: Just prior to getting the databases.
2022-10-20 07:10:41.266 D/POSTDBMSG: Just after getting the databases.
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 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.
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.