How check if sms/inbox is empty? - android

I'd like to know if we can write a short boolean test which return true if sms/inbox is empty or not.
Something like Databse("content://sms/inbox")==null?

Here's the code:
// Retrieve a Cursor pointing to the sms list and the size of it.
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = mContext.getContentResolver().query(uriSMSURI, null, null, null, null);
boolean ret = cur.getCount() > 0;
Remember to close the cursor afterwards.

You should have a look at this , its not a simple one liner but it will give you the data you require. It seems there is no documented way to do this easily , you are going to have to do alot of manual work or hope someone has written a lib to do it all for you

Related

Getting All data from specific column in SQLITE Android

There is android sqlite database with one table, im using this query for getting values :
Cursor cursor = db.query(Table_Items, null, "type=? AND operationtype=? AND problemtype=?",
new String[] { roosazi,type,problem }, null, null,KEY_Items_ID+" "+date , null);
everything is working fine.
question is:
how can i get all from specific column? let me give an example:
all values with type="A" and operationtype="XYZ" are needed , no matter what problemtype is! of course i can use something like this :
Cursor cursor = db.query(Table_Items, null, "type=? AND operationtype=?",
new String[] { roosazi,type }, null, null,KEY_Items_ID+" "+date , null);
but problem is sometimes problemtype is X and sometimes its like ALL!
how can i achieve this? can i put something like * instead of problem?
thank u so much
I understand that you want to use the same query to get sometimes with a particular problem type like X,Y or Z, and sometimes with any problem type,
If that is the case you could use the statement 'like' in your query instead of '=' in the problemtype field
Cursor cursor = db.query(Table_Items, null, "type=? AND operationtype=? AND problemtype like '?'",
When you want to return all values just past
problem = "%"
% simbol means any characters,
When you want to return values with a particular problem use
problem = "X"
in the values array
new String[] { roosazi,type,problem }

How to get Missed call & SMS count

I want to get the count of missed calls and unread messages in my application. and I'd like to open the relevant application when user click on the count.
Now biggest problem is how to get the count?
I searched online but couldn't find any solution.
Thanks in advance.
http://developer.android.com/reference/android/provider/CallLog.Calls.html
Take a look at this CallLog class. All you need is to query the phone for any calls then extract missed one (оr do this when you are querying the phone, in the selection arguments). The same applies for the messages. SMS are stored in the Content provider under "content://sms/"
Then just get the count of rows in the Cursor that is return by the query. :)
I hope this helps.
For missed calls:
String[] projection = {
CallLog.Calls.CACHED_NAME,
CallLog.Calls.CACHED_NUMBER_LABEL,
CallLog.Calls.TYPE
};
String where = CallLog.Calls.TYPE + "=" + CallLog.Calls.MISSED_TYPE;
Cursor c = this.getContentResolver().query(
CallLog.Calls.CONTENT_URI,
selection,
where,
null,
null
);
c.moveToFirst();
Log.d("CALL", ""+c.getCount()); //do some other operation
if (c.getCount() == SOME_VALUE_TO_START_APP_ONE) //...etc etc
In the where clause you set condition for selection of data. In our case we need everything which type equals CallLog.Calls.MISSED_TYPE. We select project the Name of the caller and his number, ofcourse you can specify more information to be queried like type of number like mobile, home, work.
The expression is equivalent to SQL query, something like: SELECT CACHED_NAME, CACHED_NUMBER_LABEL, TYPE FROM CONTENT_URI WHERE TYPE=MISSED_TYPE
This requires permissions to be added to the Manifest
<uses-permission android:name="android.permission.READ_LOGS"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
For querying SMS ContentProvider:
Uri sms_content = Uri.parse("content://sms");
Cursor c = this.getContentResolver().query(sms_content, null,null, null, null);
c.moveToFirst();
Log.d("SMS COUNT", "" + c.getCount()); //do some other operation
// Here proceed with the what you wanted
if (c.getCount() == SOME_VALUE_TO_START_APP_ONE)//...etc etc
You can go deeper in the content tree like specifying the type of sms, like: content://sms/sent or content://sms/inbox and add projection and selection for the second argument of the query() method like, name, person, status of the message (like the Calls example).
This requires permission:
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
As I don't have enough reputation to answer #Prasad question comment about
ERROR -> getContentResolver() is undefined for the type new Runnable(){}
getContentResolver() is part of application context, so if you are using a BroadcastReceiver use context in onReceive() function like this
#Override
public void onReceive(Context context, Intent intent) {
context.getContentResolver()
}
If you are using the code above inside an Activity, then you can use
getApplicationContext().getContentResolver()
also make sure to use [Ctrl + Shift + O (O not zero)] to organize imports
Key Shortcut for Eclipse Imports

Removing rows from an Android SQLite Cursor

I query and get a result set back, but I need to do some calculations that are impossible in the SQLite WHERE clause in order to determine what shows up in the ListView. How can I remove certain rows from the cursor? I know it is the same question as this Filter rows from Cursor so they don't show up in ListView but that answer does not help. Can an example be provided if there isn't a simpler way to do this?
It might work to simply retain all the rows in the Cursor, but then use a custom adapter to hide the unwanted rows at display time. For example, if you extend CursorAdapter, then you might have something like this in your bindView implementation:
View v = view.findViewById(R.id.my_list_entry);
boolean keepThisRow = .......; // do my calculations
v.setVisibility(keepThisRow ? View.VISIBLE : View.GONE);
There should be a better way to do this, but what I ended up doing is storing the ID of each row I wanted in a string ArrayList, and then requerying where _id IN arraListOfIds.toString(), replacing the square brackets with parentheses to fit SQL syntax.
// Get all of the rows from the database
mTasksCursor = mDbHelper.fetchAllTasks();
ArrayList<String> activeTaskIDs = new ArrayList<String>();
// calculate which ones belong
// .....
if (!hasCompleted)
activeTaskIDs.add(mTasksCursor.getString(TaskerDBadapter.INDEX_ID));
// requery on my list of IDs
mTasksCursor = mDbHelper.fetchActiveTasks(activeTaskIDs);
public Cursor fetchActiveTasks(ArrayList<String> activeTaskIDs)
{
String inClause = activeTaskIDs.toString();
inClause = inClause.replace('[', '(');
inClause = inClause.replace(']', ')');
Cursor mCursor = mDb.query(true, DATABASE_TABLE, columnStringArray(),
KEY_ROWID + " IN " + inClause,
null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
ContentResolver cr = getContentResolver();
Cursor groupCur = cr.query(
Groups.CONTENT_URI, // what table/content
new String [] {Groups._ID, Groups.NAME}, // what columns
"Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
null, // ???
Groups.NAME + " ASC" // sort order
);
The "What Columns" piece above is where you can tell the cursor which rows to return. Using "null" returns them all.
I need to do some calculations that
are impossible in the SQLite WHERE
clause
I find this very hard to believe; my experience has been that SQL will let you query for just about anything you'd ever need (with the exception of heirarchical or recursive queries in SQLite's case). If there's some function you need that isn't supported, you can add it easily with sqlite_create_function() and use it in your app. Or perhaps a creative use of the SELECT clause can do what you are looking for.
Can you explain what these impossible calculations are?
EDIT: Nevermind, checking out this webpage reveals that the sqlite_create_function() adapter is all closed up by the Android SQLite wrapper. That's annoying.

sqlite LIKE problem in android

Hello i've spent almost 2 hours trying to figure out why the LIKE statement doesn't work and i only get this error: 03-03 11:31:01.770: ERROR/AndroidRuntime(11767): Caused by: android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x89d9f8
In SQLiteManager it works perfectly like this: SELECT Word FROM Sign WHERE Word LIKE 'he%';
But when i try to do it from java it won't work.
Here's is my query, i've tried in a lot of ways with no luck:
Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word"+" LIKE '"+" ?"+"%'", new String[]{name}, null, null, null);
Any ideas? i'm i doing it wrong or is there a bug?
Thanks for your time.
The solution is actually very easy. Just include the % inside your selectionArgs.
String []selectionArgs = {name + "%"});
I think you shouldn't use selArgs for LIKE such a way. You may try this:
Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word"+" LIKE '"+name+"%'", null, null, null, null);
EDIT:
OK, if you want be safe from SQL injections, don't use above solution, use this:
Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word LIKE '?'", new String[]{name+"%"}, null, null, null);
This is how I did:
String []columns = {"_id", "name"};
String []selectionArgs = {name+"%"};
db.query(true,"mydb",columns,"name LIKE ?",selectionArgs,null,null,null);
Another -- perhaps cleaner -- solution is to use the || operator as described here: Sqlite binding within string literal

Help with the Android Cursor

So I have a Cursor that is getting a result from a query to the application database. I know that there is at least one correct entry in the database since I was able to retrieve the string from the row previously.
I then changed some of the logic to accommodate the result and am suddenly getting null returned when calling c.getString(0). The relevant code is posted below.
I'm new to Android and Java, so I might be missing some subtlety that's causing the problem.
Cursor c = context.getContentResolver().query(tempJobName.build(),
null, null, null, null);
for (c.moveToFirst(); c.isAfterLast() == false; c.moveToNext())
{
Log.w(TAG, c.getString(0));
if (c.getString(0).equalsIgnoreCase(jobName))
{
existed = true;
break;
}
}
You might want to add more details. But since you did find some records, the solution for your problem is easy. Could you please replace this line with this? ( First column of table might change right :))
c.getString(0);
with
int columnIndex = c.getColumnIndex(COLUMN_NAME);// You could also use getcolumnIndexorThrow variant.
c.getString(columnIndex);
if this does not work, then your table does not have the column. You are simply barking up the wrong tree.

Categories

Resources