android database delete row by content - android

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)

Related

Create words from random characters using the sqlite database

Let's just say I have the variable String SRand = "KELRSFGLIU", what I want to do is create a word from the SRand variable and search for that word in the database. Or looking for data in a database based on the SRand variable, the words that need to be found do not have to be 10 characters but can be 3, 4 - 10 characters
can this be done?
As an illustration, I want to do something like this:
Ilustration 1:
String SRand = "KELRSFGLIU";
String Suggestion = "";
private void Create_Suggestion(){
//The magic for creating Sugeestion in here
//The result can be "FIRE", "GLUE", "FUR", or something else.
Suggestion = ???;
SearchData(Suggestion);
}
private void SearchData(String Suggest){
//Data Must Be Found
}
Any Idea?
I suggest you use trees in case you want to do that, more info can be found here

Get SQL insert statement string from model?

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();

Android Get Text With Special Character From DB Using Json Into TextView

I'm using json to read long text from MySQL and set it on the TextView, it works without special characters but as soon as I have text like "an apostrophe' like this one" it returns null on textView. I tried using Html.fromHtml but it doesn't work. Any idea how I can use setText(string_with_special_characters)?
CODE:
public void accessWebService() {
JsonRead task = new JsonRead();
task.execute(new String[] { "http://mysite/myfile.php" });
}
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("json_array");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String chapter = jsonChildNode.optString("Column1");
TextView tvChapter = (TextView) findViewById(R.id.chapter);
tvChapter.setText(Html.fromHtml(chapter));
To answer the question above, I have noticed the following strange behavior:
When I copy text (paragraph) from Microsoft Word and paste into MySQL column, TextView returns null, If I type out the entire paragraph within MySQL column TextView returns the paragraph string as expected. Copying text from Word to Scite or Notepad prior still doesn't work, typing the whole text out works. This is strange as you can't tell if text was copied and pasted or typed out in DB columns, looks exactly the same (including white space).
I can't retype everything... with the info given, please feel free to provide a solution otherwise I will be typing until next year
UPDATE
I have done further investigation:
Note the following apostrophe's
’ '
The one on the left is from text editors while the one on the right is from SQL.
SOLUTION:
UPDATE `mytable`SET `column` = replace(column, "’", "'");

Reading a textfile database and displaying the results

I have a database thats in the form of a text file, my job is to parse the txt file and display the data in a listview. I have no idea where to start.
Heres an example entry.
"|9251115|,|0|,|DETAILS|,||,||,|Heading Price Text Text |,||,||
Where each || represents a field. There are also html tags between heading price and the text (p,b)
My first idea would be to parse it similarly to an xml document, i.e have it create a new line where it starts with a "|", fill it with everything in between and end the line when it reaches the next "|". But I still have no concrete idea on how to do this.
EDIT:
Taking it one step at a time for now. Using stringtokenizer to read it line by line and remove "," for a start. Ran into a problem, the textview to display the results is displaying false for some reason instead of the scanned text. here's my code if anyone needs a good headscratcher.
Context myContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView t = (TextView) findViewById(R.id.text);
st = new ArrayList<property>();
try
{
InputStream is;
is = myContext.getAssets().open("rooms.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String read = br.readLine();
while( read != null)
{
StringTokenizer st = new StringTokenizer(read,",");
{
while(st.hasMoreTokens())
{
String a = st.nextToken();
String b = st.nextToken();
String c = st.nextToken();
String d = st.nextToken();
String e = st.nextToken();
String f = st.nextToken();
String g = st.nextToken();
String h = st.nextToken();
t.setText(a+" "+b+" "+c+" "+d+" "+e+" "+f+" "+g+" "+h);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
While you can definitely implement your own parser using pure Java code, you should consider using a SQLite database (1) to store your data, which will allow you to insert, delete, modify and query much more easily.
If you database comes in that format from an external source, I'd write a one-time parser that parses the data and inserts it into the SQLite database for future use.
Remember that the CPU on Android devices is slower than your average PC CPU, so if you are parsing large amounts of data in this format all the time, your app might become very slow. Hence my suggestion of converting it to a database.
Another option you have in this case is using XML like you said, because there are ready-to-use parsers out there. But the advice about performance remains: you should really avoid reparsing the data all the time and, instead, store it in a ready-to-use format.
(1): http://developer.android.com/reference/android/database/sqlite/package-summary.html
Here is how I would do,
Have an object with getter/setter
Have a list intialized
1) You need to use StreamReaders/Bufferedreader to read the file
2) If each is not empty
2a) Use StringTokenizer to parse the string with "," as delimiter
2b) Set tokenized values to object
2c) Add object to list
3) return the list created in above step.
Note: If large data you need to be careful while reading entire file, you may get OutofMemoryError.
Bruno Oliveira gave very good advice.
You can parse your file by reading it line by line and then use string.split method, as result you will have all your data in an array where you can easily read and put into a list view or move it to a sqlite database.

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