I'm trying to make a query where I get data from two tables but it won't show me any result. I know there is a result because in SQLite3 it displays at least one, e.g.
sqlite> select eventthemename, eventtypename from event_type, event_theme
...> where event_type.eventthemes = event_theme._id
...> and event_type._id = '2';
Tribal | Dance
I'm using a content provider. Does anyone have an idea on how to make this?
Your question isn't really clear (you should include some of your code!), so I might not answer your question as you hoped. But following is a simple example I have where I join two tables in one query:
private static final String QUERY_ALL_COURSES_WITH_SEMESTER =
"SELECT * FROM Course JOIN Semester ON semesterId = courseSemesterId";
public Course getCourseByCodeAndSemester(String courseCode, Semester semester)
{
Course result = null;
String whereClause = " WHERE courseCode = '" + courseCode.toUpperCase() + "'"
+ " AND semesterId = " + semester.getInternalId();
Cursor cursor = db.rawQuery(QUERY_ALL_COURSES_WITH_SEMESTER + whereClause, null);
if (cursor.moveToFirst())
{
result = Course.createFromCursor(cursor);
}
cursor.close();
return result;
}
Note that there are probably many things that could be optimized in this function, but it illustrates how it can be done.
As I'm using content providers I ended doing something not quite fast but that works:
themes = managedQuery(
EventTheme.CONTENT_URI,
PROJECTIONTHEMES,
EventTheme.EVENTTYPE + "= ?",
new String[] {eventType},
EventTheme.DEFAULT_SORT_ORDER);
String[] from = new String[] {
Event._ID,
Event.NAME,
Event.STARTDATE,
Event.ENDDATE,
PointOfInterest.POINTOFINTERESTNAME
};
int[] to = new int[] {
R.id.event_id,
R.id.name,
R.id.start_date,
R.id.end_date,
R.id.location_name
};
while (themes.getPosition() < themes.getCount() - 1) {
themes.moveToNext();
eventTheme = themes.getString(themes.getColumnIndexOrThrow(EventTheme._ID));
events = managedQuery(
Event.CONTENT_URI,
PROJECTIONEVENTS,
Event.EVENTTHEME + "= ?",
new String [] { eventTheme } ,
Event.DEFAULT_SORT_ORDER);
}
Related
I'm getting skype contacts in my android device with this code:
private void getContactList() {
Cursor c = getContentResolver().query(
RawContacts.CONTENT_URI,
new String[] { RawContacts.CONTACT_ID,
RawContacts.DISPLAY_NAME_PRIMARY,
RawContacts.DISPLAY_NAME_ALTERNATIVE },
RawContacts.ACCOUNT_TYPE + "= ?",
new String[] { "com.skype.contacts.sync" }, null);
int contactNameColumn = c
.getColumnIndex(RawContacts.DISPLAY_NAME_ALTERNATIVE);
int count = c.getCount();
skypeName = new String[count];
for (int i = 0; i < count; i++) {
c.moveToPosition(i);
skypeName[i] = c.getString(contactNameColumn);
Log.i("KEY", skypeName[i]);
}
}
This code works fine, but it returns the skype display names.However is there any possibility to get Skype name not the display name so I can call or video call using that Skype name?.
Thanks,
Regards.
You need to query over the Data table not RawContacts, the Data table's data is organized by mimetypes, you just need to find the mimetype containing the info you're looking for, in skype's case it's: "vnd.android.cursor.item/com.skype.android.skypecall.action"
private void getContactList() {
Cursor c = getContentResolver().query(
Data.CONTENT_URI,
new String[] { Data.CONTACT_ID, Data.DATA1 },
Data.MIMETYPE + "= ?",
new String[] { "vnd.android.cursor.item/com.skype.android.skypecall.action" },
null);
while (c != null && c.moveToNext()) {
String contact = c.getLong(0);
String skype = c.getString(1);
Log.i("contact " + contact + " has skype username: " + skype);
}
}
I've typed the code here, so it's not checked and I might have typos
Make sure you ALWAYS close cursors via c.close()
I'm not incredibly familiar with the Android-Skype API, but it looks like this line
.getColumnIndex(RawContacts.DISPLAY_NAME_ALTERNATIVE);
is what pulls the display name instead of the username. You could check the API and see if there's another RawContacts.method that fetches the username instead.
Additional information could be available here:
http://www.programmableweb.com/api/skype
or
http://www.skype.com/en/developer/
I'm trying to execute a query on a SQLiteDatabase in Android, using the query() function. I want to pass the argument in SelectionArgs[], but when I'm using a IN statement, it doesn't seem to substitute the '?' with the correct argument.
My query looks like this:
temp = database.query(TABLE_NAME_ENTRIES,
new String[] {"_id", "Entry", "Summary"},
"_id IN ( ? )",
new String[] {ids}, null, null, null);
and it results in an empty Cursor. Debug gives me the information that the executed query uses a statement "_id IN ( ? )", showing that it doesn't seem to replace the '?' as expected. When I change the query to
temp = database.query(TABLE_NAME_ENTRIES,
new String[] {"_id", "Entry", "Summary"},
"_id IN ( " + ids + " )",
null, null, null, null);
instead, I get the expected result.
I'm really stupid on this problem, any ideas what I'm doing wrong?
You could use a workaround like this - creating a method that generates dynamically your string with ? and , and put it in the query like this:
String[] ids = { "id1", "id2" }; // do whatever is needed first
String query = "SELECT * FROM table"
+ " WHERE _id IN (" + makePlaceholders(ids.length) + ")";
Cursor cursor = mDb.rawQuery(query, ids);
String makePlaceholders(int len) {
if (len < 1) {
// It will lead to an invalid query anyway ..
throw new RuntimeException("No placeholders");
} else {
StringBuilder sb = new StringBuilder(len * 2 - 1);
sb.append("?");
for (int i = 1; i < len; i++) {
sb.append(",?");
}
return sb.toString();
}
}
P.S. I think that the spaces before and after the question mark in your query could be wrong there, but I didn't test it, so I can't be 100% sure
I'm trying to implement dynamic queries in my Android app, to let the users search according to some criteria. In this case I'm trying to search simply by an integer value. Here's my attempt:
...
public String[][] listarNegocio(int idProyecto,
int minimo,
int maximo)
{
String[][] arrayDatos = null;
String[] parametros = {String.valueOf(idProyecto)};
Cursor cursor = null;
cursor = querySQL("SELECT *" +
" FROM negocio" +
" WHERE ? in (0, id_proyecto)", parametros);
if(cursor.getCount() > 0)
{
int i = minimo - 1;
arrayDatos = new String[maximo - minimo + 1][20];
while(cursor.moveToNext() && i < maximo)
{
// Here I fill the array with data
i = i + 1;
}
}
cursor.close();
CloseDB();
return(arrayDatos);
}
public Cursor querySQL(String sql, String[] selectionArgs)
{
Cursor oRet = null;
// Opens the database object in "write" mode.
db = oDB.getReadableDatabase();
oRet = db.rawQuery(sql, selectionArgs);
return(oRet);
}
...
I tested this query using SQLFiddle, and it should return only the rows where the column id_proyecto equals the parameter idProyecto, or every row if idProyecto equals 0. But it doesn't return anything. If I remove the WHERE clause and replace "parametros" with "null", it works fine.
Additionally, I need to search by text values, using LIKE. For example, WHERE col_name LIKE strName + '%' OR strName = ''. How should I format my parameters and the query to make it work?
You should do one query for each case. For an id that exists, do SELECT * FROM negocio WHERE id_proyecto = ?. For an id that doesn't exist (I'm assuming 0 isn't a real id), just query everything with SELECT * FROM negocio.
Code should be something like this:
if(parametros[0] != 0){
cursor = querySQL("SELECT *" +
" FROM negocio" +
" WHERE id_proyecto = ?", parametros);
} else {
cursor = querySQL("SELECT *" +
" FROM negocio", null);
}
Regarding your second question, it depends on what you're looking for, you could use LIKE '%param%' or CONTAINS for occurrences in between text, LIKE param for partial matches or just = param if you're looking an exact match.
I am trying to write an SQL database request using .query instead of .rawQuery (i have been told it's more efficient, even though not everyone seem to agree with this...).
If I had to write it in SQL, it would be approximately something like this :
select COL_NAME, COL_COMMENTS, KEY_ROW_ID
from TABLE
where COL_CAT1 = myVariable1 or myVariable2 or ... myVariableN
or COL_CAT2 = myVariable1 or myVariable2 or .... myVariableN
or COL_CAT3 = myVariable1 or myVariable2 or.... myVariableN
I have tried this :
public Cursor findNameInTable(int myVariable1, int myVariable2, int myVariableN) {
String where = COL_CAT1 + " = ? OR " + COL_CAT2 + "=?";
String[] whereArgs = new String[] { Integer.toString(myVariable1), Integer.toString(myVariable2), Integer.toString(myVariableN)};
c = myDatabase
.query(DATABASE_TABLE, new String[] { KEY_ROWID, COL_NAME , COL_COMMENTS },
where,
whereArgs, null,
null, null);
return c;
}
The problem with this is that the system is doing this :
select .....
from .....
where COL_CAT1 = myVariable1
or COL_CAT2 = myVariable2
or ???? = myVariableN
and then it crashes because it expects to compare each variable with a new column, which is not what I want: I have more inputs variable than columns.
It's actually the " =?" which seems not to be appropriate, but no way to find how to write this kind of request, most of documentation is about rawQuery() and not query(). Thanks in advance.
Try this
public Cursor findNameInTable(int myVariable1, int myVariable2, ..., int myVariableN)
{
String inInterval = "(?,?,?,...,?)"; // N question mark altogether.
String where = COL_CAT1 + " IN " + inInterval
+ " OR " + COL_CAT2 + " IN " + inInterval
+ ...........
+ " OR " + COL_CATM + " IN " + inInterval;
int numberOfColumn = M; // The number of columns you have.
String[] whereArgs = new String[M * N];
for (int i = 0; i < M; i++)
{
whereArgs[i * N + 0] = Integer.toString(myVariable1);
whereArgs[i * N + 1] = Integer.toString(myVariable2);
whereArgs[i * N + 2] = Integer.toString(myVariable3);
........................
whereArgs[i * N + N - 1] = Integer.toString(myVariableN);
}
Cursor c = myDatabase
.query(DATABASE_TABLE, new String[] { KEY_ROWID, COL_NAME , COL_COMMENTS },
where,
whereArgs, null,
null, null);
return c;
}
Because you are creating an extensive query, you may want to consider using:
http://developer.android.com/reference/android/database/sqlite/SQLiteQueryBuilder.html
This will allow you to basically create a longer where clause. However; this should also theoretically be possible with a rawQuery with a StringBuilder, but in best practices its better to use the wrapper approach method.
Whenever I want to add new data to an existing Android contact, I use the following function to retrieve all RawContacts IDs for the given contact ID:
protected ArrayList<Long> getRawContactID(String contact_id) {
ArrayList<Long> rawContactIDs = new ArrayList<Long>();
String[] projection = new String[] { ContactsContract.RawContacts._ID };
String where = ContactsContract.RawContacts.CONTACT_ID + " = ?";
String[] selection = new String[] { contact_id };
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, where, selection, null);
try {
while (c.moveToNext()) {
rawContactIDs.add(c.getLong(0));
}
}
finally {
c.close();
}
return rawContactIDs;
}
After that, I just insert the data using the ContentResolver:
getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
This is done for all RawContacts IDs that have been found previously. The effect is, of course, that all data is added repeatedly. Thus I want to return only one result now, but this has to meet special requirements.
I would like to adjust my function above so that its result meets the following requirements:
ContactsContract.RawContactsColumn.DELETED must be 0
The RawContacts entry must not be a secured one like Facebook's
ContactsContract.SyncColumns.ACCOUNT_TYPE is preferably "com.google". So if there is one entry that meets this requirement, it should be returned. If there is none, return any of the remaining entries.
How can I do this (most efficiently)? I don't want to make the query to complex.
I have given this some thought, from my experience with contact r/w, and with your needs in mind. I hope this helps you solve the issue and or points you in the direction you are looking for.
Please note that i have no device available with any sync adapters such as facebook so unfortunately i cannot confirm my answer viability (the read only bit mainly which might changeable to a simple != '' ).
Same getRawContactID function with some adjustments
protected ArrayList<Long> getRawContactID(String contact_id) {
HashMap<String,Long> rawContactIDs = new HashMap<String,Long>();
String[] projection = new String[] { ContactsContract.RawContacts._ID, ContactsContract.RawContacts.ACCOUNT_TYPE };
String where = ContactsContract.RawContacts.CONTACT_ID + " = ? AND " + ContactsContract.RawContacts.DELETED + " != 1 AND " + ContactsContract.RawContacts.RAW_CONTACT_IS_READ_ONLY + " != 1" ;
String[] selection = new String[] { contact_id };
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, where, selection, null);
try {
while (c.moveToNext()) {
rawContactIDs.put(c.getString(1),c.getLong(0));
}
}
finally {
c.close();
}
return getBestRawID(rawContactIDs);
}
And another getBestRawID function to find the best suited account -
protected ArrayList<Long> getBestRawID(Map<String,Long> rawContactIDs)
{
ArrayList<Long> out = new ArrayList<Long>();
for (String key : rawContactIDs.KeySet())
{
if (key.equals("com.google"))
{
out.clear(); // might be better to seperate handling of this to another function to prevent WW3.
out.add(rawContactIDs.get(key));
return out;
} else {
out.add(rawContactIDs.get(key));
}
}
return out;
}
Also note - I wrote most of the code without running / testing it. Apologies in advance.