Searching a database in Android - java

Targeting 4.2 using Eclipse
I have a basic input screen that takes address book information from the user and puts it into a db table called myAddressBook my code for creating the table is as follows (db is the SQLiteDatabase declaration:
//MODE_PRIVATE = only this application
db = openOrCreateDatabase("AdddressBookDB", MODE_PRIVATE, null);
//Create the Table
db.execSQL("CREATE TABLE IF NOT EXISTS myAddressBook(Name VARCHAR, Address1 NVARCHAR, Address2 NVARCHAR, City VARCHAR, State VARCHAR, Zip INT(5), Phone INT(10));");
Now I have a Search button on the form and an EditText that I want to use to search my table and display the results in a list, or possibly in the original EditTexts used for the input. In the OnClick for the Search button, I have:
String searchvalue = searchEditText.getText().toString();
To get the string of whatever the user wants to search for. Now how do I basically say "find anything in the database that partially or fully matches searchvalue"?? (I am new to Android but VERY new to SQL)

Probably, this is answer for your question
Cursor cursor = getReadableDatabase().
rawQuery("select * from todo where _id = ?", new String[] { id });
This is good article. Please read that for getting answer for your question.

Related

Sqlite query is yielding last but one row value instead of last inserted row value

I have a weird sqlite problem, partly Flutter partly Android... I have a database that I create in Flutter. When I insert a new row and I save it, I want to retrieve it in Android and send the values to a broadcast receiver. I am using this query: "SELECT * FROM " + TABLE_NAME + " ORDER BY " + COLUMN_ID + " DESC LIMIT 1"; This works great when creating the first row, but after that my broadcast receiver only ever receives the value of the last but one row, not the last row.
This is my code on the Java side, to get the details from the sqlite database and send them to the receiver:
public void getScheduleFromFlutter() {
String setting = "";
DatabaseHandler db = new DatabaseHandler(this);
Cursor cursor = db.getValues();
if (cursor.moveToFirst())
setting = cursor.getString(cursor.getColumnIndex(COLUMN_SETTING));
Intent intent = new Intent(this, Schedules.class);
intent.putExtra("SETTING", setting);
sendBroadcast(intent);
cursor.close();
db.close();
}
Any ideas?
You might have some issues in the query to retrieve the last row.
However if you re inserting values in table with Sqflite.
When inserting a value:
// Insert the Dog into the correct table. You might also specify the
// `conflictAlgorithm` to use in case the same dog is inserted twice.
//
// In this case, replace any previous data.
await db.insert(
'dogs',
dog.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
The method insert returns a future with the ID of new column.
// INSERT helper
Future<int> insert(String table, Map<String, dynamic> values,
{String nullColumnHack, ConflictAlgorithm conflictAlgorithm});
You can then send this ID instead or query the table with this ID to get the entry you need.

JDBC not updating sqlite table at specific column

I've encountered this very strange behaviour, where I construct a string to update a row of a table such as the following:
sql = "UPDATE cosmetics SET trail = 4,color = '[blue]',doTrail = 0,trails = null,trailSeen = null,inventory = null,uuid = 'abcd' WHERE uuid = 'abcd'";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
pstmt.close();
In a try catch, and the code runs fine.
My issue is everything but the first column mentioned(ie, trail in this case) is updated. If I check the table from sqlite with:
SELECT * FROM cosmetics WHERE uuid = 'abcd';
It returns
uuid|trail|doTrail|color|inventory|trails|trailSeen
abcd|0|0|[blue]|||
where previously, the value was:
uuid|trail|doTrail|color|inventory|trails|trailSeen
abcd|0|1|[white]|||
So doTrail was updated, and so was color, the only thing not updated was trail. I have no idea why this is, so any help would be much appreciated.
Here's the .schema cosmetics
CREATE TABLE cosmetics (uuid TEXT PRIMARY KEY, trail INTEGER, doTrail BOOLEAN, color TEXT DEFAULT "[white]", inventory TEXT, trails TEXT, trailSeen TEXT);
I should also mention if I copy and paste the value of sql directly into a terminal, there are no issues and the table is updated as expected.

How can I search new inserts in my access database?

I created an AddressBook GUI application with Insert, Update, Delete, Search, and Print functions. It connects to my access database table which contains four tables(names, addresses, phoneNumbers, and emailAddresses)
So far everything is working except when I try to search new input I just inserted into the table. If I search records I placed directly into access it works.
I THINK I narrowed down the problem but don't know how to fix it. When I insert new records into my table the names table creates a new primary key for that record but the rest of the tables don't, they only create a new foreign key number. Since my search is based on inner joining the id's I'm guessing my problem lies here but I'm not sure.
Here Is my Search Code
if (e.getActionCommand().equals("Search")){
JFrame mini = new JFrame();
// Gets user input. If user presses Cancel, 'name' will be null
String first = JOptionPane.showInputDialog(mini,"Enter first name:");
String last = JOptionPane.showInputDialog(mini, "Enter last name:");
try{
resultSet = statement.executeQuery( "SELECT * FROM ((names INNER JOIN addresses
ON names.personID = addresses.addressID)INNER JOIN phoneNumbers
ON names.personID = phoneNumbers.phoneID) INNER JOIN emailAddresses
ON names.personID = emailAddresses.emailID
WHERE lastName LIKE '%" + last + "%' AND firstName LIKE '%" + first+"%'");
resultSet.next();
jTextField1.setText(resultSet.getString("firstName"));
jTextField2.setText(resultSet.getString("lastName"));
jTextField3.setText(resultSet.getString("address1"));
jTextField4.setText(resultSet.getString("address2"));
jTextField5.setText(resultSet.getString("city"));
jTextField6.setText(resultSet.getString("state"));
jTextField7.setText(resultSet.getString("zipcode"));
jTextField8.setText(resultSet.getString("phoneNumber"));
jTextField9.setText(resultSet.getString("emailAddress"));
jTextField10.setText(resultSet.getString("personID"));
jTextField10.setEditable(false);
} catch(SQLException sqlException) {
JOptionPane.showMessageDialog(null, sqlException.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
Access uses * as the wildcard character, not %

How to get only contacts with birthdays in upcoming ascending order in android?

I am trying to fetch only those contacts for which birthday or anniversary information is available. However, I only found way to get contacts with phone number, but my app needs only contacts with birthday/anniversary information available and sorted in their upcoming birthdays order.
I am showing the results in ListView.
I need proper query to get around this problem, I tried googling and stackoverflow but found no solution.
Here is the code I'm using to get the information about contacts:
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
String SORT_ORDER = ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY + " ASC ";
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri,
null,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
if (contactsCursor.moveToFirst()) {
do {
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
String[] projection1 ={
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DATA2,
ContactsContract.Contacts.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.DATA1,
ContactsContract.CommonDataKinds.Phone.DATA15
};
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
String selection =
ContactsContract.Data.CONTACT_ID + "=" + contactId;
Cursor dataCursor = getContentResolver().query(
dataUri,
projection1, //projection
selection, //selection
null,
null);
////some code here
} while (dataCursor.moveToNext());
////some more code
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{Long.toString(contactId), displayName, photoPath, details});
}
} while (contactsCursor.moveToNext());
}
return mMatrixCursor;
}
I am getting all the required information correctly and having no problem with that, however I'm struggling in finding proper query to show only contacts with birthdays and sorting them in proper order as birthdays are not always stored in proper format. Thanks in advance !

Java oracle search

I have dropdown menu that has list of column names from certain table in the database and I have textbox where user can type what one is looking for. User first selects the column from dropdown menu and types on textbox what s/he is looking for. I am kind of lost how can i match those dropdown column name and textbox string to look under specific column in oracle database.. Any sample code or suggestion would be helpful.. Thank you
String colname = request.getParameter("colname");//get the column name from teh dropdown
String value = request.getParameter("value");//get the value that the user entered
PreparedStatement searchQuery = null;
String searchString = String.format("Select * from yourtable where %s = ?", colname);
//create a connection , say con
searchQuery = con.prepareStatement(searchString);
searchQuery.setString(1, value);
ReultSet rs = searchQuery.executeQuery();
This solution is only basic a idea so you have to modify to suit. If the columns that you are searching are of different types then you have to cater for that.

Categories

Resources