I have an app that gets JSON data from a server. I then put the parsed data into the android SQLite database and use the data as needed. This all works great, however, I am unable to find a method to update the whole table.
The scenario would be that this Json Data feed gets updated every week on the server. I have two Questions:
What am I missing or what is the method for updating the SQLite table? (currently this just duplicates the data)
public void updateTable(Product product){
SQLiteDatabase db = this.getWritableDatabase();
try{
ContentValues values = new ContentValues();
values.put(KEY_TYPE_NAME, product.getmProductTypeName());
// more columns here...
db.update(TABLE_NAME, values, null,null);
db.close();
}catch(Exception e){
Log.e("error:",e + "in updateData method")
}
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
Related Code in "Main Activity":
handler = new DBHandler(this);
NetworkUtils utils = new NetworkUtils(MainActivity.this);
if (handler.getProductCount() == 0 && utils.isConnectingToInternet()) {
new JsonDataParse().execute();
}`
Related Code "DBhandler" Activity:
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_TYPE_NAME + " TEXT" + ")"
That is basically my CREATE TABLE String format. I just condensed to because it has 16 columns.
This is the code I added to only delete the stored data only if there was data:
if(handler.getProductCount() == 0) {
}else{
handler.deleteData();
}
Then I just just added the delete the method as suggested:
public void deleteData() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "1", null);
}
I'm not sure what you mean by "update the whole table". It sounds to me like you just need to delete the data in the table and then use your current method to add the new data. To delete the contents you can use:
db.delete(TABLE_NAME, "1", null);
Then call your existing method to re-populate the table from the server.
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
No it wouldn't be bad practice. That makes sense, as you'll only be able to reach the server if you're connected to the internet anyway.
Related
I am creating a simple Database to add the values of product. While adding the entries in database I am getting an error in Logcat and the program get stop there and then.
I am not clear with the error but its something related to insertion of data or in query I have written. I tried all possible alternatives I could.
Program Code is :
DataBase.java
public class DataBase extends SQLiteOpenHelper
{
public DataBase(Context context) {
super(context, CreateTable.DB_NAME, null, CreateTable.DB_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String create = "Create Table " + CreateTable.TABLE_NAME + "( " + CreateTable.KEY_ID
+ " INTEGER PRIMARY KEY," + CreateTable.KEY_NAME + " TEXT,"
+ CreateTable.KEY_PRICE + " REAL)";
db.execSQL(create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void addProduct(Product p)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(CreateTable.KEY_NAME, p.getName());
c.put(CreateTable.KEY_PRICE, p.getPrice());
db.insert(CreateTable.TABLE_NAME, null, c);
db.close();
}
}
EnterDeatils.java
public class EnterDeatils extends Activity {
EditText name;
EditText price;
Button done;
int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_deatils);
name = (EditText) findViewById(R.id.edtname);
price = (EditText) findViewById(R.id.edtprice);
done = (Button) findViewById(R.id.btndone);
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Product p = new Product();
p.setId(id);
p.setName(name.getText().toString());
p.setPrice(Float.valueOf(price.getText().toString()));
DataBase d = new DataBase(EnterDeatils.this);
d.addProduct(p);
}
});
}
}
LogCat Error:
01-12 23:06:52.343: E/Database(382): Error inserting pPrice=12.0 pName=ds
01-12 23:06:52.343: E/Database(382): android.database.sqlite.SQLiteException: table Books has no column named pPrice: , while compiling: INSERT INTO Books(pPrice, pName) VALUES(?, ?);
Requesting you guys to just help me to identify the error.
Thanks in Advance.
SQLiteOpenHelper onCreate() is only called if the database file does not exist. If you modify the SQL in onCreate(), you'll have to ensure the database file is updated.
Two approaches:
Delete the old version of the database. Uninstall is one way to do this. This way the database is created with whatever code you currently have in onCreate(). This is often the simplest way during app development.
Bump up the database version number you pass to SQLiteOpenHelper superclass. If this number is different from the version number stored in the database file, onUpgrade() or onDowngrade() is called, and you can update the database schema. This is the preferred way when you already have released versions out so your users can preserve their data when updating your app.
Delete your database from terminal
adb shell
cd /data/data/com.example.applicationname/databases
rm *
First you created table Books with x number of columns but pPrice column was not included in that create table query. Later on you added this column name to your create table query.
That's why this problem happened.
Try to delete the database. It will delete the old database from application and when you re start new database will be created.
onCreate() is only called if your database DOES NOT exist
Seems that your database was created without column KEY_PRICE.
After that you have altered your code adding column KEY_PRICE to String create.
If this is true you must increment database version in order it be created again:
Change:
CreateTable.DB_VERSION = 1;
To
CreateTable.DB_VERSION = 2;
As laalto suggested change onUpgrade
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CreateTable.TABLE_NAME);
onCreate(db);
}
Check if you are missing some space. I had same problem , and solved with adding space...
I'm trying to to create a database and insert some data into it but this doesn't seem to be working. Can anybody tell me what's wrong in my implementation? Here is my code for the database. Thank you.
SQLiteDatabase db = null;
db.openOrCreateDatabase("order", null);
db.execSQL("CREATE TABLE IF NOT EXISTS order ( id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, Price INTEGER)");
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', '100')");
SQLiteDatabase db = null;
db.openOrCreateDatabase.. will result in NullPointerException. You need to assign SQLLiteDatabase instance to db and then call openOrCreateDatabase on db.
Another issue is, 100 is integer, don't need in single quotes.
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', 100)");
There is a really nice tutorial supplied by google. It take you through how to do the basics with the SQLite database.
http://developer.android.com/resources/tutorials/notepad/index.html
I would suggest going through that.
In that tutorial is suggests using a SQLHelper inner class something like this
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE_CELEBS);
db.execSQL(DATABASE_CREATE_CHECKINS);
Log.i("dbCreate", "must have worked");
} catch (Exception e) {
Log.i("dbCreate", e.toString());
}
}
#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 celebs");
db.execSQL("DROP TABLE IF EXISTS checkins");
onCreate(db);
}
}
Then to get a new database you can call
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
You need to learn about SQLiteOpenHelper. Ask Google for some tutorials.
Incredibly Sqlite has much better performance "in transation" on inserts without transaction. I particularly, massive use transaction processes, or failure comes randomly at some point.
Currently I'm using ContentProvider in my application. Because of "layers" and no actual need for provider - I'm working on optimizing data access as much as possible. Here is my attempt to do this:
public static String getPreferenceString(Context context, String key)
{
DatabaseHelper helper = new DatabaseHelper(context);
SQLiteDatabase database = helper.getReadableDatabase();
SQLiteStatement statement = database.compileStatement("SELECT Value FROM Preferences WHERE Key='" + key + "' LIMIT 1");
try
{
return statement.simpleQueryForString();
}
catch (Exception ex)
{
return "";
}
finally
{
statement.close();
database.close();
helper.close();
}
}
public static void setPreferenceString(Context context, String key, String value)
{
DatabaseHelper helper = new DatabaseHelper(context);
SQLiteDatabase database = helper.getReadableDatabase();
SQLiteStatement statement = database.compileStatement("INSERT OR REPLACE INTO Preferences (Key, UpdatedOn, Value) VALUES ('" +
key + "', '" +
Utility.getDateConvertedToUTCDBString(new Date()) + "', '" +
value + "'); ");
try
{
statement.execute();
}
finally
{
statement.close();
database.close();
helper.close();
}
}
Is that about as close as I can get to direct calls to SQLite?
Should I have all this .close() statements in my code?
In setPreferenceString I did copy/paste and called getReadableDatabase even though I write data and it works. Why?
Is that about as close as I can get to direct calls to SQLite?
AFAIK SQL queries are closest you can go against RDBs
Should I have all this .close() statements in my code?
Personally, I would not create a DatabaseHelper, an SQLiteDatabase, and an SQLiteStatement each time I call that method. I would create all this just before you need them, and close them when no needed anymore. Also centralizing this is a good idea IMHO (using a singleton, for example).
Also your SQL statement could be written like
SELECT Value FROM Preferences WHERE Key= ? LIMIT 1
This way you only have to prepare it once and bind parameters as you need the statement. Same goes for any SQL query.
My app's got a database with three tables in it: one to store the names of the people it tracks, one to track an ongoing event, and one - for lack of a better term - for settings.
I load the first table when the app starts. I ask for a readable database to load in members to display, and later I write to the database when the list changes. I've had no problems here.
The other two tables, however, I can't get to work. The code in the helper classes is identical with the exception of class names and column names, and (at least until the point where I try to access the table) the code to use the table is nearly identical as well.
Here's the code for my helper class (I've got a separate helper for each table, and as I said, it's identical except for class names and columns):
public class db_MembersOpenHelper extends SQLiteOpenHelper
{
public static final String TABLE_NAME = "members_table";
public static final String[] COLUMN_NAMES = new String[] {
Constants.KEY_ID,
"name",
"score"
};
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " ("
+ COLUMN_NAMES[0] + " INTEGER PRIMARY KEY autoincrement, "
+ COLUMN_NAMES[1] + " TEXT, "
+ COLUMN_NAMES[2] + " INTEGER);";
public db_MembersOpenHelper(Context context)
{
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_CREATE); }
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ".");
// Do nothing. We do not have any updated DB version
}
}
Here's how I use it successfully:
db_MembersOpenHelper membersDbHelper = new db_MembersOpenHelper(this);
SQLiteDatabase membersDb = membersDbHelper.getReadableDatabase();
Cursor membersResult = membersDb.query(TABLE_NAME, null, null, null, null, null, null);
members = new HashMap<String, Integer>();
membersResult.moveToFirst();
for(int r = 0; r < membersResult.getCount(); r++)
{
members.put(membersResult.getString(1), membersResult.getInt(2));
membersResult.moveToNext();
}
membersDb.close();
And here's where it fails:
db_PlayersOpenHelper playersDbHelper = new db_PlayersOpenHelper(this);
final SQLiteDatabase playersDb = playersDbHelper.getWritableDatabase();
if(newGame)
{
for(String name : players)
{
ContentValues row = new ContentValues();
row.put(COLUMN_NAMES[1], name);
row.put(COLUMN_NAMES[2], (Integer)null);
playersDb.insert(TABLE_NAME, null, row);
}
}
The first one works like a charm. The second results in ERROR/Database(6739): Error inserting achievement_id=null name=c
android.database.sqlite.SQLiteException: no such table: players_table: , while compiling: INSERT INTO players_table(achievement_id, name) VALUES(?, ?);
...
I did do some testing, and the onCreate method is not being called at all for the tables that aren't working. Which would explain why my phone thinks the table doesn't exist, but I don't know why the method isn't getting called.
I can't figure this out; what am I doing so wrong with the one table that I accidentally did right with the other?
I think the problem is that you are managing three tables with with three helpers, but only using one database. SQLiteOpenHelper manages on database, not one table. For example, it checks to see whether the database, not table, exists when it starts. It already does, so onCreate() does not fire.
I would manage all tables with one helper.
Let me see if I get this right. You are trying to create one database with three tables. But when you create the database, you create just one table; you are somehow instantiating the same database at a different place and wonder why its onCreate method doesn't get called. Is this a correct interpretation?
My strategy would be to try and create all three tables in the single onCreate() method.
If you are working with multiple tables, then you have to create all of the tables at once. If you have run your application first and later you update your database, then it will not upgrade your DB.
Now delete your application, then run it again.
There is one more solution but it is not proper. You can declare onOpen method in which you can call onCreate. And add IF NOT EXISTS before table name in your create table string. – Sourabh just now edit
I am creating my SQLite database for my App at runtime if it does not exist and insert rows if it does. Since it is supposed to be created at runtime and I have implemented it by creating a subclass of SQLiteOpenHelper and overriding the onCreate() method -
"Do I need to put anything in the /assets folder of my project?"
I am not using any Content Provider "Do I need to add any tags in the AndroidManifest.xml?"
Here is what I have done. The strings have been defined properly and I do not get any runtime exceptions.
Implementation of the SQLiteOpenHelper subclass.
public class MyDB extends SQLiteOpenHelper {
public MyDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERAUTH_TABLE_CREATE);
db.execSQL(USERPREF_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and
recreate.");
db.execSQL("DROP TABLE IF EXISTS " + USERAUTH_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + USERPREF_TABLE_NAME);
onCreate(db);
}
}
Here is where I create an instance of the MyDB subclass of the SQLiteOpenHelper.
MyDB tdb = new MyDB(Activity.this);
SQLiteDatabase db = tdb.getReadableDatabase();
Everything runs and when I go to the sqlite shell and write the following query
select * from table_name - it just tells me no such record exist. I set breakpoints and it seems after the getReadableDatabase() is called the #Override OnCreate() method is never executed which is where I execute the Create table SQLs. I have tried getWritableDatabase()
as well.
I dont understand why the tables are not being created. If anyone can help that would be awesome.
Thanks.
Query Text String#1
private static final String USERAUTH_TABLE_CREATE =
"CREATE TABLE " + USERAUTH_TABLE_NAME + " (" +
"number INTEGER NOT NULL," +
"dip TEXT NOT NULL," +
"email TEXT NOT NULL," +
"password TEXT NOT NULL," +
"flag INTEGER" + ");" ;
Query Text String #2
private static final String USERPREF_TABLE_CREATE =
"CREATE TABLE " + USERPREF_TABLE_NAME + " (" +
"tpd TEXT NOT NULL ," +
"cat TEXT NOT NULL" + ");";
If onCreate() is not being called, then the database has already been created for your app. The quickest way to solve it is to delete your project on the emulator (Settings --> Applications --> Your application), and then restart your application. Alternatively you could use ADB to just drop your database -- it's up to you. Restarting the app after dropping the database will call onCreate() because the database does not exist, and then your table creation sql will be run. onCreate() is only called if your database DOES NOT exist (so pretty much the first time you call the database in your code.
"Do I need to put anything in the /assets folder of my project?"
No
"Do I need to add any tags in the AndroidManifest.xml?"
No
Your syntax is ok ... could you paste the query you are making for creating tables ?
This might be a silly question, but have you defined the DATABASE_NAME and DATABASE_VERSION variables?
Issue resolved. Code was working all the way once again. sqlite shell was not showing me the tables and the database. When I kept my app running on the emulator and navigated to data > data > your-package-name > databases > your-database-file using DDMS the system shows me the SQLite DB was created fine. I have checked the tables are there as well.
Thank you all guys!!
This simple application will create a data base and 1 table w and at the end it will
retrieve the value which u have enetered and vl show in textBox.
SQLiteDatabase myDB= null;
String TableName="Profile";
String ShowData="";
/* This function create new database if not exists. */
try {
myDB = openOrCreateDatabase("DataBase.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "+ TableName + " (id INT(4),firstname VARCHAR,lastname VARCHAR);");
/* Insert data to a Table*/
//myDB.execSQL("INSERT INTO "+ TableName +"(id, firstname, lastname) "+ " VALUES (1, 'Pir', 'Fahim');");
Toast.makeText(this," DATA BASE HAVE BEEN CREATED ", Toast.LENGTH_SHORT).show();
/*Fetch data from database table */
Cursor c = myDB.rawQuery("SELECT* FROM " + TableName , null);
int id = c.getColumnIndex("id");
int fristName = c.getColumnIndex("firstname");
int lastName = c.getColumnIndex("lastname");
// Check result.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
int personId = c.getInt(id);
String FirstName = c.getString(fristName);
String LastName = c.getString(lastName);
ShowData =ShowData +personId+" .) " +FirstName+" "+LastName+"\n";
txt.append("********************"+"\n"+personId+"\n"+FirstName+"\n"+LastName+"\n");
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
while(c.moveToNext());
}
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(this, "Error = "+e.getMessage(), Toast.LENGTH_LONG).show();
}
finally
{
if (myDB != null)
myDB.close();
}