the android widget content when device rotated are suddenly gone.
do I have to repopulate them when device is rotated? but the widget dont have onconfiguration change to listen to.
also I used alarmmanager with service to populate the widget for new app (adding to viewflipper) to display every 1 minute.
widget code:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
try{
// create intent service per APP id
for(int i = 0; i < appWidgetIds.length; i++)
{
Log.e("onUpdate -- Widget_2_6", "onUpdate -- Widget_2_6: widget ID: " + appWidgetIds[i]);
// check if alarms not created, create 1
if(!GlobalStorage.tempStorage.containsKey(Widget_2_6.class.toString() + appWidgetIds[i]))
{
createAlarmService(context, appWidgetIds[i]);
// put to hash for alarms created
GlobalStorage.tempStorage.put(Widget_2_6.class.toString() + appWidgetIds[i], 0);
//CustomAndroidTools.popToast(Widget_2_6.class.toString() + appWidgetIds[i], context);
}
}
}
catch(Exception e)
{
Log.e("onUpdate -- Widget_2_6", "onUpdate -- Widget_2_6: error: " + e.toString());
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
private void createAlarmService(Context context, int id)
{
if(alarm == null)
{
createAlarm(context);
}
// each new alarm will repeat in increasing half minute: so first is 1 min next is 1 min and 30 sec ...
alarm.setRepeating(AlarmManager.RTC, 0, (1000 * (60 + (GlobalStorage.tempStorage.size() * 30))), createPendingIntent(context, id));
Log.e("createAlarmService -- Widget_2_6", "createAlarmService -- Widget_2_6, creating alarm for widget id: " + id);
}
service code:
if(CustomAndroidTools.checkDeviceIsInteractive(context))
{
new Thread(new Runnable() {
public void run() {
try{
ArrayList<AppInfo> appInfos = init(context, _class, widgetID);
buildUpdate(context, _class, widgetID, appInfos);
// update the limit offset here instead so that to ensure no exception came from building the UI of the widget
updateLimitOffset(_class, widgetID);
}
catch(Exception e)
{
Log.e("Thread -- onStartCommand -- WidgetUpdateService", "Thread -- onStartCommand -- WidgetUpdateService: error: " + e.toString());
}
}
}).start();
}
private ArrayList<AppInfo> init(Context context, Class<?> _class, int widgetID)
{
ArrayList<AppInfo> appInfos = new ArrayList<AppInfo>();
try{
appListManager alm = new appListManager(context);
int skip = 0;
//int limit = 10;
if(GlobalStorage.tempStorage.containsKey(_class.toString() + widgetID))
{
skip = GlobalStorage.tempStorage.get(_class.toString() + widgetID);
}
if(skip == 0) // first initialize
{
///TODO: for testing, get the first 5 used by banner
appInfos.add(alm.getAppById(30));
appInfos.add(alm.getAppById(16));
appInfos.add(alm.getAppById(13));
appInfos.add(alm.getAppById(12));
appInfos.add(alm.getAppById(6));
}
//appInfos = alm.getAllAppsUnderTheCategory(-1, skip, limit);
}
catch(Exception e)
{
Log.e("init -- WidgetUpdateService", "init -- WidgetUpdateService: error: " + e.toString());
}
return appInfos;
}
private void updateLimitOffset(Class<?> _class, int widgetID){
int skip = 0;
int limit = 10;
if(GlobalStorage.tempStorage.containsKey(_class.toString() + widgetID))
{
skip = GlobalStorage.tempStorage.get(_class.toString() + widgetID);
}
if(skip != 0)
{
limit = 5;
}
GlobalStorage.tempStorage.put(_class.toString() + widgetID, skip + limit); // update offset limit here
}
private void buildUpdate(Context context, Class<?> _class, int widgetID, ArrayList<AppInfo> appInfos) throws Exception
{
RemoteViews views = null;
appListManager alm = new appListManager(context);
try{
if(_class.equals(Widget_1_6.class) || _class.equals(Widget_1_6_2.class))
{
views = new RemoteViews(getPackageName(), R.layout.widget_1_6);
}
else if(_class.equals(Widget_2_6.class) || _class.equals(Widget_2_6_2.class))
{
views = new RemoteViews(getPackageName(), R.layout.widget_2_6);
}
if(alm.getTotalApps(-1) < 1)
{
views.setViewVisibility(R.id.app, View.GONE);
views.setViewVisibility(R.id.sorryText, View.VISIBLE);
views.setViewVisibility(R.id.loadingText, View.GONE);
}
else
{
views.setViewVisibility(R.id.app, View.VISIBLE);
views.setViewVisibility(R.id.sorryText, View.GONE);
views.setViewVisibility(R.id.loadingText, View.GONE);
if(appInfos != null)
{
for(int i = 0; i < appInfos.size(); i++)
{
views.addView(R.id.appInfo, inflateLayout(appInfos.get(i), context, _class, widgetID));
}
}
Intent refreshWidgetIncrement = new Intent(context, WidgetControlService.class);
refreshWidgetIncrement.putExtra(WidgetControlService.INCREMENT, true);
refreshWidgetIncrement.putExtra(WidgetControlService.DECREMENT, false);
refreshWidgetIncrement.putExtra(WidgetControlService.CLASS, _class);
refreshWidgetIncrement.putExtra(WidgetControlService.WIDGET_ID, widgetID);
refreshWidgetIncrement.setData(Uri.withAppendedPath(Uri.parse("BFR://widget/id/#togetituniqie" + WidgetControlService.class.toString()), UUID.randomUUID().toString()));
PendingIntent pIntentIncrement = PendingIntent.getService(context, 0, refreshWidgetIncrement, PendingIntent.FLAG_CANCEL_CURRENT);
views.setOnClickPendingIntent(R.id.arrowRight, pIntentIncrement);
Intent refreshWidgetDecrement = new Intent(context, WidgetControlService.class);
refreshWidgetDecrement.putExtra(WidgetControlService.DECREMENT, true);
refreshWidgetDecrement.putExtra(WidgetControlService.INCREMENT, false);
refreshWidgetDecrement.putExtra(WidgetControlService.CLASS, _class);
refreshWidgetDecrement.putExtra(WidgetControlService.WIDGET_ID, widgetID);
refreshWidgetDecrement.setData(Uri.withAppendedPath(Uri.parse("BFR://widget/id/#togetituniqie" + WidgetControlService.class.toString()), UUID.randomUUID().toString()));
PendingIntent pIntentDecrement = PendingIntent.getService(context, 0, refreshWidgetDecrement, PendingIntent.FLAG_CANCEL_CURRENT);
views.setOnClickPendingIntent(R.id.arrowLeft, pIntentDecrement);
}
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(widgetID, views);
}
catch(Exception e)
{
Log.e("buildUpdate -- WidgetUpdateService", "buildUpdate -- WidgetUpdateService: error: " + e.toString());
}
}
private RemoteViews inflateLayout(AppInfo appInfo, Context context, Class<?> _class, int widgetID) throws IOException
{
RemoteViews view = null;
if(_class.equals(Widget_1_6.class) || _class.equals(Widget_1_6_2.class))
{
view = new RemoteViews(getPackageName(), R.layout.widget_1_6_body_fragment);
view = inflateWidget1_6(view, appInfo, context, _class, widgetID);
}
else if(_class.equals(Widget_2_6.class) || _class.equals(Widget_2_6_2.class))
{
view = new RemoteViews(getPackageName(), R.layout.widget_2_6_body_fragment);
view = inflateWidget2_6(view, appInfo, context, _class, widgetID);
}
return view;
}
private RemoteViews inflateWidget1_6(RemoteViews view, AppInfo appInfo, Context context, Class<?> _class, int widgetID) throws IOException
{
view.setTextViewText(R.id.appTitle, appInfo.title);
view.setTextViewText(R.id.appDesc, appInfo.shortDesc);
File file = new File(Constants.saveImageLocation + appInfo.iconLoc);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bitmap = null;
if(file.exists()) // if exists in local
{
bitmap = BitmapFactory.decodeFile(Constants.saveImageLocation + appInfo.iconLoc, options);
}
else if (CustomAndroidTools.isImageFoundInAssets(appInfo.iconLoc, context))
{
bitmap = CustomAndroidTools.getImageFromAssets(appInfo.iconLoc, context);
}
else
{
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.broken, options);
}
view.setImageViewBitmap(R.id.appIcon, bitmap);
view.setOnClickPendingIntent(R.id.appIcon, null);
view.setOnClickPendingIntent(R.id.appDetail, null);
Intent openApp = new Intent(context, AppDetailViewActivity.class);
openApp.putExtra(AppDetailViewActivity.LAST_SELECTED_APP, appInfo);
Log.e("current App", "current App: name: " + appInfo.title + ", category index: " + appInfo.category + ". For Widget type: " + _class.toString() + ", id: " + widgetID);
openApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
openApp.setData(Uri.withAppendedPath(Uri.parse("BFR://widget/id/#togetituniqie" + new ComponentName(context, _class)), UUID.randomUUID().toString()));
PendingIntent pIntent = PendingIntent.getActivity(context, 0, openApp, 0);
view.setOnClickPendingIntent(R.id.appIcon, pIntent);
view.setOnClickPendingIntent(R.id.appDetail, pIntent);
return view;
}
private RemoteViews inflateWidget2_6(RemoteViews view, AppInfo appInfo, Context context, Class<?> _class, int widgetID) throws IOException
{
File file = new File(Constants.saveImageLocation + appInfo.bannerLoc);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bitmap = null;
if(file.exists()) // if exists in local
{
bitmap = BitmapFactory.decodeFile(Constants.saveImageLocation + appInfo.bannerLoc, options);
}
else if (CustomAndroidTools.isImageFoundInAssets(appInfo.bannerLoc, context))
{
bitmap = CustomAndroidTools.getImageFromAssets(appInfo.bannerLoc, context);
}
else
{
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.broken, options);
}
view.setImageViewBitmap(R.id.appBanner, bitmap);
view.setOnClickPendingIntent(R.id.appBanner, null);
Intent openApp = new Intent(context, AppDetailViewActivity.class);
openApp.putExtra(AppDetailViewActivity.LAST_SELECTED_APP, appInfo);
Log.e("current App", "current App: name: " + appInfo.title + ", category index: " + appInfo.category + ". For Widget type: " + _class.toString() + ", id: " + widgetID);
openApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
openApp.setData(Uri.withAppendedPath(Uri.parse("BFR://widget/id/#togetituniqie" + new ComponentName(context, _class)), UUID.randomUUID().toString()));
PendingIntent pIntent = PendingIntent.getActivity(context, 0, openApp, 0);
view.setOnClickPendingIntent(R.id.appBanner, pIntent);
return view;
}
is there anything i missed?
Ok. got it working, the problem is with the RemoteView's behavior.(NOTE: RemoteView will send the latest changes to views needing a refresh/update)
so what I did was instead of using manager.updateAppWidget(widgetID, views); on all occasion.
I used a flag to know when to use updateAppWidget or partiallyUpdateAppWidget.
below is the modified code under the buildUpdate function from above listing, replacing manager.updateAppWidget(widgetID, views); into:
if(!GlobalStorage.tempStorage.containsKey(_class.toString() + widgetID) || GlobalStorage.tempStorage.get(_class.toString() + widgetID) == 0)
{
Log.e("buildUpdate -- WidgetUpdateService", "buildUpdate -- WidgetUpdateService: either not in collection or is 0: do full update");
manager.updateAppWidget(widgetID, views);
}
else
{
Log.e("buildUpdate -- WidgetUpdateService", "buildUpdate -- WidgetUpdateService: is not 0: do partial update");
manager.partiallyUpdateAppWidget(widgetID, views);
}
with the modified logic, when the view is needing for a refresh/update (which we cannot control most of the time like orientation change). it will not override the whole view and just the partial view.
Related
Creating an alarm notification and just cant figure out why i keep running into the error of
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
it is failing on(in the schedule course alarm() part.
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, nextAlarmId, intentAlarm, PendingIntent.FLAG_ONE_SHOT));
Part one
private boolean createTestAlarm() {
long now = DateUtil.todayLong();
if (now <= DateUtil.getDateTimestamp(course.start)) {
AlarmHandler.scheduleCourseAlarm(getApplicationContext(), courseId, DateUtil.getDateTimestamp(course.start),
"Course starts today!", course.name + " begins on " + course.start);
}
part two
public class AlarmHandler extends BroadcastReceiver {
public static final String courseAlarmFile = "courseAlarms";
public static final String assessmentAlarmFile = "assessmentAlarms";
public static final String alarmFile = "alarmFile";
public static final String nextAlarmField = "nextAlarmId";
#Override
public void onReceive(Context context, Intent intent) {
String destination = intent.getStringExtra("destination");
if (destination == null || destination.isEmpty()) {
destination = "";
}
int id = intent.getIntExtra("id", 0);
String alarmTitle = intent.getStringExtra("title");
String alarmText = intent.getStringExtra("text");
int nextAlarmId = intent.getIntExtra("nextAlarmId", getAndIncrementNextAlarmId(context));
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_calendar_clock)
.setContentTitle(alarmTitle)
.setContentText(alarmText);
Intent resultIntent;
Uri uri;
SharedPreferences sharedPreferences;
switch (destination) {
case "course":
Course course = DatabaseControl.getCourse(context, id);
if (course != null && course.notifications == 1) {
resultIntent = new Intent(context, CourseViewerActivity.class);
uri = Uri.parse(DatabaseData.COURSES_URI + "/" + id);
resultIntent.putExtra(DatabaseData.COURSE_CONTENT_TYPE, uri);
}
else {
return;
}
break;
case "assessment":
Assessment assessment = DatabaseControl.getAssessment(context, id);
if (assessment != null && assessment.notifications == 1) {
resultIntent = new Intent(context, AssessmentViewerActivity.class);
uri = Uri.parse(DatabaseData.ASSESSMENTS_URI + "/" + id);
resultIntent.putExtra(DatabaseData.ASSESSMENT_CONTENT_TYPE, uri);
}
else {
return;
}
break;
default:
resultIntent = new Intent(context, MainActivity.class);
break;
}
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent).setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(nextAlarmId, builder.build());
}
public static boolean scheduleCourseAlarm(Context context, long id, long time, String title, String text) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int nextAlarmId = getNextAlarmId(context);
Intent intentAlarm = new Intent(context, AlarmHandler.class);
intentAlarm.putExtra("id", id);
intentAlarm.putExtra("title", title);
intentAlarm.putExtra("text", text);
intentAlarm.putExtra("destination", "course");
intentAlarm.putExtra("nextAlarmId", nextAlarmId);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, nextAlarmId, intentAlarm, PendingIntent.FLAG_ONE_SHOT));
SharedPreferences sp = context.getSharedPreferences(courseAlarmFile, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(Long.toString(id), nextAlarmId);
editor.commit();
incrementNextAlarmId(context);
return true;
}
private static int getNextAlarmId(Context context) {
SharedPreferences alarmPrefs;
alarmPrefs = context.getSharedPreferences(alarmFile, Context.MODE_PRIVATE);
int nextAlarmId = alarmPrefs.getInt(nextAlarmField, 1);
return nextAlarmId;
}
private static void incrementNextAlarmId(Context context) {
SharedPreferences alarmPrefs;
alarmPrefs = context.getSharedPreferences(alarmFile, Context.MODE_PRIVATE);
int nextAlarmId = alarmPrefs.getInt(nextAlarmField, 1);
SharedPreferences.Editor alarmEditor = alarmPrefs.edit();
alarmEditor.putInt(nextAlarmField, nextAlarmId + 1);
alarmEditor.commit();
}
private static int getAndIncrementNextAlarmId(Context context) {
int nextAlarmId = getNextAlarmId(context);
incrementNextAlarmId(context);
return nextAlarmId;
}
}
part 3 -database code
public static Course getCourse(Context context, long courseId) {
Cursor cursor = context.getContentResolver().query(DatabaseData.COURSES_URI, Database.COURSES_COLUMNS,
Database.COURSES_TABLE_ID + " = " + courseId, null, null);
cursor.moveToFirst();
Long termId = cursor.getLong(cursor.getColumnIndex(Database.COURSE_TERM_ID));
String courseName = cursor.getString(cursor.getColumnIndex(Database.COURSE_NAME));
String courseDescription = cursor.getString(cursor.getColumnIndex(Database.COURSE_DESCRIPTION));
String courseStart = cursor.getString(cursor.getColumnIndex(Database.COURSE_START));
String courseEnd = cursor.getString(cursor.getColumnIndex(Database.COURSE_END));
String courseMentor = cursor.getString(cursor.getColumnIndex(Database.COURSE_MENTOR));
String courseMentorPhone = cursor.getString(cursor.getColumnIndex(Database.COURSE_MENTOR_PHONE));
String courseMentorEmail = cursor.getString(cursor.getColumnIndex(Database.COURSE_MENTOR_EMAIL));
String courseNote = cursor.getString(cursor.getColumnIndex(Database.COURSE_NOTE));
int courseNotifications = (cursor.getInt(cursor.getColumnIndex(Database.COURSE_NOTIFICATIONS)));
Course c = new Course();
c.courseId = courseId;
c.termId = termId;
c.name = courseName;
c.description = courseDescription;
c.start = courseStart;
c.end = courseEnd;
c.mentor = courseMentor;
c.mentorPhone = courseMentorPhone;
c.mentorEmail = courseMentorEmail;
c.note = courseNote;
c.notifications = courseNotifications;
return c;
}
Sure the error message says:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
So this means:
CursorIndexOutOfBoundsException think of a cursor as a collection, you are out of bounds
Index 0 requested You wanted to access at position 0 in the collection
with a size of 0 but the collections size is 0 (empty) therefore Out of Bounds.
If you are expecting your database schema to be correct you should not use getColumnIndex but use getColumnIndexOrThrow https://developer.android.com/reference/android/database/Cursor#getColumnIndexOrThrow(java.lang.String) that way you will fail fast and see which part of your data is incorrect.
But yeah basically your cursor is empty, check the query that you are doing. You can also breakpoint on a cursor, and to try alternative queries on teh content resolver.
You could also use a Tool like Stetho, to inspect your on device database to see if it has any data (and practice some queries)
http://facebook.github.io/stetho/
Or move away from cursors altogther and use opne of the newer recommended database access libraries like Room:
https://developer.android.com/topic/libraries/architecture/room
My assumption is that I just do not fully understand widgets yet. Hopefully one of you guru's can see where my logic/thinking is flawed.
Ultimately what happens with my widget is that it eventually becomes unresponsive at very random intervals (usually > 5 hours).
My investigation so far has led me to believe that it's potentially a result of the OS running low on memory and my widget being recreated?
If that's the case, I would have thought that the OnUpdate() method would handle this but potentially I'm wrong here.
I have read pretty much every thread on here regarding widget unresponsiveness. The only one that showed promise for me was this one:
Android Homescreen Widget becomes Unresponsive
but I'm not using a service and not sure I need to.
The goal of the widget is to first check if the user has created a profile. This is done by checking for the existence of a local db along with a user record. If neither of these exist, the widget should display a "Get Started" image (which it does successfully).
Once the user taps on this image, they are launched into a profile creation wizard. Once the profile is created, the widget is updated from the app to display an image along with some caloric intake information.
There are three clickable items on the widget. The image and the two textviews. Each respectively launching a different activity in my app.
Here is the widget class:
public class bbi_widget extends AppWidgetProvider {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
private static String week6Path = "";
public static RemoteViews getWidgetRemoteViews(Context context) {
Intent calorieCrushIntent = new Intent(context, calorie_crush.class);
Intent dashBoardIntent = new Intent(context, DashboardActivity.class);
PendingIntent calorieCrushPendingIntent = PendingIntent.getActivity(
context, 0, calorieCrushIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent dashboardPendingIntent = PendingIntent.getActivity(
context, 0, dashBoardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews appWidgetViews = new RemoteViews(context.getPackageName(),
R.layout.initial_widget_layout);
appWidgetViews.setOnClickPendingIntent(R.id.surp_def_widgettextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.calTextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, dashboardPendingIntent);
return appWidgetViews;
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
BBIDatabase db = new BBIDatabase(context);
db.openToRead();
boolean doesTableExist = db.doesTableExist(BBIDatabase.BBI_USER_TABLE);
db.close();
boolean doesUserExist = false;
if (doesTableExist){
db.openToRead();
doesUserExist = db.doesUserExist();
db.close();
}
if (!doesTableExist || !doesUserExist){
Intent getStartedIntent = new Intent(context, GettingStartedWizardActivity.class);
PendingIntent getStartedPendingIntent = PendingIntent.getActivity(
context, 0, getStartedIntent, PendingIntent.FLAG_UPDATE_CURRENT);
for (int index = 0; index < appWidgetIds.length; index++) {
int appWidgetId = appWidgetIds[index];
RemoteViews appWidgetViews = getWidgetRemoteViews(context);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, getStartedPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, appWidgetViews);
}
} else {
db.openToRead();
String curPath = db.GetSixWeekPath();
Bitmap sixWeekBmp = null;
if (week6Path != curPath && curPath != null && week6Path != null) {
week6Path = db.GetSixWeekPath();
sixWeekBmp = BitmapFactory.decodeFile(week6Path);
}
db.close();
db.openToRead();
int totalCalsToday = db.GetTodaysCalorieIntakeForWidget();
int bmrWithAct = db.GetBMRPlusActivity();
int additionalCalsCrushed = db.GetTodaysCaloriesBurnedForWidget();
int surp = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (surp < 0)
surp = 0;
int def = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (def > 0)
def = 0;
db.close();
for (int index = 0; index < appWidgetIds.length; index++) {
int appWidgetId = appWidgetIds[index];
RemoteViews appWidgetViews = getWidgetRemoteViews(context);
appWidgetViews.setViewVisibility(R.id.calTextView, View.VISIBLE);
appWidgetViews.setViewVisibility(R.id.surp_def_widgettextView, View.VISIBLE);
appWidgetViews.setTextViewText(R.id.calTextView, "Calorie intake: " + String.valueOf(totalCalsToday));
if (surp > 0) {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "SURPLUS " + String.valueOf(surp));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.surplus_ball_color));
} else {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "DEFICIT " + String.valueOf(def));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.calorie_crush_ball));
}
appWidgetViews.setImageViewBitmap(R.id.widget_after_picture, sixWeekBmp);
Intent calorieCrushIntent = new Intent(context, calorie_crush.class);
Intent dashBoardIntent = new Intent(context, DashboardActivity.class);
PendingIntent calorieCrushPendingIntent = PendingIntent.getActivity(
context, 0, calorieCrushIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent dashboardPendingIntent = PendingIntent.getActivity(
context, 0, dashBoardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
appWidgetViews.setOnClickPendingIntent(R.id.surp_def_widgettextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.calTextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, dashboardPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, appWidgetViews);
}
}
}
}
From my app, I do update these values in the widget using remoteViews.
Here is the helper class in my app:
public class WidgetHelper {
public static void UpdateCalorieIntake(int newValue, Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.initial_widget_layout);
ComponentName thisWidget = new ComponentName(context, bbi_widget.class);
remoteViews.setTextViewText(R.id.calTextView, "Calories in " + String.valueOf(newValue));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
public static void UpdateWidgetSurplus(int newValue, Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.initial_widget_layout);
ComponentName thisWidget = new ComponentName(context, bbi_widget.class);
if (newValue > 0) {
remoteViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric Surplus " + String.valueOf(newValue));
remoteViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.surplus_ball_color));
} else {
remoteViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric Deficit " + String.valueOf(newValue));
remoteViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.calorie_crush_ball));
}
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
private static String week6Path = "";
public static void UpdateAll(Context context) {
BBIDatabase db = new BBIDatabase(context);
db.openToRead();
String curPath = db.GetSixWeekPath();
Bitmap sixWeekBmp = null;
if (week6Path != curPath && curPath != null && week6Path != null) {
week6Path = db.GetSixWeekPath();
sixWeekBmp = BitmapFactory.decodeFile(week6Path);
}
db.close();
db.openToRead();
int totalCalsToday = db.GetTodaysCalorieIntakeForWidget();
int bmrWithAct = db.GetBMRPlusActivity();
int additionalCalsCrushed = db.GetTodaysCaloriesBurnedForWidget();
int surp = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (surp < 0)
surp = 0;
int def = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (def > 0)
def = 0;
db.close();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews appWidgetViews = new RemoteViews(context.getPackageName(), R.layout.initial_widget_layout);
ComponentName thisWidget = new ComponentName(context, bbi_widget.class);
appWidgetViews.setTextViewText(R.id.calTextView, "Calorie intake: " + String.valueOf(totalCalsToday));
if (surp > 0) {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric surplus " + String.valueOf(surp));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.surplus_ball_color));
} else {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric deficit " + String.valueOf(def));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.calorie_crush_ball));
}
appWidgetViews.setImageViewBitmap(R.id.widget_after_picture, sixWeekBmp);
Intent calorieCrushIntent = new Intent(context, calorie_crush.class);
Intent dashBoardIntent = new Intent(context, DashboardActivity.class);
PendingIntent calorieCrushPendingIntent = PendingIntent.getActivity(
context, 0, calorieCrushIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent dashboardPendingIntent = PendingIntent.getActivity(
context, 0, dashBoardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
appWidgetViews.setOnClickPendingIntent(R.id.surp_def_widgettextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.calTextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, dashboardPendingIntent);
appWidgetManager.updateAppWidget(thisWidget, appWidgetViews);
}
}
Provider infor:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dp"
android:minHeight="294dp"
android:previewImage="#drawable/bbi_icon"
android:initialLayout="#layout/initial_widget_layout"
>
</appwidget-provider>
I want to update widget item when I Add or Remove item using activity in my WelcomeWidget class onReceive() as
public void onReceive(Context context, Intent intent) {
setup(context);
if (datalist.size() != 0)
{
if (intent.getAction().equals(ACTION_NEXT_TIP)) {
mMessage = getNextMessageIndex();
SharedPreferences.Editor pref = context.getSharedPreferences(
PREFS_NAME, 0).edit();
pref.putInt(PREFS_TIP_NUMBER, mMessage);
pref.commit();
refresh();
}
else if (intent.getAction().equals(ACTION_SETTING))
{
Intent articleIntent = new Intent(context,
LoremActivity.class);
articleIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(articleIntent);
} else {
refresh();
} } }
where refresh method is as :
private void refresh() {
RemoteViews rv = buildUpdate(mContext);
for (int i : mWidgetIds) {
mWidgetManager.updateAppWidget(i, rv);
}
Using Animation as :
AnimationSet farsiTelLogoAnimation = new AnimationSet(true);
RotateAnimation rotate = new RotateAnimation(0, 360,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotate.setFillAfter(true);
rotate.setDuration(1000);
farsiTelLogoAnimation.addAnimation(rotate);
}
getting message index
private int getNextMessageIndex() {
return (mMessage + 1) % datalist.size();
}
where buildUpdate () method is as
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews =
new RemoteViews(context.getPackageName(), R.layout.widget);
// Action for tap on bubble
Intent bcast = new Intent(context,
WelcomeWidget.class);
bcast.setAction(ACTION_NEXT_TIP);
PendingIntent pending = PendingIntent.getBroadcast(context,
0, bcast, PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.widget, pending);
// RemoteViews updateViews1 = new
RemoteViews(context.getPackageName(), // R.id.setting);
Intent bcast1 = new Intent(context, WelcomeWidget.class);
bcast1.setAction(ACTION_SETTING); PendingIntent pending1 =
PendingIntent.getBroadcast(context,
0, bcast1, PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.
setOnClickPendingIntent(R.id.setting, pending1);
// Tip bubble text if (mMessage >= 0) { // String[] parts =
sNewlineRegex.split(mTips[mMessage], 2);
String to = datalist.get(mMessage).getFrom();
String from = datalist.get(mMessage).getTo();
String rate = datalist.get(mMessage).getRate();
// Look for a callout graphic referenced in the text Matcher m =
sDrawableRegex.matcher(to);
if (m.find()) {
String imageName = m.group(1);
int resId = context.getResources().getIdentifier(
imageName, null, context.getPackageName());
// updateViews.setImageViewResource(R.id.tip_callout, resId);
// updateViews.setViewVisibility(R.id.tip_callout,
// View.VISIBLE);
to = m.replaceFirst(""); } else {
// updateViews.setImageViewResource(R.id.tip_callout, 0);0
// updateViews.setViewVisibility(R.id.tip_callout, View.GONE); }
updateViews.setTextViewText(R.id.to, to);
updateViews.setTextViewText(R.id.from, from);
updateViews.setTextViewText(R.id.rate, rate);
updateViews.setTextViewText(
R.id.tip_footer,
context.getResources().getString(R.string.pager_footer,
(1 + mMessage), datalist.size()));
updateViews.setViewVisibility(R.id.tip_bubble, View.VISIBLE);
}
else {
updateViews.setViewVisibility(R.id.tip_bubble, View.INVISIBLE);
}
return updateViews;
}
where Button click event reload widget
I don't really understand your code because the format is horrible.
Anyway, to update a widget from your activity you can send a Broadcast intent with APPWIDGET_UPDATE. Use the following code:
Intent intent = new Intent(YourActivity.this, YourWidgetProvider.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids[] = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), ASquareAnalogClockProvider.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);
Hope it helps :)
I am using DownloadManager to download the following url:
http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
But the downloading is failed. I even hit the url on browser and it works properly. Is it the problem of url parsing?
Code: DDownloadService.java
public class DDownloadService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
Context conte;
// NotificationManager notificationManager;
// NotificationCompat.Builder mBuilder;
boolean playing = false;
Runnable runnable;
SharedPreferences pre;
static int countOfCurrent = 0;
String downloadName, downloadUrl;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
// ..
static int downloadNumber = 0;
DownloadManager mgr[] = new DownloadManager[100];
long downloadIds[] = new long[100];
BroadcastReceiver cancelDownload;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
downloadNumber++;
downloadName = pre.getString("downloadname", "");
downloadName = viewSD(downloadName);
downloadUrl = pre.getString("downloadurl", "");
downloadName = downloadName.toLowerCase();
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "") + "|"
+ downloadName).commit();
pre.edit().putInt(downloadName + "no", +downloadNumber).commit();
mgr[downloadNumber] = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
try {
countOfCurrent++;
downloadIds[downloadNumber] = mgr[downloadNumber]
.enqueue(new DownloadManager.Request(Uri
.parse(downloadUrl))
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Downloading")
.setDescription(downloadName)
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_HIDDEN)
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_MUSIC,
downloadName)
.setVisibleInDownloadsUi(false));
pre.edit()
.putLong(downloadName + "id",
downloadIds[downloadNumber]).commit();
Timer myTimer = new Timer();
myTimer.schedule(new RegrowCornAnimate(downloadNumber,
downloadName), 0, 10);
} catch (IllegalStateException e) {
Toast.makeText(getBaseContext(), "No storage found!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(getBaseContext(), " Something wrong happened!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
conte = this;
pre = getSharedPreferences("download", 0);
downloadName = pre.getString("downloadname", "");
downloadUrl = pre.getString("downloadurl", "");
cancelDownload = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
try {
mgr[pre.getInt(arg1.getExtras().getString("name") + "no", 0)]
.remove(pre.getLong(
arg1.getExtras().getString("name") + "id",
0));
} catch (Exception e) {
e.printStackTrace();
}
}
};
registerReceiver(cancelDownload, new IntentFilter("cancelIt"));
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Downloading in progress").setContentText("");
startForeground(55, mBuilder.build());
notificationManager.cancel(55);
HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);
// //..................
// notificationManager = (NotificationManager) conte
// .getSystemService(Context.NOTIFICATION_SERVICE);
// mBuilder = new NotificationCompat.Builder(conte);
// RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.notification_layout);
// try {
// mBuilder.setSmallIcon(R.drawable.icon);
// mBuilder.setAutoCancel(false).setOngoing(true)
// .setContent(remoteViews);
// Uri uri = RingtoneManager
// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mBuilder.setSound(uri);
// notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
// mBuilder.build());
// } catch (Exception e) {
// e.printStackTrace();
// }
// //...................
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// online = intent.getExtras().getString("online");
// link = intent.getExtras().getString("link");
// name = intent.getExtras().getString("name");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(cancelDownload);
}
class RegrowCornAnimate extends TimerTask {
private final int serial;
private final String name_of_da;
boolean startFlag = true, errorFlag = true;
RegrowCornAnimate(int serial, String name) {
this.serial = serial;
this.name_of_da = name;
}
public void run() {
// Do stuff
int dl_progress = 0;
try {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadIds[serial]);
Cursor c = mgr[serial].query(q);
c.moveToFirst();
long bytes_downloaded = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
long bytes_total = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
dl_progress = (int) ((bytes_downloaded * 100) / bytes_total);
pre.edit().putInt(name_of_da, dl_progress).commit();
switch (c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
// msg = "Download failed!";
// Toast.makeText(getBaseContext(), "Url Broken!",
// Toast.LENGTH_SHORT).show();
sendNotification(1, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
case DownloadManager.STATUS_PAUSED:
// msg = "Download paused!";
if (errorFlag) {
errorFlag = false;
sendNotification(7, serial, name_of_da, dl_progress);
}
break;
case DownloadManager.STATUS_PENDING:
// msg = "Download pending!";
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_RUNNING:
// msg = "Download in progress!";
errorFlag = true;
if (startFlag) {
if (verifyFromSD(name_of_da)) {
startFlag = false;
sendBroadcast(new Intent("start"));
}
}
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_SUCCESSFUL:
// msg = "Download complete!";
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "")
.replace("|" + name_of_da, ""))
.commit();
pre.edit().putInt(name_of_da, 100);
sendNotification(0, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
default:
// msg = "Download is nowhere in sight";
sendNotification(10, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
}
c.close();
} catch (Exception e) {
e.printStackTrace();
sendNotification(7, serial, name_of_da, dl_progress);
cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
}
}
}
public void sendNotification(int tmout, int nin, String name, int progress) {
if (tmout == 0) {
// notificationManager.notify(nin, mBuilder.build());
if (progress >= 100) {
// notificationManager.cancel(nin);
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Completed").setContentText(name)
.setAutoCancel(true).setOngoing(false)
.setProgress(100, 100, false);
Uri ttt = Uri.parse(Environment.getExternalStorageDirectory()
.toString() + "/Music/" + name);
pre.edit().putInt("retry", 1).commit();
Intent inten = new Intent(Intent.ACTION_VIEW, ttt);
String arr[] = name.split("\\.");
inten.setDataAndType(ttt, "audio/" + arr[arr.length - 1]);
PendingIntent i = PendingIntent.getActivity(getBaseContext(),
0, inten, 0);
mBuilder.setContentIntent(i);
notificationManager.notify(nin, mBuilder.build());
} else {
mBuilder.setContentTitle("Downloading: " + name)
.setContentText(progress + " %")
.setSmallIcon(R.drawable.icon).setAutoCancel(false)
.setOngoing(true);
mBuilder.setProgress(100, progress, false);
notificationManager.notify(nin, mBuilder.build());
}
} else {
if (tmout == 1) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Failed: " + name)
.setContentText(progress + " %").setAutoCancel(true)
.setProgress(100, progress, false).setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else if (tmout == 7) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Cancelled: " + name)
.setAutoCancel(true).setProgress(100, progress, false)
.setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Interrupted: " + name)
.setContentText("No storage found").setAutoCancel(true)
.setOngoing(false);
}
notificationManager.notify(nin, mBuilder.build());
}
}
private String viewSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return naame;
}
while (true) {
String newName = naame;
naame = relooper(files, newName);
if (newName.equals(naame))
break;
}
return naame;
}
public String relooper(File[] files, String name) {
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (name.equalsIgnoreCase(myfile))
return "copy_of_" + name;
}
return name;
}
private boolean verifyFromSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return false;
}
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (naame.equalsIgnoreCase(myfile))
return true;
}
return false;
}
}
EDIT: I found the problem from logcat:
01-07 11:47:37.313: W/DownloadManager(18893): Exception for id 285: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): java.lang.IllegalArgumentException: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): at java.net.URI.create(URI.java:727)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getProxy(Proxy.java:113)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getPreferredHttpHost(Proxy.java:218)
01-07 11:47:37.313: W/DownloadManager(18893): at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:174)
But I still need to know which format to use to parse url for DownloadManager.
The IllegalArgumentException occurs when the URL contains illegal characters such as [ ]. As mentioned in the comments, you need to encode such characters using URLEncoder.
I implemented it this way in my code -
private String checkUrl(String url) {
if(url.contains("[")) {
String[] a = url.split("\\[");
String b = "[" + a[1]; //contains text after [ e.g. [DJKANG.Com].mp3
url = a[0] + URLEncoder.encode(b, "UTF-8"); // encodes illegal characters
}
return url;
}
I am allowing the user to change the icon in the class Personalize by sending a request code holding an image from a user gallery.
The setIconImageinWidget() method sends the result here (in Drag_and_Drop_App):
else if(requestCode == RESULT_ICON){
byte[] byteArray = data.getByteArrayExtra("myIconBitmap");
Bitmap myIcon = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
setBackgroundImageForIcon(myIcon);
Log.d("Drag_and_Drop_App", "Icon is set");
}
}
Here is the setBackgroundImageForIcon method:
#SuppressLint("NewApi")
private void setBackgroundImageForIcon(Bitmap bitmap) {
ImageView ivICON = (ImageView) findViewById(R.id.bwidgetOpen);
Drawable dq = new BitmapDrawable(getResources(), bitmap);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
ivICON.setImageDrawable(dq);
} else {
ivICON.setImageDrawable(dq);
Log.d("Drag_and_Drop_App", "Icon is set");
}
}
This returns no errors but the icon is not changed at all based on whatever picture the user chooses to use.
After looking around a while I realized that I would have to change the app widget provider section of my coding here:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class AFBWidget extends AppWidgetProvider{
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
Random r = new Random();
int randomInt = r.nextInt(1000000000);
String rand = String.valueOf(randomInt);
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++){
int awID = appWidgetIds[i];
RemoteViews v = new RemoteViews(context.getPackageName(), R.layout.widget);
v.setTextViewText(R.id.tvwidgetUpdate, rand);
Intent configIntent = new Intent(context, Drag_and_Drop_App.class);
PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);
v.setOnClickPendingIntent(R.id.bwidgetOpen, configPendingIntent);
//me trying to set the Bitmap from the above classes somehow... v.setImageViewBitmap(R.id.bwidgetOpen, R.id.);
appWidgetManager.updateAppWidget(awID, v);
}
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onDeleted(context, appWidgetIds);
Toast.makeText(context, "Thanks for checking us out!", Toast.LENGTH_SHORT).show();
}
}
And the imageView I am changing is this:
<ImageView
android:id="#+id/bwidgetOpen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:contentDescription="#string/desc"/>
in Widget.xml
How can I change my Widget Provider so that it will allow the changing of the icon?
I know this is a lot to read but any help is apperciated!
UPDATED:
#SuppressLint("NewApi")
private void setBackgroundImageForIcon(Bitmap bitmap) {
Log.d("Drag_and_Drop_App", "Icon...");
ImageView ivICON = (ImageView) findViewById(R.id.bwidgetOpen);
BitmapDrawable dq = new BitmapDrawable(getResources(), bitmap);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
// ivICON.setImageDrawable(dq);
ivICON.setImageResource(R.drawable.pattern1);
} else {
// ivICON.setImageDrawable(dq);
ivICON.setImageResource(R.drawable.pattern1);
Log.d("Drag_and_Drop_App", "Icon is set");
}
}