I am creating an app blocking Application and would like to know a few things:
How to load a list of installed apps into a database table.
Create a new table within the database and set the table name
through an EditText field or an AlertDialog.
Call in selected apps into another activity
List of apps needs to have a CheckBox next to them to select which
apps to carry over to another
Completed Events
I have already managed to populate a ListView with all the installed apps.
I've set up an AlertDialog with everything I need so far, just need
to know how to link that to create a new table and set the entered
text as the table name.
All layouts have been created and set up to accommodate everything,
the problem just lies with the database and calling everything in
I hope I've provided enough details or if this makes any sense at all. Thank you in advance and I hope someone will be able to help me with this problem. If needed I can post segments of my already existing code to make things easier?
For using a Android Database, I recommend to follow this tutorial:
Android | Simple SQLite Database Tutorial
After this tutorial you will understand how the android database works, how you can create tables:
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, "+
"author TEXT )";
// create books table
db.execSQL(CREATE_BOOK_TABLE);
}
And how to
addItemsToDatabase(Object object)
getItemsFromDatabase(int id)
getAllItemsFromDatabase()
updateItemInDatabase(Object object)
deleteItemFromDatabase(Object object)
When you know all this you can create own methods to use!
Related
How to dynamically create table in database using greendao or ORMLite? I want to create new table in database when user pressed button, for each new table in database, data model is same but I need table with diffrent name. Is that possible ?
Concerning greendao:
It's not possible to dynamically create a new table. With greendao the code for handling your database is created on your development station by a J2SE-Application (using the daogenerator).
Concerning Ormlite:
I haven't been using Ormlite until now, but I doupt that generating new tables at runtime is possible.
Conclusion:
IMHO a database design, where you have to create new tables at runtime is bad practice, because you won't beable to benefit from ORM-frameworks. A design like that is also very difficult to maintain (if not impossible) and/or to test. On top of that a design like that may be difficult to understand for other developers as it is really uncommon.
Thus you should redesign your database schema.
You can use SQLite
public void createUserTable(DatabaseOperations d, String user) {
final SQLiteDatabase db = getWritableDatabase();
String CREATE_TABLE_NEW_USER = "CREATE TABLE " + user + " (" + UserInfo.NOTES + " TEXT)";
db.execSQL(CREATE_TABLE_NEW_USER);
db.close();
}
I am on Android and this question is of Sqlite :
I have a table (USERLOGIN) which holds the user's credentials (username and password) in it. I have another table ($USER$_PROJS) which holds information of projects for a particular user. Users can create and add projects in there.
[ $USER$ will be a variable which comes from the column username in USERLOGIN table. So its basically a dynamic table creation. ]
Both of these tables are in the same database USER.db.
I have only one LoginDatabseAdapter class and DatabseHelper class which manages both of these.
Now initially when user logs-in, the database is behaving properly. But when inside the user profile when a user tries to create/add project its not inserting the values into $USER$_PROJS table.
I think i need to use the USE TABLE (once the user successfully logs-in his profile) like statement but its giving an error when i try to use it.
I have searched almost all the resources on net but was unable to find the solution !!
Any help would be appreciated !!
CODE RESPONSIBLE FOR CREATING TABLE :
public void createprojtable(String u){
db.execSQL(
"create table if not exists "+u+"_PROJS(ID integer primary key autoincrement,
PROJ_NAME text,DATE text); ");
}
public void insertProjEntry(String u,String projName,
String projdate) {
//db.execSQL("use table "+u+"_PROJS;");
ContentValues newValues = new ContentValues();
newValues.put("PROJ", projName);
newValues.put("DATE", projdate);
db.insert(u+"_PROJS", null, newValues);
}
Have a look at the Cursors for Sqlite in Android. You get Cursors specific to a table. Using the Cursors you can read data from a specific table as such. While updating the data also you can specify table name as one of the parameters. So you can pretty much get what you are looking for using existing APIs.
Have a look at following links :
Android SQLite Database and ContentProvider - Tutorial
android.database.sqlite
I am using a SQLite database to store data that can be used to reconstruct some objects that I am using in the application I am developing. I am storing CheckIns, Recipients, and ContactMethods.
These objects are related as follows:
CheckIn <--many -- to -- many--> Recipient
Recipient <--one -- to -- many--> ContactMethod
In Java, these objects' fields are defined as follows:
public class CheckIn {
private int id;
private boolean isEnabled;
private Date startTime;
private Repetition repetition;
private Set<Recipient> recipients;
}
public class Recipient {
private String name;
private Set<ContactMethod> contactMethods;
}
public class ContactMethod {
private String type;
private String address;
}
The database schema I have come up with for these objects is defined as follows:
CREATE TABLE checkIn(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
isEnabled INTEGER,
startTime INTEGER,
repetitionNum INTEGER,
repetitionUnits TEXT
);
CREATE TABLE recipient(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT
);
CREATE TABLE contactMethod(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT,
address TEXT,
recipientID INTEGER,
FOREIGN KEY(recipientID) REFERENCES recipient(_id) ON DELETE CASCADE
);
CREATE TABLE checkIn_recipient(
checkInID INTEGER,
recipientID INTEGER,
FOREIGN KEY(checkInID) REFERENCES checkIn(_id),
FOREIGN KEY(recipientID) REFERENCES recipient(_id)
);
I have two questions.
1. How do I efficiently INSERT a CheckIn to the database, along with its related objects?
To be more specific, if I have a CheckIn object in Java, not yet committed to the database, how can I structure an INSERT statement that will insert the CheckIn to the CheckIn table, but also store the new CheckIn's relation to one or more Recipients? It seems like to store the relation to the Recipients, I would need to already know the checkIn._id, which hasn't been set yet, since the CheckIn hasn't been entered into the database yet.
2. In Android, what is the best way to rebuild a CheckIn object, for example, from a database query?
I think I know the SQL query that I will need to get the right data:
SELECT checkIn.*, recipient.name, contactMethod.type, contactMethod.address
FROM checkIn
JOIN checkIn_recipient
ON (checkIn._id = checkIn_recipient.checkInID)
JOIN recipient
ON (checkIn_recipient.recipientID = recipient._id)
JOIN contactMethod
ON (recipient._id = contactMethod.recipientID)
This query will get me rows of data containing all of the information I need to build an object for every CheckIn and Recipient in the database, and I know how to get a Cursor object that will iterate through these rows. However, since the data required for a single CheckIn appears on multiple rows, I am confused about the best way to construct individual CheckIn objects. If I am trying to write a method like public Set<CheckIn> getAllCheckIns() that will return a set of all CheckIns that are stored in the database, do I need to run the query above, then loop through each row with the same checkIn._id, and within that loop, every row with the same recipient._id, and so forth? Is there any better way to do this?
I am sorry for the long question. I have only been working with SQL beyond single table databases since this morning, and I didn't want to leave out any important information. Let me know if I missed something.
Answer to Question 1: There are 2 possible ways.
a. You find the ID of the inserted row and use that to insert into the 2nd table. You can find the ID of inserted row if you are using the Android Insert method as documented here:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert%28java.lang.String,%20java.lang.String,%20android.content.ContentValues%29
Here you must ensure that all DB tables are committed or none.
b. You can create triggers. Triggers are database operations that are automatically performed when a specified database event occurs.
Learn how to create triggers: http://www.sqlite.org/lang_createtrigger.html
So for e.g. you can create a AFTER INSERT trigger that will be fired when a row in inserted in check in table. Then in that trigger you can insert a row into another table.
When the trigger is fired, you have access to the newly inserted row.
Answer to question 2:
I usually do the following :
Select from table 1 - Check In table
Iterate over the cursor and prepare the Check In object.
Within the loop, select from table 2 - Recipient table
Iterate over the recipient table and prepare the Check in object.
This would involve too many DB selects.
Alternatively, you could select all data once and then iterate to prepare the objects.
The point I am trying to make is that you have to iterate :D
i am getting information from user in sqlite database.
But when i insert same record which is already in database it is added again.
how i can stop duplication of record in sqlite. I am developing this in android.
I am using mobile number as primary key. still it add that record in database.
Please suggest me appropriate solutions.
Thanks in advanced.
Be aware of the limitations of REPLACE or INSERT OR REPLACE as these will overwrite any custom data your app user has added to these rows in the database - it is not as advanced as UPSERT in other SQL databases.
As mentioned in a previous post you really need to identify what the primary key could be and use this information to either update old data or to remove an old row before inserting the fresh one.
If this is not possible then you could always DELETE FROM my_table or DROP my_table before running the insertions so that there will be no duplicates. This will (for better or worse) also make sure that data that is missing from new imports is not left lying around in your app.
make sure you have set your phone number as Primary Key at the time you created the table.
for example:
String query = "CREATE TABLE IF NOT EXISTS PhoneBook ("+
"TelNum VARCHAR(100) PRIMARY KEY NOT NULL,"+
"Address TEXT);";
db.execSQL(query);
and in case you want to enforce foreign keys defined in your table then call the following method before doing anything in your database
db.execSQL("PRAGMA foreign_keys = ON;"); //enforcing FK
Use REPLACE INTO keyword:
REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');
This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.
I am missing something with all of the android SQLite tutorials.
I want to create a SQLite database that holds the autoincrementing key, and four text fields that I will pass in
I intend to pass in this SQL database
private static final String INSERT = "insert into " + TABLE_NAME + "(field1) values (?)" + "(field2) values (?)" + "(field3) values (?)";
but I'm not sure if the android sdk has a proper insert function.
I'm not sure how "Cursor" relates to anything I am trying to do, and I'm not sure how much object oriented initializing I should be trying to as opposed to just calling some built in android sdk functions.
insight appreciated, but please break it down
Will recommend you to go through NotePad exercise here is a link. Specially go through Exercise 1.
And for more depth knowledge you can go through project which I have created. Here is a link
Look for creatFeed function call here. I think will help to answer your problem.