Android set widget background - android

In my drawable-hdpi folder i have 4 image files (.png) to serve as the background of awidget. By default android:background="#drawable/goldgreenbg" is set for the LinearLayout. I created a preferences screen to let the user change the background.
How to do that? I would like to use this code for it:
if (listpref.equals("color1"))
{
Toast.makeText(EditPreferences.this, "Black" + listpref, Toast.LENGTH_LONG).show();
}
else if (listpref.equals("color2"))
{
Toast.makeText(EditPreferences.this, "Brown" + listpref, Toast.LENGTH_LONG).show();
}
Update:
Where shall i put this code to?
MainActivity.java: for the activity
UpdateService.java: for the widget
EditPreferences.java: for the preferences
Main.xml includes the listview and widgetlayout is id of it.
setContentView(R.layout.main);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
String listpref = preferences.getString("listPref", "n/a");
LinearLayout ll = (LinearLayout) findViewById(R.id.widgetlayout);
if (listpref.equals("color1"))
{
Toast.makeText(MainActivity.this, "Black" + listpref, Toast.LENGTH_LONG).show();
ll.setBackgroundDrawable(getResources().getDrawable(R.drawable.blackbg));
}
else if (listpref.equals("color2"))
{
Toast.makeText(MainActivity.this, "Brown" + listpref, Toast.LENGTH_LONG).show();
ll.setBackgroundDrawable(getResources().getDrawable(R.drawable.brownbg));
}

Assuming you allready have the LinearLayout on your screen (using setContentView), you can change the background quite easily like so:
yourLinearLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.blackbg));
(and get that layout using findViewById() ofcourse )

I found the solution.
EditPreferences.java:
final Preference listpref = getPreferenceScreen().findPreference("listPref");
listpref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference p, Object newValue)
{
String color = (String) newValue;
if (color.equals("color1"))
{
RemoteViews updateViews = new RemoteViews(EditPreferences.this.getPackageName(), R.layout.main);
updateViews.setTextColor(R.id.widget_textview, Color.rgb(208, 202, 202));
updateViews.setTextColor(R.id.widget_textview2, Color.WHITE);
updateViews.setTextColor(R.id.widget_textview3, Color.rgb(176, 175, 175));
// updateViews.setImageViewBitmap(R.id.ImageView01, ((BitmapDrawable)EditPreferences.this.getResources().getDrawable(R.drawable.forestbg)).getBitmap());
updateViews.setImageViewResource(R.id.ImageView01, R.drawable.blacktrans);
ComponentName thisWidget = new ComponentName(EditPreferences.this, HelloWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(EditPreferences.this);
manager.updateAppWidget(thisWidget, updateViews);
}
else if (color.equals("color2"))
{
RemoteViews updateViews = new RemoteViews(EditPreferences.this.getPackageName(), R.layout.main);
updateViews.setTextColor(R.id.widget_textview, Color.rgb(23, 81, 11));
updateViews.setTextColor(R.id.widget_textview2, Color.rgb(232, 232, 107));
updateViews.setTextColor(R.id.widget_textview3, Color.rgb(23, 81, 11));
updateViews.setImageViewBitmap(R.id.ImageView01, ((BitmapDrawable)EditPreferences.this.getResources().getDrawable(R.drawable.goldgreenbg)).getBitmap());
// updateViews.setImageViewResource(R.id.ImageView01, R.drawable.goldgreenbgf);
ComponentName thisWidget = new ComponentName(EditPreferences.this, HelloWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(EditPreferences.this);
manager.updateAppWidget(thisWidget, updateViews);
}
return true;
}
});
public void onStart(Intent intent, int startId) {
getPrefs();
}
private void getPrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ListPreference = prefs.getString("listPref", "nr1");
}
This way it is working perfectly.

Related

Receiving more shared preferences than should exist when creating new widget

I am constructing widgets which give you the best currency rate for the values you choose. On the homePage, when I click on widgets and select the widget I want to create, the WidgetConfigure Application should launch.
However, it crashes before the configure page even launches and I get this error:
java.lang.RuntimeException:java.lang.IndexOutOfBoundsException: Index: 2, Size: 2. This is the code it refers to:
// Set the currencies for each object
for(String currency: preferredCurrencies){
currencyObjects.get(currencyCount).setCurrencyType(currency);
currencyCount+=1;
}
The code is in one of my widget methods responsible for updating it.
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetId, List<CurrencyObject> currencyObjects, Intent clickIntent) {
theAppWidgetManager = appWidgetManager;
// There may be multiple widgets active, so update all of them
// Get the preferred Currencies
Set<String> preferredCurrencies = AppWidgetConfigure.loadCurrencyPref(context,appWidgetId);
// Inflate the layout
RemoteViews view = new RemoteViews(context.getPackageName(), layout);
// if the preferred Currencies have been declared already
if(preferredCurrencies!= null){
// Set the currencies for each object
*for(String currency: preferredCurrencies){
currencyObjects.get(currencyCount).setCurrencyType(currency);
currencyCount+=1;
}*
}
else{
for(CurrencyObject curObj:currencyObjects){
curObj.setCurrencyType("EUR");
}
}
currencyCount = 0;
}
In my widget configure class I have these methods, where I set the preferredCurrencies:
private static final String PREFS_NAME = "change.Widgets";
private static final String PREF_PREFIX_KEY = "appwidget_";
int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
private List<String> currencies = new ArrayList<>();
private int checkCounter;
private Set<String> chosenCurrencies = new TreeSet<>();
static void saveCurrencyPref(Context context, int appWidgetId, Set<String> chosenCurrencies) {
SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
prefs.putStringSet(PREF_PREFIX_KEY + appWidgetId, chosenCurrencies);
prefs.apply();
}
static void deleteCurrencyPref(Context context, int appWidgetId) {
SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
prefs.remove(PREF_PREFIX_KEY + appWidgetId);
prefs.apply();
}
public static Set<String> loadCurrencyPref(Context context, int appWidgetId) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
Set chosenCurrencies = prefs.getStringSet(PREF_PREFIX_KEY + appWidgetId, null);
return chosenCurrencies;
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If this activity was started with an intent without an app widget ID, finish with an error.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
return;
}
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if the user presses the back button.
setResult(RESULT_CANCELED);
// Create the layout with the checkboxes and the Button.
setContentView(R.layout.widget_configure);
LinearLayout ll = (LinearLayout) findViewById(R.id.configure_layout);
TextView txt = new TextView(this);
txt.setText("Must have: " + Integer.toString(checkBoxLimit) + " checkboxes");
ll.addView(txt);
// Create the checkboxes
currencies.addAll(Arrays.asList(getResources().getStringArray(R.array.currency_array)));
for(String item:currencies){
CheckBox ch = new CheckBox(this);
ch.setText(item);
ll.addView(ch);
ch.setOnCheckedChangeListener((cb, isChecked)->{
//If it's checked and more than the allowed limit, don't consider it
if(isChecked){
if(checkCounter>=checkBoxLimit){
cb.setChecked(false);
Toast.makeText(this, txt.getText(), Toast.LENGTH_SHORT).show();
}
// If it's within the allowed limit, add to list of chosenCurrencies.
else{
checkCounter+=1;
chosenCurrencies.add(cb.getText().toString());
}
}
// If its, unchecked remove the currency from the list of chosenCurrencies.
else{
checkCounter-=1;
chosenCurrencies.remove(cb.getText().toString());
}
});
}
// Create the button
Button btn = new Button(this);
btn.setText(R.string.apply);
ll.addView(btn);
// Finish this
//Launch the widget once the button is pressed
btn.setOnClickListener(v->{
//If User selects right amount of checkboxes
if(checkBoxLimit == checkCounter){
final Context context = AppWidgetConfigure.this;
// delete the previous currencies that existed there for that widget Id
deleteCurrencyPref(context, mAppWidgetId);
// Save the preferences
saveCurrencyPref(context, mAppWidgetId, chosenCurrencies);
// It is the responsibility of the configuration activity to update the app widget
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] oneIdList = new int[1];
oneIdList[0] = mAppWidgetId;
//Update the current type of widget
widget.onUpdate(context, appWidgetManager, oneIdList);
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
else{
Toast.makeText(this, txt.getText(), Toast.LENGTH_SHORT).show();
}
});
}
// Set the currencies for each object
for (String currency : preferredCurrencies) {
if (currencyCount >= currencyObjects.size()) {
return
}
currencyObjects.get(currencyCount).setCurrencyType(currency);
currencyCount++;
}
your app crash because you want to get a invalid item of list. ex your list have 2 items but you call list.get(2)

Android Widget Works in Lollipop, but NOT in KitKat

I have a clock widget that updates every minute. It renders a bitmap and replaces an imageview. This is to use a custom font in a widget. Below I showed the important pieces of my code. My problem is that the widget is there, but nothing shows up. I can still tap the widget to bring up the settings, so I know it's there. It's like the service update isn't working correctly in Kitkat but it does in Lollipop. Any suggestions?
public class DigitalClockWidget_2x1 extends AppWidgetProvider {
public RemoteViews mRemoteViews;
static String APP_SETTINGS = "8BitSettings";
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.startService(new Intent(UpdateTimeService.UPDATE_TIME));
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent LaunchIntent = getLaunchIntent(context);
PendingIntent clickPendIntent = PendingIntent.getActivity(context, 0, LaunchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mRemoteViews.setOnClickPendingIntent(R.id.widget_root, clickPendIntent);
ComponentName componentName = new ComponentName(context.getPackageName(),DigitalClockWidget_2x1.class.getName());
appWidgetManager.updateAppWidget(componentName, mRemoteViews);
context.startService(new Intent(UpdateTimeService.UPDATE_TIME));
}
public static Intent getLaunchIntent(Context context){
SharedPreferences clockSettings = context.getSharedPreferences("ClockSettings", 0);
String launchString = clockSettings.getString("tappedAction", APP_SETTINGS);
if(launchString.compareTo(APP_SETTINGS) == 0){
return new Intent(context, SettingsPage.class);
}
return context.getPackageManager().getLaunchIntentForPackage(launchString);
}
public static final class UpdateTimeService extends Service {
static final String UPDATE_TIME = "org.penguinproductions.eight_bit_clock.action.UPDATE_TIME_2x1";
RemoteViews mRemoteViews;
private Calendar mCalendar;
private final static IntentFilter mIntentFilter = new IntentFilter();
int textColor = 0;
boolean tweentyfourHour = false;
SharedPreferences clockSettings;
String APP_SETTINGS = "8BitSettings";
static {
mIntentFilter.addAction(Intent.ACTION_TIME_TICK);
mIntentFilter.addAction(Intent.ACTION_TIME_CHANGED);
mIntentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
}
#Override
public void onCreate() {
super.onCreate();
mCalendar = Calendar.getInstance();
registerReceiver(mTimeChangedReceiver, mIntentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mTimeChangedReceiver);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent != null) {
if (UPDATE_TIME.equals(intent.getAction())) {
updateTime();
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private final BroadcastReceiver mTimeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateTime();
}
};
private void updateTime() {
mCalendar.setTimeInMillis(System.currentTimeMillis());
mRemoteViews = new RemoteViews(getPackageName(), R.layout.widget);
String date = DateFormat.format(getString(R.string.date_format), mCalendar).toString();
mRemoteViews.setImageViewBitmap(R.id.imageView_txt, buildUpdate(getTodaysTime(), mCalendar.get(Calendar.AM_PM), date));
ComponentName mComponentName = new ComponentName(this, DigitalClockWidget_2x1.class);
AppWidgetManager mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetManager.updateAppWidget(mComponentName, mRemoteViews);
Intent LaunchIntent = getLaunchIntent(getBaseContext());
PendingIntent clickPendIntent = PendingIntent.getActivity(getBaseContext(), 0, LaunchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mRemoteViews.setOnClickPendingIntent(R.id.widget_root, clickPendIntent);
mAppWidgetManager = AppWidgetManager.getInstance(getBaseContext());
mAppWidgetManager.updateAppWidget(mComponentName, mRemoteViews);
}
}
EDIT:
The issue seems to have to do with the Bitmap rendering. I replaced the imageview with a textview and it worked. So the Bitmap isn't displaying in KitKat, but it does in Lollipop
public Bitmap buildUpdate(String time, int AMPM, String date) {
Log.v("Penguin", "Building time string:" + time);
clockSettings = this.getSharedPreferences("ClockSettings", 0);
boolean showDate = clockSettings.getBoolean("showDate", true);
boolean showampm = clockSettings.getBoolean("ampm", true);
boolean leading0 = clockSettings.getBoolean("leading0", true);
textColor = clockSettings.getInt("clockColor", Color.WHITE);
int dateColor = clockSettings.getInt("dateColor", Color.WHITE);
Bitmap myBitmap = Bitmap.createBitmap(2500, 1100, Bitmap.Config.ARGB_8888);
int fontSize = 425;
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Typeface clock = Typeface.createFromAsset(this.getAssets(), "fonts/PressStart2P.ttf");
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(clock);
paint.setStyle(Paint.Style.FILL);
paint.setColor(textColor);
paint.setTextSize(fontSize);
paint.setTextAlign(Paint.Align.CENTER);
myCanvas.drawText(time, myBitmap.getWidth() / 2, fontSize+200, paint);
paint.setTextSize(100);
if(showampm) {
// alert("AMPM");
String ampm = "AM";
if (AMPM == 1) ampm = "PM";
myCanvas.drawText(ampm, (myBitmap.getWidth() / 2) + ((time.length() * fontSize) / 2) + 100, 300, paint);
}
paint.setTextSize(125);
if(showDate) {
paint.setColor(dateColor);
myCanvas.drawText(date, myBitmap.getWidth() / 2, (myBitmap.getHeight() / 2 + 400), paint);
}
return myBitmap;
}
So the issue was that the size limit for my older phone running KitKat only allows for texture sizes no bigger than 2048x2048 pixels. My bitmap was 2500x1100, so scaling it down has fixed the issue

Android widget becomes unresponsive after random amounts of time pass

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>

android widget update text using activity

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 :)

Allowing icon to change from user input

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");
}
}

Categories

Resources