Get SQL insert statement string from model? - android

Pretty simple question, assuming I've got the model for a row in a table, I'd like to get the insert statement necessary to create that row.
List<MyModel> updatedRows = new Select()
.from(MyDatabase.getMyModels().get(table))
.where(Condition.column(NameAlias.builder("id").build())
.in(new Select(UpdatedRecord$Table.updated_record_id)
.from(UpdatedRecord.class)
.where(UpdatedRecord$Table.updated_table.eq(table))))
.queryList();
StringBuilder updateStatements = new StringBuilder();
for (MyModel tableModel : updatedRows) {
// this is the insert statement, but there's no way to get it as a string
tableModel.getModelAdapter().getInsertStatement();
updateStatements.append(insertSqlStatementString);
}
tableModel.getModelAdapter().getInsertStatement() properly returns the insert statement, however, it is in the form of a DatabaseStatement, and I can't find any documentation for that class. I want the insert statement as a string.
Looking at that line in the debugger shows that underneath it there is a Statement and inside of that, mSQL which holds the string.
Can anyone help me out or point me in the right direction?
Tried this to no avail:
String tableCreateStatement = tableModel.getModelAdapter().getCreationQuery();
DatabaseStatement dbSt = tableModel.getModelAdapter().getCompiledStatement();
tableModel.getModelAdapter().bindToInsertStatement(dbSt, tableModel);
AndroidDatabaseStatement a = (AndroidDatabaseStatement)dbSt;
String p = a.getStatement().toString();

Here's what I ended up using after the main contributor to DBFlow responded to my question here:
// BaseModel row;
ContentValues values = new ContentValues();
row.getModelAdapter().bindToInsertValues(values, row);
String query = SQLite.insert(row.getClass()).columnValues(values).getQuery();

Related

Adding data to SQLite

I'm creating my first data enabled app but am struggling with the last part - actually adding and retrieving the data. For now I am only concerned with adding data to the table. Following this tutorial I have created model classes for my tables and a DBHelper class with all my CRUD methods (I can post all these if required but not sure they are necessary to answer this question. Please correct me if I am wrong!). Unfortunately the tutorial ends here and doesn't go into detail on how to pass the data from the UI of the app into the DB.
After some Google searches I have found an example of how to pass some data to these methods but only how to pass one piece of data at a time, so only really useful if my table has just one field - mine has more than one.
For example, if I have a a table for "Todo" tasks, in my dbhelper my create method may be;
public void createTodo(String todoText) {
ContentValues contentValues = new ContentValues();
contentValues.put("todo", todoText);
// Insert into DB
db.insert("todos", null, contentValues);
}
so from my activity I just need
dao.createTodo(todoTextValue);
For my app I will be adding more than one field at a time, so my create method looks like this;
public long createSite(Site site){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SITE_NAME, site.getSiteName());
values.put(KEY_SITE_LAT, site.getSiteLat());
values.put(KEY_SITE_LON, site.getSiteLon());
values.put(KEY_CREATED_AT, site.getSiteCreatedDateTime());
// Insert Row
long siteid = database.insert(TABLE_SITES, null, values);
So my question really is how I can pass all the different bits of data to the createSite method.
I don't know if this really needs an answer, but well here's a code...
Assuming your Site class is like this.
public class Site {
private String siteName;
private double siteLat;
private double siteLon;
private Date siteCreatedDateTime;
// getters and setters here
}
You then pass the data from your EditText value to your new Site object. It will look like this in your activity.
EditText siteNameInput = (EditText) findViewById(R.id.siteNameInput);
EditText siteLatInput = (EditText) findViewById(R.id.siteLatInput);
EditText siteLonInput = (EditText) findViewById(R.id.siteLonInput);
EditText siteCreatedDateTimeInput = (EditText) findViewById(R.id.siteCreatedDateTimeInput);
String siteName = siteNameInput.getText().toString();
String siteLat = siteLatInput.getText().toString();
String siteLon = siteLonInput.getText().toString();
String siteCreatedDateTime= siteCreatedDateTimeInput.getText().toString();
Site site = new Site();
site.setSiteName(siteName);
site.setSiteLat(siteLat);
site.setSiteLon(siteLon);
site.setSiteCreatedDateTime(siteCreatedDateTime);
dao.createSite(site);
Hope this helps you... You can learn more on Object-Oriented programming in Java here
public long createSite(Model site,String name, String address){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, site.name);
values.put(KEY_ADDRESS, site.address);
// Insert Row
long siteid = database.insert(TABLE_SITES, null, values);
to add elements to the class you just add
public class Model {
String name;
String address;
//add year as many as you need
Model(String name, String address){
this.name=name;
this.address=address;
}
}
And in you activity you call this
In java to add a new object in this case Model
Model x = new Model("josh","Ireland");
and you just pass to
dao.createTodo(x);
Todo and Site are models. Each variable represents a column of that table. You need to create a custom model for each of your tables. The createSite method takes an object of type Site and adds it as a row in the TABLE_SITES in the DB. values.put(...)takes columnName, value. So here you give your own column names and values.
Instead of getting into all this I suggest you use an orm like active android:
http://www.activeandroid.com/

Parse - Empty Table Checking

How to check if table is empty using parse , I'm having a problem with the code below :
private String[] getMaxDateMessage() throws ParseException {
final String[] msgData = new String[3];
ParseObject ob = null;
String[] userIds = {currentUserId, recipientId};
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereContainedIn("senderId", Arrays.asList(userIds));
query.whereContainedIn("recipientId", Arrays.asList(userIds));
query.orderByDescending("createdAt");
if(query.hasCachedResult())
{
ob = query.getFirst();
if (ob.isDataAvailable()) {
//for (int i = 0; i < 1; i++) {
//createdDate[0] = messageList.get(i).get("createdAt").toString();
msgData[0] = ob.getCreatedAt().toString();
msgData[1] = ob.get("senderId").toString();
msgData[2] = ob.get("recipientId").toString();
// }
}
}
The thing is that the table is empty , so the query should return null , but no exception is been throwed , it just crashes the app .
So how can I check if the table is empty before trying to fetch any data ?
Update : The solution that I have found is to use query.count().
If the count returns a value that is not 0 then the table is not empty .
Using query.count() to determine if the table is empty is not an optimal solution. While this is perfectly fine when actually run against an empty table, using query.count() will almost always result in a sub-optimal query when there's more than one object in the table. The reason for this is quite clear: you only care about the first object matched by this query, yet a query.count() will scan the whole table in order to return the total of objects that match your query.
Therefore, the ideal solution is to simply use query.getFirst() and check if you get any results. You should be able to handle the case where ob is not a ParseObject, e.g. the collection is either empty or no objects match your query.

android database delete row by content

Hey Guys ive got a problem with my database.
iam displaying my database in a textview looking like:
hh:mm dd:MM:yyyy text
12:14 12.12.2014 awdawdawd
13:12 13:12:2015 awdaw awdw
onclick iam getting the text by:
StringBuilder ortsplit = new StringBuilder();
String item = ((TextView) view).getText().toString();
String[] itemsplit = item.split("\\s+");
String uhrsplit = itemsplit[0].toString();
String datumsplit = itemsplit[1].toString();
ortsplit.setLength(0);
for (int i = 2; i < itemsplit.length; i++) {
ortsplit.append(" " + itemsplit[i].toString());
}
String sortsplit = String.valueOf(ortsplit);
then iam opening my database:
datasource.open();
datasource.findedel(uhrsplit,datumsplit,sortsplit);
datasource.close();
my datasource.findedel:
public void findedel(String pZeit, String pDatum, String pOrt) {
database.delete("TABELLE", "UHRZEIT="+Zeit +"AND DATUM="+Datum+"AND ORT="+Ort,null);
}
ive got no "id" displayed in the rows, earlier it looked like:
1 hh:mm dd:MM:yyyy text
2 12:14 12.12.2014 awdawdawd
3 13:12 13:12:2015 awdaw awdw
and ive just took the "id" and searched my entries for that id = id and deleted the row, but since i deleted the first row i want to search the row by the content.
any1 got a solution for my problem?
You have multiple errors and also you are prone to SQL injection.
You must use prepared statements or you must add quotes to your strings and escaping the quotes the string has, for example, in your code:
database.delete("TABELLE", "UHRZEIT="+Zeit +"AND DATUM="+Datum+"AND ORT="+Ort,null);
this: DATUM="+Datum+"AND is bad coded, there is not space between Datum and AND so, if datum is equal to test, then you string will be like this: DATUM=testAND. That will return syntax errors in mysql, and also string must be quoted like this: DATUM='test' AND.
The main problem of quoting this way is that if Datum has quotes by itself, you will have errors too. For example, if Datum equals to te'st then your string is going to be like this: DATUM='te'st' AND. As you see, you will have 3 quotes and then will return syntax error.
You must read and understand this before going further, because you will end up with a really messy code plenty of errors and vulnerabilities: http://wangling.me/2009/08/whats-good-about-selectionargs-in-sqlite-queries.html
Good luck ;)
And also, in Java all variable names must start in lowercase (Instead of String Datum use String datum)

Sql lite gets all data sent to webservice JSon format in android?

I am creating local database I want to send all data sent to web service.
For example product name one column. Lots of product name is there. I want to send it.
& Product name = briyani,egg,rice
I got all details from database below i have mention code:
public String fetchMyRowid(String column_name)
{
String query = "select "+column_name+" From " + TABLErestaurant;
mCursor =db.rawQuery(query, null);
StringBuffer buf = new StringBuffer();
if (mCursor.moveToNext()) {
buf.append(mCursor.getString(0));
String str = buf.toString();
System.out.println("**************"+str);
}
return buf.toString();
}
}
return buf.toString();
}
In class :
HashMap<String, String> paramsvalue = new HashMap<String, String>(); paramsvalue.put("product_name", dataBase.fetchMyRowid(DatabaseHelper.columnproductname));
But I have some issue. I got only one product name. I need all product name. Can any one suggest solution for this.
wel come to stackoveflow,
Please check below link in that i have first select all table's recode then i have created one another method for get all columns value by row. after that i have marge all data in to JSON. this is idea you have to do similar way...
https://stackoverflow.com/a/10600440/1168654

Android: having basic problems with sqlite database

I am having some trouble implementing a sqlite database in my simple android application:
a user is displayed a list of animals in a Listview.Upon selecting an animal the user is brought to an activity "Animal",which will display a picture of the animal and give them options to
view Animal Bio
Back
All very simple so far, right?
I have working the database, which will populate the listView of animals.Database currently looks like
Table Animal-
_ID,
Name
Table Biography-
_ID,
Bio
This is where I would welcome any helpful advice on my problem, or on how to improve my implementation.
Currently populating the DB as follows
long populateDB(){
String[] animalName = {"Lion" "Zebra", "Tiger", "Gorilla",...};
String[] animalBios = {"Found in the "...}
ContentValues animalNameVals = new ContentValues();
ContentValues animalBioVals = new ContentValues();
long[] rowIds = new long[animalName.length];
// Populate the animal table
for(int i = 0; i < animalName.length; i++){
animalNameVals.put(KEY_ANIMALNAME, animalName[i]);
rowIds[i] = db.insert(ANIMAL_TABLE, null, animalNameVals);
}
// Populate the Bio table
for(int j = 0; j < bios.length; j++){
animalBioVals.put(KEY_BIO, bios[j]);
rowIds[j] = db.insert(BIOS_TABLE, null, animalBioVals);
}
return rowIds[0];
}
And had planned on being able to tell database which animal on list was selected by passing extras with the intent, eg if position on listItemClick == 1, pass in tiger and retrieve tiger bio from db.
Problems:
Then on the Animal activity page is getExtra() == tiger, telling the activity that tiger was selected from the list and to load this bio from the DB..well, I cannot see an efficient method of implementation for this idea and am struggling to do so.
My second headache comes from adding the bio to the application from the Db.Originally I had a test bio hardcoded in a string, shown in a TextView.Is there a way to retrieve a string from a cursor and add it to the TextView id?I understand I will need some adapter, what I do not understand is why cant it be as simple as setResource(R.id.bio) = bio.
Thanks you for reading and any help is much appriciated.
First problem: First of all, I'm not sure why you don't have the column Bio in the Animal-table? As no Bio would fit to any other animal than itself, you can safely do this. By doing this you can query the database upon selection and pass the entire object (including name of animal and bio) to the next Activity and use this to get your information. If this was somewhat unclear, let me know and I'll try to explain it better.
Second problem: You can get values from tables (there of also Strings) using a Cursor. To get the String you can do something like this where cursor is the Cursor with your result from the database:
String bio;
// Move Cursor to its first element
if(cursor.moveToFirst()) {
// Make sure the cursor is not null
if(cursor != null) {
bio = cursor.getString(cursor.getColumnIndex("Bio")));
}
}
Sidenote: If I read the code correctly, it seems that you use long for ID's? The usual thing to go about ID's is integers as far as I know.

Categories

Resources