How do I display exactly one data (specified row and column value ) from SQLite database to a paragraph in iText pdf? I used iText pdf and extracted the table from database but I cannot extract a specific data from it and add it to paragraph.
I am making a CV maker app and I need to display the user data from database to pdf using Android.
Pick whatever is the unique column on the database(maybe a username) and use it to query the database for specific rows that contain the username, since it's a profile table is safe to assume that the user's profile will prop up just once.
Then you can get out specific columns from the returned cursor.
SQLiteDatabase db = this.getWriteableDatabase();
String query = "SELECT * FROM " + your_table_name + " WHERE " + username_column + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {thUsersUsername});
If (cursor.getCount == 1){
cursor.moveToFirst();
//get a specific column eg address
String address = cursor.getString(cursor.getColumnIndex(enterColumNameHere));
Toast.makeText(this, address, Toast.LENGTH_LONG).show;
cursor.close();
db.close();
}
That's basically what you need.
Related
I have a local SQLite Database in may App. I create and open the Database like this:
CookieClickerBase = getBaseContext().openOrCreateDatabase(CookieBase, MODE_PRIVATE, null);
CookieClickerBase.execSQL("CREATE TABLE IF NOT EXISTS cookiedata(what TEXT, data LONG)");
I insert some thin into the table link this:
CookieClickerBase.execSQL("INSERT INTO cookiedata VALUES ('Image','3')");
But now I wont to change the data from 3 to 9 in the table entry, where what = Image.
How can I do that?
THANKS!
You could use an UPDATE statement with execSQL():
CookieClickerBase.execSQL("UPDATE cookiedata SET data = 9 WHERE what ='Image'");
or use the recommended method which is update() with ContentValues:
ContentValues cv = new ContentValues();
cv.put("data", "9");
int rows = CookieClickerBase.update("cookiedata", cv, "what = ?", new String[] {"Image"});
The variable rows will contain the number of updated rows.
I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.
Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.
The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.
I like the interface and any kind help would be appreciated.
Database db = Display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);
// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);
//keeps adding "John" to the database, even though value has been changed to "James"
Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);
while (cur.next()) {
System.out.println(dataText);
}
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.
It should be:
Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
Row currentRow = cur.getRow();
String dataText = currentRow.getString("Date");
System.out.println(dataText);
}
If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.
I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.
I have a simple app that contains an Sqlite database containing 2 tables:
TABLE_CHAP that contains:
_id
Chapter_title
Number_of_flashcards
TABLE_Flash contains:
_id
Chap_id
flashcard content
I upload the content of the database to the assets folder, TABLE_FLASH contains a number of flashcards that belongs to each chapter.
What I'm trying to do is to count the frequency of Chap_id in TABLE_FLASH and insert this number to Number_of_flashcards in TABLE_CHAP and afterward display the number_of_flashcard in front of the concerned Chapter_Title.
the Number_of_flashcards is dynamic as the user may add his own flashcards to each chapter.
public void nberOfFlahcards(){
int xy= getChap_tableCount();
ContentValues contentValues = new ContentValues();
database = openHelper.getWritableDatabase();
for(int i=1; i<=xy; i++){
String countQuery = "SELECT * FROM TABLE_CHAP WHERE Chap_ID = " + i;
Cursor cursor = database.rawQuery(countQuery, null);
int total_count=cursor.getCount();
Log.v(TAG, "Nber of Flashcards for chapter"+i+"is: "+total_count);
contentValues.put(KEY_NBER_FLAHCARDS, Integer.toString(total_count));
database.update(TABLE_CHAP,contentValues, KEY_NBER_FLAHCARDS,null );
this code gave me always 0, please check where's the error and if you have better code or better architecture for the database please advise.
This update can be done with a single query
UPDATE TABLE_CHAP SET Number_of_flashcards =
(SELECT count(*)
FROM TABLE_Flash AS tf
WHERE tf.Chap_id=TABLE_CHAP._id)
But I'd better have a method int getNumberOfFlashcards(int chap_id) which computes the count for the given chap_id.
I have an image processing app. My app stores the already processed images in a database. Every time the user opens the app, the app starts to check the database to see what photos have already been processed. With my code this process is taking around 10-20 seconds, which for my needs is a lot of time.
The database only has one column, the path of the image. I take the full image list from the phone and then search every item of the list in the database.
My code is as follows:
public static ArrayList<String> getAlreadyProcessedPhotos(Context context, ArrayList<String> photos, SQLiteDatabase db)
{
ArrayList<String> notAlreadyProcessedPhotos = new ArrayList<>();
for(String path : photos)
{
File imgFile = new File(path);
if (!Utils.isAlreadyProcessed(context, imgFile, db))
{
notAlreadyProcessedPhotos.add(path);
}
}
return notAlreadyProcessedPhotos;
}
public static boolean isAlreadyProcessed(Context context, File imgFile, SQLiteDatabase photosDb) {
if(photosDb == null || !photosDb.isOpen())
photosDb = new DatabaseHelper(context).getReadableDatabase();
String searchQuery = "SELECT * FROM " + DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.PATH_COLUMN + "=?";
Cursor cursor = photosDb.rawQuery(searchQuery, new String[] {imgFile.getAbsolutePath()});
boolean result = cursor.moveToFirst();
cursor.close();
return result;
}
For each file that you want to check you are executing a separate sqlite query. No wonder it's slow! If there are 100 files you will need to do a 100 queries. But this can really be done with one simple query. You just need to combine your two methods into 1
public static ArrayList<String> getAlreadyProcessedPhotos(Context context, ArrayList<String> photos, SQLiteDatabase db)
{
ArrayList<String> notAlreadyProcessedPhotos = new ArrayList<>();
ArrayList<String> preProc = new ArrayList()
for (String item: photos) {
preProc.add("'" + item + "'");
}
String inClause = TextUtils.join(",", preProc);
String searchQuery = "SELECT " + DatabaseHelper.PATH_COLUMN + "FROM " + DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.PATH_COLUMN + "NOT IN (" +inClause + ")";
Cursor cursor = photosDb.rawQuery(searchQuery);
while(cursor.moveToNext())
{
notAlreadyProcessedPhotos.add(cursor.getString(0);
}
return notAlreadyProcessedPhotos;
}
This is one loop, one query. I don't know where your photos array list comes from but I get the feeling there is room for further optimization there as well.
The answer to almost all sql (Sqlite, MySql, ....) speed issues is to create an index on the table. See: https://www.sqlite.org/lang_createindex.html
My guess your doing a full table scan on the imgFile you just added, that is as slow as it gets.
Other things you can do ( But won't help near as much as an index)
1) Since you are not using the imgFile returned from Sqlite, change your sql to 'Select count() From ... ' which will return an integer that is greater than zero if present.
2) Add a limit clause to the select statement "Select .... limit 1;" This will allow Sqlite to return once the first record is found.
You already got the responses in form of the comments too!
First is the loop issue as how suggested e4c5. Of course that will make a huge boost.
The second is the SELECT * FROM table replace with SELECT field1WhatIreallyNeed, field2WhatIreallyNeed FROM table.
It helps adding to index the Where fields too.
I have integrated sqlite3 with NDK , so it is used C there and is even faster, but worth if your records are close to 1 million in 1 table.
The best answer is in comment: you don't need database for this! And that would be the fastest. Think about the database how is read, where is stored? - in a file not, just with another constraints, parsing, processing overheads.
I need the database, becuase my app overwrites the original photo, so
the photo always exists
No, you don't need database for this!
There are eTags
There is a meta file info
You can store in an separate file downloaded_timestamp, processed_timestamp and you can calculate if needs to be processed or not, and that will take milliseconds and not 10-20 seconds.
So, drop your database and use a simple file, read the data from that file all at once, not line by line.
Hello I develop register screen in android and I need to get id from my database by entered username and password that stores database and make it as int.Firstly user will register then type name and pass and login up.In my database I have many raws like:id username password.I want to get id of entered username and password.For ex:id:1 username:A pass:a id:2, username:B pass:b.. and when user A entered his name and pass and login up i should get his id then make it int type if you dont something please leave comment thanks
I tried to made attempt but i dont know is it rightand how to develop it:
EditText name;
String Username = name.getText().toString();
Cursor c = database.rawQuery("SELECT * FROM " +LOGIN_TABLE + " where username = '"+Username+"'", null);
and in this code Login table is my table name?
If you are using the built in id field of the database, I recommend changing the query a bit.
I find that if I did not define the _id row in my create table statement, I do not get it in Select * statements.
Cursor c = database.rawQuery("SELECT * FROM " +LOGIN_TABLE + " where username = '"+Username+"'", null);
Can be switched to:
Cursor c = database.rawQuery("SELECT _id, * FROM " +LOGIN_TABLE + " where username = '"+Username+"'", null);
After that, when you get it from the cursor, use this to find the id:
Long id = c.getLong(c.getColumnIndex("_id"));
EDIT:
Before calling the last line of code here, make sure to move the cursor to the first result.
if (c.moveToFirst())
{
id = c.getLong(c.getColumnIndex("_id"));
}
Get the id from database as:
String id = c.getString(1);//c is object of cursor
then convert to integer by using Integer.parseInt()
int integerId = Integer.parseInt(id);
public void addData(View view){
DBHandler dbHandler = new DBHandler(this);
//normally the id is comming as int , i changed it to string
long val = dbHandler.addInfo(username.getText().toString(), password.getText().toString());
if(val > 0){
Toast.makeText(this, "Inserted Successfully", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Inserting Error", Toast.LENGTH_LONG).show();
}
}