I am desperate to find the solution so I ask for help!
I am a new french programmer. My objective is to create a widget able to show SMS.
My problem is that I don’t know how create a cursor which select the first SMS in content://sms/inbox
Excuse my bad English, I hope you will able to understand my wich.
Thank you for your answer.
this is my code:
package sfeir.monwidget;
import android.R.string;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.net.Uri;
import android.widget.RemoteViews;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.widget.ArrayAdapter;
public class MonWidget extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Uri uri = Uri.parse("content://sms/inbox");
// returns all the results.
Cursor c= getContentResolver().query(uri, null, null ,null,null);
// called by the Activity.
startManagingCursor(c);
String body = null;
String number = null;
if(c.moveToFirst()) { // move cursor to first row
// retrieves the body and number of the SMS
body = c.getString(c.getColumnIndexOrThrow("body")).toString();
number = c.getString(c.getColumnIndexOrThrow("address")).toString();
}
// when your done, close the cursor.
c.close();
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text, (CharSequence) body);
ComponentName thisWidget = new ComponentName(context, MonWidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
}
}
You would need to set specific permissions (read below for the link) but here is example of the code to use a
Cursorto retrieve the first SMS message.I would recommend looking over FrontPage/Tutorials/SMS Messaging – Mobdev Wiki it gives a good introductory on dealing with SMS handling on Android.
EDIT:
Those methods were not visible to your application because it was not extending to the
Activitysuperclass. By default, when you develop an application, it inherits methods from that relationship. But you are not creating an application, per se, you are developing a widget.Luckily, within the
onUpdatemethod they pass in the currentContextwhich is a super class forActivityso we can use the variablecontextto invokegetContentResolver(see above in the code)I also removed
startManagingCursormethod from the code, it is not completely necessary to have, it allows the Activity to handle the givenCursor‘s lifecycle based on the Activity’s lifecycle.Let me know if theres any problems.
EDIT 2:
Inside your
AndroidManifest.xmlfile you need to set the correct permissions to avoid any exceptions, add this line.