how to read last sms - android

Using the code below i wrote in TextView "textStareLed" first unreaded message. How can write the last message?
I try to use the cursor.moveToPrevious() but didn`t work.
protected void AfisareStareLed() {
TextView view = new TextView(this);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSMSURI, null, null, null, null)
while (cursor.moveToNext()){
if(cursor.getString(2).equals("+4xxxxx") && cursor.getString(8).equals("0")){//cursor.getString(8)==0 <=> "read=0"
TextView textStareLed = (TextView) findViewById(R.id.textStareLed);
textStareLed.setText(cursor.getString(13));
}
}
markMessageRead();//mark all message "read=1"
}

Just add "date desc limit 1"
String msgData = "";
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), new String[] {"body"}, null ,null, "date desc limit 1"); //if you change the 1 to 2 you´ll get the last 2 sms...
cursor.moveToFirst();
do{
for(int idx=0;idx<cursor.getColumnCount();idx++)
{
msgData += cursor.getString(idx);
}
}while(cursor.moveToNext());
textStareLed.setText(msgData);

Related

how to use where clause in cursor query in sqlite

I want only particular rows that has "E" inside the column "TX_IDT". I used the following code but apps stops. In logcat the error says it is at db.query line.
public Cursor getAllRows( ) {
String where = null;
SQLiteDatabase db = helper.getReadableDatabase();
String[] columns = { VivzHelper.UID, helper.UID,helper.NAME,helper.TX_IDT};
String whereClause = "TX_IDT = ? ";
String[] whereArgs = new String[] { "E" };
Cursor c = db.query( VivzHelper.TABLE_NAME, columns,whereClause,whereArgs, null, null, NAME + " ASC"); // for out btn
if (c != null) {
c.moveToFirst();
}
return c;
}
`
Seems like you want record's containing "E" ,
Try this
Cursor c = db.query(VivzHelper.TABLE_NAME, columns, helper.TX_IDT +" LIKE '%E%' ", null, null, null, null);

Can't read phone contacts

I got this Exception
12-01 12:28:42.552: E/AndroidRuntime(25581): Caused by: java.lang.IllegalStateException: Couldn't read row 1, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
When I want to use below code to read phone(sim) contacts
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor.moveToFirst()&&cursor.getCount()>0&&cursor!=null){
while (cursor.moveToNext()) {
// String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
User user=new User();
user.setFirstname(name);
user.setPhoneNumber(phone);
listdata.add(user);
cla_contact.notifyDataSetChanged();
}
cursor.close();
}
What's [roblem and how to solve?
Replace your first line of code with the following it is working for me.
Cursor cursor =
getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
You better change the order of conditions in the 'if' loop to avoid null pointer exceptions (if in case cursor is null).
if(cursor!=null && cursor.getCount()>0 && cursor.moveToFirst()){
Please accept the answer if it works for you. Thank you.
Do like this
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name= cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactID + " " + name);
}
}
it will move the cursor to the first row before reading the data.
Makr as right if it works for you. :)
Try this
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor.moveToFirst()){
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactID + " " + name);
}
cursor.close();
}
and also make sure you have this in manifest
<uses-permission android:name="android.permission.READ_CONTACTS" />
try like this,
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor != null && cursor.getCount() > 0){
if (cursor.moveToFirst()) {
do {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactID + " " + name);
} while (cursor.moveToNext());
}
cursor.close();

Index 0 requested with size of 0

I am trying to pull a record from the database but I am getting an error.
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
The following is the code I am using to pull the record.
public String[] getSingleTransaction(String table, String id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = null;
String[] data = new String[4];
try{
cursor = db.query(table, new String[] {KEY_ID, KEY_CREDIT, KEY_DEBIT, KEY_MEMO, KEY_TIMESTAMP}, KEY_ID + "=?",
new String[] {String.valueOf(id)}, null, null, null, null);
if(cursor != null) {
cursor.moveToFirst();
data[0] = cursor.getString(0); //This is where I am getting the error.
data[1] = cursor.getString(1);
data[2] = cursor.getString(2);
data[3] = cursor.getString(3);
data[4] = cursor.getString(4);
}
return data;
}finally {
cursor.close();
}
}
Is anyone able to see what I might be doing wrong here?
First thing i noticed is that you are accessing 5 elements..but your array was declared with 4. Your array must have 5 elements (size 5)..so it will be declared like this:
String[] data = new String[5];
then before accessing the cursor, you have to check if it 'successfully' moved to the first position..with this:
boolean success = cursor.moveToFirst();
if it is 'TRUE' then you can access the cursor. In your case, it would return 'FALSE' if your query would lead to no results..EMPTY result.
Change this:
if(cursor != null) {
cursor.moveToFirst();
data[0] = cursor.getString(0); //This is where I am getting the error.
data[1] = cursor.getString(1);
data[2] = cursor.getString(2);
data[3] = cursor.getString(3);
data[4] = cursor.getString(4);
}
to this:
if(cursor != null) {
if(cursor.moveToFirst()) {
data[0] = cursor.getString(0); //This is where I am getting the error.
data[1] = cursor.getString(1);
data[2] = cursor.getString(2);
data[3] = cursor.getString(3);
data[4] = cursor.getString(4);
}
}
I think the problem is that your cursor is not null but is not returning values, that is why it crashes.
PD: You should increase your String array as the other answer says :) as the following:
String[] data = new String[5];

Contacts First and Last name along with email id details in android

I am using the following code to retrieve the contacts first and last name list from android however i also want to retrieve the email simultaneously:
Cursor1 = getContentResolver().query(
public List<String> getFullContactName()
{
List<String> name = new ArrayList<String>();
String[] projection = new String[] {Data.DATA2, Data.DATA3};
String where = Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'";
Uri uri = Data.CONTENT_URI;
ContentResolver contentResolver = getApplicationContext().getContentResolver();
Cursor cursor = contentResolver.query(uri,projection,where,null,null);
String firstName, lastName;
while (cursor.moveToNext())
{
firstName = cursor.getString(cursor.getColumnIndex(Data.DATA2));
lastName = cursor.getString(cursor.getColumnIndex(Data.DATA3));
name.add(firstName + " " + lastName);
Toast.makeText(getApplicationContext(), "First name"+firstName, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Second name"+lastName, Toast.LENGTH_LONG).show();
}
cursor.close();
cursor = null;
return name;
}
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
}
cursor.close();
I need to know how can i read first name ,last name email, phone number together using a single Cursor because i need to fetch details in a list and then display them in a listview. I havent got a reference where i can fetch the details using a single cursor.
Use below code for get contact details.
public void getContacts(ContentResolver cr) {
ArrayList<HashMap<String, String>> mContacts = new ArrayList<HashMap<String, String>>();
HashMap<String, String> mTempObj = new HashMap<String, String>();
cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Email", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
cur.moveToNext();
}
}
cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Number", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA)));
cur.moveToNext();
}
}
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Name", cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
cur.moveToNext();
}
}
cur = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Address", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)));
mTempObj.add("City", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)));
mTempObj.add("State", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION)));
cur.moveToNext();
}
}
mContacts.add(mTempObj);
}
it will solve your problem.
remove
cursor.close();
cursor = null;
and make sure that the contactId that you passed to the Cursor emails is the same as the one that you retrieved from Cursor cursor which seems that you did not declare it in your String[] projection
For the first projection you can as follow:
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
this projection will retrive the contact Id and contact name, then to get the contact id and Name
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String Name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Then the second projection could be somthing:
String[] projection2= new String[]{
Email.ADDRESS,
Email.TYPE
Then define second cursor to get email within the first cursor something like
Cursor cur2 = cr.query(emailURI,projection2,Email.CONTACT_ID + "=" +id,null,null);
where id is the id that you got from first cursor.
Hope this help

Search sms Inbox

How can I search the sms inbox and show latest message from a special number. For example search for "999999999" and show last message received from this number. Is any way to do this?
I have use this code to return the count of messages my inbox
TextView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (TextView) findViewById(R.id.textView1);
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
int unreadMessagesCount = c.getCount();
c.deactivate();
view.setText(String.valueOf(unreadMessagesCount));
If you only want the last message sent by a specific number use this:
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(SMS_INBOX, null, "address = ?",
new String[] {"9999999999"}, "date desc limit 1");
if(cursor.moveToFirst()) {
// Do something
Log.v("Example", cursor.getString(cursor.getColumnIndex("body")));
}
cursor.close();
The second answer to How many database columns associated with a SMS in android? is a great reference for different columns in an SMS.
try as:
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX,null,null, null,"DATE desc");
if(c.moveToFirst()){
for(int i=0;i<c.getCount();i++){
String body= c.getString(c.getColumnIndexOrThrow("body")).toString();
String number=c.getString(c.getColumnIndexOrThrow("address")).toString();
if(number=="999999999")
{
//get message body here
break;
}
else
c.moveToNext();
}
}
c.close();

Categories

Resources