HELP! Okay so I have been designing an android app for quite some time now and I have been manually putting all this data into strings and then just pulling them up in my layouts, but then a friend of mine suggested I put all the necessary data into a database and then just pull it out of there on each activity....sounds good....Accept I have been reading tutorial after tutorial on how this works and it seems much harder than just making lots and lots of strings and the examples in the tutorials each serve their own purpose which is not mine and dose not make understanding any easier for me. All I will be needing this database to do is read and display the info where I want it on the layouts. I created this database with SQLite Database Browser.
Database structure:
Name - fishindex_db
Tables - fish, states, reg
Rows:
fish - _id, name, desc, loc
states - _id, name, abbr, updated
reg - _id, name, size, season, quantity, notes
so now say I want to display all the content from primary key (_id) 12 from the reg table in a layout list view how is this done? need .java and .xml code example please.
These are two tutorials you can use to get you up and running in terms of what you want to achieve:
Android SQLite Database Tutorial
How to connect Android with PHP, MySQL - this one takes it a bit further in showing you how to connect to production databases and consume web services.
Hope this helps.
Take a look at the code to connect to fishindex_db
public class SQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "fishindex_db.db";
public static final String TABLE_NAME = "fish";
public static final String _id = "id";
public static final String name = "name";
public static final String desc = "desc";
private SQLiteDatabase database;
SQLiteHelper sQLiteHelper = new SQLiteHelper(MainActivity.this);
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//this is to get all records in fish table
public ArrayList<FishModel> getAllRecords() {
database = this.getReadableDatabase();
Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null);
ArrayList<FishModel> fishes= new ArrayList<FishModel>();
FishModel fishModel;
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
fishModel= new FishModel();
fishModel.setID(cursor.getString(0));
fishModel.setName(cursor.getString(1));
fishModel.setLastName(cursor.getString(2));
fishes.add(fishModel);
}
}
cursor.close();
database.close();
return contacts;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a windows phone developer and newly I started developing android apps using android studio.
I need to create a database and store in it values and retrieve the updated values on screen, so I need help in:
Creating the database.
How to show values from the database on screen?
to create database , you need to extend SQLiteOpenHelper and need a constructor that takes Context.
lets say you name this class DBOperator. The table creation process will look something like this ,
public class DbOperator extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "DB_NAME";
protected static final String FIRST_TABLE_NAME = "FIRST_TABLE";
protected static final String SECOND_TABLE_NAME = "SECOND_TABLE";
public static final String CREATE_FIRST_TABLE = "create table if not exists "
+ FIRST_TABLE_NAME
+ " ( _id integer primary key autoincrement, COL1 TEXT NOT NULL, COL2 TEXT NOT NULL,COL3 TEXT, COL4 int, COL5 TEXT,"
+ "COL6 TEXT,COL7 REAL, COL8 INTEGER,COL9 TEXT not null);";
public static final String CREATE_SECOND_TABLE = "create table if not exists "
+ SECOND_TABLE_NAME+.........
public DbOperator(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SFIRST_TABLE);
db.execSQL(CREATE_SECOND_TABLE);
//db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//THIS WILL BE EXECUTED WHEN YOU UPDATED VERSION OF DATABASE_VERSION
//YOUR DROP AND CREATE QUERIES
}
}
Now your data manipulation class ( add, delete , update ) will look something like this ,
public class FirstTableDML extends DbOperator {
public FirstTableDML(Context context) {
super(context);
}
private static final String COL_ID = "_id";
private static final String COL1 = "COL1";
private static final String COL2 = "COL2";
........
.......
public void deleteFirstTableDataList(List<FirstTableData> firstTableDataList) {
for (FirstTableData data : firstTableDataList)
deleteFirstTableDetailData(data);
}
public void deleteFirstTableDetailData(FirstTableData item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(FIRST_TABLE_NAME, item.getId() + "=" + COL_ID, null);
db.close();
}
/**this method retrieves all the records from table and returns them as list of
FirstTableData types. Now you use this list to display detail on your screen as per your
requirements.
*/
public List< FirstTableData > getFirstTableDataList() {
List< FirstTableData > firstTableDataList = new ArrayList< FirstTableData >();
String refQuery = "Select * From " + FIRST_TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(refQuery, null);
try {
if (cursor.moveToFirst()) {
do {
FirstTableData itemData = new FirstTableData();
itemData.setId(cursor.getInt(0));
itemData.setCol1(cursor.getString(1));
itemData.setCol2(cursor.getInt(2));
.....
.....
firstTableDataList.add(itemData);
} while (cursor.moveToNext());
}
} finally {
db.close();
}
Collections.sort(itemDataList);
return itemDataList;
}
public int addFirstTableData(FirstTableData data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL1, data.getCol1());
values.put(COL2, data.getCol2());
.....
.....
long x=db.insert(FIRST_TABLE_NAME, null, values);
db.close();
return (int)x;
}
public void updateItemDetailData(FirstTableData data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL1, data.getCol1());
values.put(COL2, data.getCol2());
values.put(COL3, data.getCol3());
.....
.....
db.update(FIRST_TABLE_NAME, values, COL_ID + "=" + data.getId(), null);
db.close();
}
}
P.S : *Data class are POJO data class representing the corresponding table.
Since you said you are not totally new to these, I have not provided any helper comments as most of the method names are self explanatory.
Hope it helps you to get started.
To creating a database for Android application, there are 2 ways:
Create database and tables using Code
Use existing database
1) Create database and tables using Code
In this scenario, you have to write a class and code to create database and tables for it. You have to use different classes and interfaces like SQLiteOpenHelper, SQLiteDatabase, etc. Check answer posted by Jimmy above.
2) Use existing database
In this scenario, you can use your existing sqlite database inside your android application. You have to place database file inside assets folder and write a code to copy that existing database on to either internal or external storage.
Regarding best scenario, I would say it's depend on the application functionality and nature, if your database is small then you should go with 1st scenario and if your database is large with many tables then you should go with 2nd scenario because you would be creating database using any GUI based SQLite browser and which would help you to make less mistakes. (When I say less mistakes using GUI, believe me there are chances of creating tables by code).
How to show values from the database on screen?
For that you have to write a SQL query which gives you Cursor in return which is a set of resultant data, so you have to iterate through the cursor data and prepare a set of data in terms of ArrayList or Array or HashMap.
You can display this set of data in ListView or GridView.
P.S. I am not posting links to any tutorials or examples as there are plenty of information/examples available on web, so suggesting you to search around the given points.
A good way to start is to read about Storage Options on the official Android documentation website: http://developer.android.com/guide/topics/data/data-storage.html
I'm working on an Android application which supports both English and Turkish Language.
The app contains SQLite database which contains a Table and Autoincrement _id column.
When this app runs on English device it works fine, but when running it on Turkish device the database stops generating ids automatically.
I have tried to extract the database file and open it on SQLite Database Browser, it is saving all columns values correctly, only _id column's value still empty in Turkish Locale
Ideas to solve this issue?
Edit:
Creating Database:
public class DatabaseHandler extends SQLiteOpenHelper {
private final static String TAG = "DatabaseHandler";
private final static int DATABASE_VERSION = 3;
private final static String DATABASE_NAME = "app_main_database";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE tbl_item (_id INTEGER PRIMARY KEY NULL, _serverId TEXT NULL, _itemName TEXT NULL, _lastEditDate DATETIME NOT NULL)";
db.execSQL(query);
}
Insert Row to the Table:
#Override
public void insert() {
ContentValues reVal = new ContentValues();
reVal.put(COL_ITEM_SERVER_ID, getItemServerId());
reVal.put(COL_ITEM_NAME, getItemName());
reVal.put(COL_LAST_EDIT_DATE, getLastEditDate());
SQLiteDatabase sqLite = new DatabaseHandler(this).getWritableDatabase();
sqLite.insert(tableName, null, obj.getContentValues());
}
You could try to open your database and set locale (using setLocale) to english. By default it will use the system locale.
Using openDatabase you can set NO_LOCALIZED_COLLATORS flag too (which disables every setLocale and could fix your problem (but never tested it just some research right now))
public static final int NO_LOCALIZED_COLLATORS
Added in API level 1
Open flag: Flag for openDatabase(String, SQLiteDatabase.CursorFactory, int) to open the database without support for localized collators.
This causes the collator LOCALIZED not to be created. You must be consistent when using this flag to use the setting the database was created with. If this is set, setLocale(Locale) will do nothing.
Constant Value: 16 (0x00000010)
As first try, i would test the setLocale on datatabase object.
I've used the GUI to create a DB which has 1650 records in it.
I'm trying to query this DB but it's always returning nothing. I've tried writing a simple getrowcount() method to see if I'm getting anything at all, but it always returns zero. I must be missing something obvious here, if someone can help point out what's going on.
In my main app.java:
db = new DbHandler(this);
String sIcao1 = "ROW COUNT = " + String.valueOf(db.getRowCount());
In my dbhandler.java:
package com.jammo.mywidget4;
<snip - standard includes>
public class DbHandler extends SQLiteOpenHelper {
private static SQLiteDatabase db;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "airports";
private static final String TABLE_AIRPORTS = "airports";
public DbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db = this.getWritableDatabase();
}
int getRowCount() {
int nCount = -1;
//SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM airports", null);
nCount = cur.getCount();
if (cur != null) {
//cur.moveToFirst();
//nCount = cur.getInt(0);
//if (cur.getInt (0) == 0) {
//}
}
return nCount;
}
}
In the GUI (SQLite DB Browser) I'm doing a simple
select * from airports
... and I'm getting back the full number of rows. When I debug the Java, cursor returns nothing.
Also, the DB created by the GUI is located in myapp/assets/airports.db.
Any ideas?
I think you need to include the .db in the DATABASE_NAME.
Try changing this:
private static final String DATABASE_NAME = "airports";
to this:
private static final String DATABASE_NAME = "airports.db";
Edit:
Actually I think even with this change it is not going to work for you. SQLiteOpenHelper is expecting your db file to be inside of /data/data/your.package/databases/ So I think you'll need to copy it from assets to there if you want it to work with an unmodified SQLiteOpenHelper.
See here to learn how to copy it over: Android: Accessing assets folder sqlite database file with .sqlite extension
hi I have a SQLite Database and I've placed it in my assets folder. I was wondering how you can "print" information from the table on the screen. I have looked around and all I can find are people adding to a database all I want to do is show it on the screen and add some filters later on.
It should be roughly like this:
private static String DB_PATH = "/data/data/com.your.app/your_path/yourdb.sqlite";
private static SQLiteDatabase myDataBase;
public static void openDatabase() {
String queryString="YOUR SQL QUERY HERE";
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,SQLiteDatabase.OPEN_READONLY);
Cursor cursor = myDataBase.rawQuery(queryString, null);
if(cursor!=null) {
cursor.moveToFirst();
while(!cursor.isLast()) {
/*CHECK CURSOR USAGE AND DO SOMETHING WITH YOUR RESULTS HERE */
cursor.moveToNext();
}
}
myDataBase.close();
}
I think this may help.
Retrieve data from the SQLIte database and store them in a String / Strings.
Bring in some TextViews in your xml to your layout.
get references to those textview / textviews in your java code.
textview.settext(-----the string retrieved------);
This will print whatever string that your retrieved from your SQLite database.
SQLiteDatabase database;
public int getId() {
String sqlQuery = "SELECT * FROM <table_name>;
int id = 0;
Cursor cursor = database.rawQuery(sqlQuery, null);
if (cursor.moveToFirst()) {
id = cursor.getInt(0); // In my case, id (int) is in first column
}
return id;
}
I'm using Sqlite with android to develop and app which can be customizable (for the dev) in the future. I have created a database with the data which is then to be used to create the database for the application. So if any changes need to be made in the future or I write an app for somebody else in the future then all I have to do is change this original database. The idea behind this is the dev's database will set up all the UI and everything to do with the app.
I am stuck on what to do next I have the database I need in the app as the dev fully populated. My idea was to create another DBHelper class and within that reference the original DBHelper class and query within the new DB Class. So this is the second DBHelper class that i'm trying to create a database from a previous database:
public class appDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "library.db"; //database name
Cursor all, tables, options, ui_type;
SQLiteDatabase database;
public appDbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
DBHandler databaseHelper = new DBHandler(context);
database = databaseHelper.getReadableDatabase();
all = database.rawQuery("SELECT * FROM config", null);
tables = database.rawQuery("SELECT * FROM table_names", null);
options = database.rawQuery("SELECT * FROM options", null);
ui_type = database.rawQuery("SELECT * FROM ui_type", null);
}
#Override
public void onCreate(SQLiteDatabase db) {
for(int i=0; i<tables.getCount(); i++){
tables.moveToPosition(i+1);
String sql = "";
for(int j = 0; i < all.getCount(); j++){
if (all.moveToFirst()) {
do{
sql = ", " + all.getString(2) + " " + all.getString(5).toUpperCase();
}
while (all.moveToNext());
}
}
Log.v("DatabaseSQL", sql);
database.execSQL( "CREATE TABLE " + tables.getString(1) + "(_id INTEGER PRIMARY KEY AUTOINCREMENT"+sql+");");
}
}
But I have a feeling this is not the way to go about what I need to do. Any help will be greatly appreciated.
I think you do it wrong and to complicated. You provide a database to read data from where you could easily just create some inserts and your configuration will be implemented.
Two solutions:
From my own project: DatabaseAdapter.onCreate()
There you should see the database setup and the filling of the database with data. The data itself are added with simple inserts which contains data based on constants. So a programmer can easily change the data by changing the constants.
With that you don't have to handle 2 databases, you don't need to provide another database and read them.
As android supports database locations you could also skip this all and just open an sqlite database file you provide in your res/raw or asset folder or anywhere on the sdcard.
I recommend to do one of the two ways mentioned above.