Create multiple tables in a DB previously created - android

I want to search on a scholar subject DB, and when I get the name of the subject, create a new table to save some homework there ( as a list to do) but this will be multiple (a scholar schedule).
I have been trying with on upgrade, I get the name, I create the table, but when I try to add smt it says "no such table" how I can do this?
THANKS A LOT

String stm = "CREATE TABLE something (colum1,colum2, ...)";
public void execSQL(String stm) {
try {
myDataBase.execSQL(stm);
} catch(Exception e) {
e.printStackTrace();
}
}
After insert your data in your colums. You can always use the same function, just create new statement variable each time you calling it. A simple easy way, not always the best, but it's work well. I suppose you know how to read data in your db. I hope it will help you.

Related

Delete all data from all tables in Sugar ORM

I use Sugar ORM 1.5 in my app and I want to clear all info when the user logoff.
I want to avoid deleting the database file or use pure SQLite scripts if possible.
The only solution I found was using deleteAll on all tables, but I want to know if there is a better way to do it.
Regards,
EDIT
I solve the problem I had deleting the database just calling SugarContext.terminate(); before deleting the database and SugarContext.init(context); after.
Looks like it's the best solution like Henry Dang pointed in the comments, and it is faster than deleting all data.
This snippet works for me. It terminates the context deletes all tables and recreates them:
SugarContext.terminate();
SchemaGenerator schemaGenerator = new SchemaGenerator(getApplicationContext());
schemaGenerator.deleteTables(new SugarDb(getApplicationContext()).getDB());
SugarContext.init(getApplicationContext());
schemaGenerator.createDatabase(new SugarDb(getApplicationContext()).getDB());
SchemaGenerator is from com.orm, my SugarORM version is 1.5.
for other users who just want to delete all records (not tables or database)
public static void deleteAllrecords(Context applicationContext) {
List<Class> domainClasses = getDomainClasses(applicationContext);
for (Class domain : domainClasses) {
SugarRecord.deleteAll(domain);
}
}
if we want to delete sequence also you can add this line inside for loop
SugarRecord.executeQuery("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + NamingHelper.toSQLName(domain) + "'");

Where to store values to be inserted to SQLite at installation

I am new for SQLite and here is the story;
I'm developing an apk which is a kind of quiz application. I want to store the questions and answers in SQLite database. ( I am also not sure if this is the best way to store data, in SQLite )
In onCreate() method I should create the db and insert all questions, answers etc. So, I'm not sure where to put the data that will be inserted to db before insert them to db tables.
I mean;
values.put("key", "What is abc");
** insert
values.put("key", "What is def");
** insert
values.put("key", "What is ghi");
** insert
values.put("key", "What is xyz");
** insert
...
where should I get those strings (What is bla bla) to insert to table ?
If this was a windows application, I would put them in a .txt file, read from there, and insert rows.
In android, I don't know.
Thanks for any suggestions.
I am also not sure if this is the best way to store data, in SQLite
There are worse choices. :-)
In onCreate() method i should create the db and insert all questions, answers etc.
I'd prepare the database ahead of time, package it with your app, and deploy it using SQLiteAssetHelper. This would be easier to write, easier to maintain, and faster to run.
You can use this to read a text file.
Once you have that in your SQLiteOpenHelper#onCreate() method you would add your default values.
One way to do this would be:
Store the data as XML file in your res/raw folder.
Create a Parser. (DOM would work for a small file. SAX would be better if the file size is large)
Parse the data in onCreate and insert the values.
For example:
` public void onCreate(SQLiteDatabase db) {
ArrayList quizDataList;
quizDataList = ParseQuizData.getQuizData(context);
ContentValues values = new ContentValues();
try {
// Create Database
db.execSQL(TABLE_CREATE);
for (Iterator<QuizData> iterator = quizDataList.iterator(); iterator.hasNext();) {
QuizData quizData = iterator.next();
values.put(COLUMN1, quizData.getAttributeFirst());
values.put(COLUMN2, quizData.getAttributeSecond());
db.insertOrThrow(TABLE_NAME, null, values);
}
} catch (Exception e) {
e.printStackTrace();
}
`

Android Update Query

I’m using a database helper to update a table with one row and two fields, I have the following code that that sends two phone numbers through.
dbHelper.updateNumbers(newSmsNumber, newVoiceNumber);
and the following method in the helper.
public void updateNumbers(String newSmsNumber, String newVoiceNumber) {
//Update code here
}
Can anyone show me the code I need to add in the method to update the two fields in the database.
Cheers,
Mike.
ContentValues cv = new ContentValues();
cv.put("SMS", newSmsNumber);
cv.put("Voice", newVoiceNumber);
db.update("[table name]", cv, "ID=?", new String[]{Integer.toString(id)});
There are some gaps to fill up though, the table name, and how you identify the entry you want to update (I put a "ID" field there in that example)
Did not run that code, did not really check, but that should give you an idea.

simple sqlite example? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
sqlite example program in android
Hi I'm new to android and I am having some trouble finding a good tutorial for an SQLite database. What I wanted to do was to store a line of data in the database, reference it later and then delete it once its been referenced. As I have said I am new to this sort of thing and have no clue even what any of the syntax is so if there is a simple tutorial out there I would like to know.
try this
try { // creating a database called db and a Table inside it, called
// userdetails. With username and password as columns.
db = openOrCreateDatabase("UserDetails.db",
Context.MODE_PRIVATE, null); // optional CursorFactory
db.execSQL("drop table if exists userdetails");
db.execSQL("create table userdetails " + " ( username TEXT,"
+ "password TEXT);");
} catch (SQLException x) {
x.printStackTrace();
Log.e(LOG_TAG_NAME, "Database creation error");
}
//.........................................................................
// and insert values into the database table.
try {
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('hi','hello');");
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('chris','gayle');");
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('v','v');");
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG_NAME, "inserting table values error");
}
String[] columns = { "username", "password" };
Cursor c = db.query("userdetails", columns, null, null, null, null,
null);
now use the cursor to retrieve values
also have a look at
http://developer.android.com/guide/topics/data/data-storage.html#db
hope all this helps
EZ Answer I think.
If I understand your needs I think that you will find a database is overkill. You can do this a lot easier I think with just a few lines of code. If I am correct, a "line of data" sounds like a single String that you want to persist. If that is the case SharedPreferneces is by far your best bet for easy implementation.
Check out THIS link to the Dev-Guide's Shared Preferences Data Storage section
Its as easy as initializing the Preferences, and either putting or asking for a value by key.
On the other hand if you need to store many lines of relational data, search through them, sort them, etc. then a database is what you want.
Generally, I choose the data storage mechanism based on what is being stored and how i want to retrieve it:
Single primitives (and Strings) get stored best in SharedPreferences.
This is a fast and easy implementation. You can get away with storing a couple of values if you need to to represent a more complex class. Sometimes it makes sense to create a helper class that keeps track of complex schemes.
Serializable complex data, like parameterized Collections, that are loaded into memory all at once, long streams of text to be parsed, or if that data is a byte stream it gets stored to a file. This is not as fast and involves catching a lot of potential IO issues. But most objects are serializable or easily made that way.
Tables of data that I want to query or provide a Cursor for because of how long they are go into a database. The start up and resource expenses of a database are huge. Writing all the helper code to use them is a pain in the extreme.
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!
First place to look for tutorials should be the official Android Docs: Link.

call sql from another class for android app

Hi
I have created a database for my application and i have added items to the database using methods from the database class. I am encountering a problem do when i try to execute a sql query in the other class(app.java), i need to reference a database and thats where im having the problem!
this is the sql query im trying to execute(in database.java)
public void getData(SQLiteDatabase db, String data){
String sql =
"SELECT permissions FROM genres WHERE name = "+data+";";
db.execSQL(sql);
}
and this is how i am calling it(in app.java)
appData.getData(db, chosenGenre);
I just dont no what to put for the "db" part in appData.getPermissions(db, chosenGenre);
Does anyone know how to do this?
Thanks
You would typically use a SQLiteOpenHelper to create the database files (if necessary) and obtain a SQLiteDatabase object which is used to access the actual database (files on disk read by SQLite).
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Here's a nice tutorial
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/2/
You don't show the code where you define the database manager 'db'! If you are using a database created outside the android device, you might get some help from this link:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
Also, I have found that it's best to frame all table names and supplied values in single quotes a la -
String sql = "SELECT permissions FROM 'genres' WHERE name = '" + data + "'";
Note that the semicolon is not required.

Categories

Resources