Android get textView value inside widget - android

Is there a way to get value from textView item inside widget ? I have a 2 textViews in my widget layout and on my widget update I want to set new value to one of them and I don't want to change value of the second one. For now when I set value like this
remoteViews.setTextViewText(R.id.text1, newValue");
widgetManager.updateAppWidget(thisWidget, remoteViews);
this is setting value of the second textView to default value defined in layout.
How to get it to not change the value of the second textView, or how to get value to the second textView to be able to adjust to the same ?

It is my understanding that whenever onUpdate is called, it updates all of the widgets, so what I do is use SharedPreferences, so when I set the TextView initially I save the textView text to sharedprefs and then I get the preference when I update. And I do this all within a for loop.
Here is my onUpdate:
#Override
public void onUpdate(Context context, AppWidgetManager awm, int[] appWidgetIds){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
int appWidgetId;
for (int i=0;i<appWidgetIds.length;i++){
appWidgetId = appWidgetIds[i];
String widgetLabel = pref.getString("label"+appWidgetId, "");
// I previously saved "widgetLabel" when I created the widget in my
// ConfigurationActivity
M.updateWidget(context, appWidgetId, widgetLabel);
// I put this in another class so it's more manageable.
}
}
in my Class M:
public static void updateWidget(Context context, int appWidgetId, String widgetLabel){
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
RemoteViews updateViews;
int layoutId = R.layout.layout;
int viewId = R.id.layout;
updateViews = new RemoteViews(context.getPackageName(),
layoutId);
updateViews.setTextViewText(R.id.widgetlabel, widgetLabel);
editor.putString("label"+appWidgetId, widgetLabel);
editor.commit();
Intent intent = new Intent(context, ClickAction.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(viewId, pendingIntent);
AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, updateViews);
}
I hope that makes sense. Let me know if I need to elaborate on anything.

Related

Update a widget when clicked, if user created multiple widgets

My app is an Android widget. It adds a button on home Screen; if a user clicked in this Button it will open a window. This window is waiting an user input. It has to write a value and this value will change the text in the Button.
The problem is if the user creates many widgets and clicked on the Button in any widget and write a value the value will be set only on the last created widget.
How can I make the Button change text on his widget?
And this is my code
public class Widget_note extends AppWidgetProvider {
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
the_context = context ;
the_appWidgetManager = appWidgetManager ;
the_appWidgetIds = appWidgetIds ;
Intent open_activity087 = new Intent();
open_activity087.setClassName("syr.hamza.app.mynotes_v2", "syr.hamza.app.mynotes_v2.SetWidgetValue");
open_activity087.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(open_activity087);
/*this will be open activity Immediately after creating widget to enter a value
* and will calling a set_value_in_widget() Function (at Below) with the value
* and this don't have any problem*/
Intent intent2 = new Intent(context, EditWidgetValue.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent2, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds,views);
/* this will be open activity if clicked on the button and get the value from user
* and calling set_value_in_widget() Function
* here is a problem */
}
public static Context the_context ;
public static AppWidgetManager the_appWidgetManager ;
public static int[] the_appWidgetIds ;
public static void set_value_in_widget(String value) {
RemoteViews views2 = new RemoteViews(the_context.getPackageName(), R.layout.widget_layout);
views2.setTextViewText( R.id.widget_button , value ) ;
the_appWidgetManager.updateAppWidget(the_appWidgetIds, views2 );
}
}
Keep all ids after a widget instance creating into SharedPreferences and on the OnUpdate read it from preferences and use instead the_appWidgetIds. Also you will need to remove them from preferences on onDelete.

How to save the configuration of widgets

I am busy following this android tutorial on widgets.
In particular the part where you set-up a ConfigurationActivty.
Here are their steps:
First, get the App Widget ID from the Intent that launched the Activity
Perform your App Widget configuration.
When the configuration is complete, get an instance of the AppWidgetManager by calling AppWidgetManager.getInstance()
Update the App Widget with a RemoteViews layout by calling updateAppWidget(int, RemoteViews)
Finally, create the return Intent, set it with the Activity result, and finish the Activity
I need help with 2: from what I have goggled people are using the SharedPrefs, But how do I actually access my XML which gives info about the widget, such as update frequency:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="#layout/widget_layout"
android:minHeight="200dp"
android:minWidth="144dp"
android:widgetCategory="home_screen"
android:configure="widget.AppWidgetConfigureActivity"
android:updatePeriodMillis="1800000" >
</appwidget-provider>
{Edit:} Ok i have implemented this so far:
private void SaveWidgetConfiguration() {
int deviceTypeId = 0;
int deviceId = 0;
String hashedPasscode = "";
int updateFreq = 30000;
SharedPreferences prefs = AppWidgetConfigureActivity.this.getSharedPreferences("prefs", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("Widget_DeviceTypeId:" + appWidgetId, deviceTypeId);
edit.putLong("Widget_DeviceId:" + appWidgetId, deviceId);
edit.putString("Widget_Passcode:" + appWidgetId, hashedPasscode);
edit.putInt("Widget_UpdateFreq:" + appWidgetId, updateFreq);
edit.commit();
}
But now where and how do I get these preferences?
I am using a service to update my widget. Do I get them in MyWidgetProvider?
My Current MyWidgetProvider:
public class MyWidgetProvider extends AppWidgetProvider {
private static final String LOG = "de.vogella.android.widget.example";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.w(LOG, "onUpdate method called");
// Get all ids
ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
// Get Preferences:
// Build the intent to call the service
Intent intent = new Intent(context.getApplicationContext(), UpdateWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
// Update the widgets via the service
context.startService(intent);
}
App Widget configuration Activity is an optional Activity that launches when the user adds your App Widget and allows him or her to modify App Widget settings at create-time. In the configuration Activity you can set up update frequency, text in TextView, background drawable of the widget and so on ... It means that you are setting up the widget before it is created and visible. You can save all the settings in SharedPreferences and if you need to update or recreate the widget (after reboot or configuration change) you can get saved settings from SharedPreferences either in onUpdate method of your AppWidgetProvider or in your service UpdateWidgetService.java. Since you use UpdateWidgetService for update your widgets you should use SharedPreferences in this service.
Here is an example:
Context context = getApplicationContext();
SharedPreferences prefs = context.getSharedPreferences("prefs", 0);
int deviceTypeId = prefs.getInt("Widget_DeviceTypeId:" + appWidgetId, defValue); // defValue is used if the preference doesn't exist
// get all other preferences/settings and use them to update the widget
If you need more details please ask.
You don't need to access appwidget_info.xml since it's shared by all widgets and you've declared it's usage at the Manifest. It will be automatically picked up by WidgetProvider. Perform your App Widget configuration. stage can be used for picking up some setting from SharedPrefences, which can be used for creating view later.

Widget update via remoteview Android

I want my activity "but1" to update the text on my widget button through button in my but1 activity. I've tried and it shows no error but still the widget doesn't updates. Is it something Im missing in manifest file?Moreover the log cat also doesnt show any problem
following is my code in But1.class
et1.setOnClickListener(new OnClickListener() {
Intent in=new Intent();
Bundle extras=in.getExtras();
if(extras!=null)
{
awID=extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
}
aw=AppWidgetManager.getInstance(context);
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
RemoteViews rv=new RemoteViews(context.getPackageName(),R.layout.activity_main);
rv.setTextViewText(R.id.button1, "Mughazf,f,jvnl");
aw.updateAppWidget(awID, rv);
Intent result=new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK,r
esult);
and my widget is:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, But1.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
views.setOnClickPendingIntent(R.id.button2, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
Problem should be with the Widget App ID . You need to keep remembering the Widget ID to update it later.
Your Widget Provider onUpdate() method should store the Widget id in shared preference or database
I am using shared preference here,
SharedPreferences prefs = context.getSharedPreferences("private preference", Context.MODE_PRIVATE);
// here i am saving one widget id. change your logic to store all the widget id's
prefs.edit().putInt("WidgetId",appWidgetId).commit();
Then when the Activity is launched and button clicked. You can update the widget layout like this
First Read the Widget ID from shared Preference
SharedPreferences prefs = getSharedPreferences("private preference", Context.MODE_PRIVATE);
int awID = prefs.getInt("WidgetId", AppWidgetManager.INVALID_APPWIDGET_ID);
Then, create the instance of RemoteView and set the new text to the TextView
RemoteViews rv=new RemoteViews(getPackageName(),R.layout.widget_layout);
rv.setTextViewText(R.id.textView1, "Some one updated Me");
Then , get the instance of AppWidget Manager
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
And, Finally update the Widget with new RemoteView Layout.
appWidgetManager.updateAppWidget(awID, rv);
So, awID - is the Widget Id what we got from onUpdate method.
This should work. Let me know if you see any issue.

Change src image of ImageButton of Android widget programatically

I am developing an Android app with a homescreen widget, which is an imageButton, and i want the image of the button to change after its been pressed. I have tried selector in an xml file, to change the image of the button, but it changes it only when it is pressed, but it goes back when its released.
I want it to change image after it was pressed and when the code inside the WidgetProvider is executed, it changes the image back to the default one.
I tried to do it programatically(in onRecieve() method), I guess it should be something with RemoteViews but whatever i try, it doesnt work.
Could someone help my with this? I saw many people asking about it, but most of the posts were either pretty old or the solutions were not working for me.
Thank you :)
Normally you'd set the image on the surface of the ImageButton using the setImageResource method (ImageButton inherits it from ImageView), but that method isn't available for RemoteViews.
RemoteViews offers a corresponding setImageViewResource method that does what you want (as well as setImageViewBitmap and setImageViewUri depending on how you'd like to provide the image data).
The code to set the image (say, within your BroadcastReceiver's onReceive method) would look something like this:
#Override
public void onReceive(Context context, Intent intent) {
int appWidgetId = intent.getIntExtra("appWidgetId", -1);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
views.setImageViewResource(R.id.imageButton1, R.drawable.awesome_image);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
Note that the code above assumes you've added the id of the widget to be manipulated as an extra to the broadcast intent (wrapped in a PendingIntent that is sent when the user clicks the ImageButton) using the key "appWidgetId". You'll most likely want to do that in the onUpdate method of your AppWidgetProvider, like so:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent ("YourActionHere");
intent.putExtra("appWidgetId", appWidgetId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
views.setImageViewResource(R.id.imageButton1, R.drawable.initial_image);
views.setOnClickPendingIntent(R.id.imageButton1, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
A simple but not elegant way is:
boolean isButtonSelected = false;
..
button.setOnClickListener(buttonListener);
..
OnClickListener buttonListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
if(isButtonSelected ){
isButtonSelected = false;
button.setBackgroundResource(R.drawable.buttonOff); // or setImageResource(..);
} else{
isButtonSelected = true;
button.setBackgroundResource(R.drawable.buttonOn);
}
}
};

How to update view of a widget on button click in android?

i am developing android widget and i displayed some data on that widget from web service and its working fine.Hear is the code for that.
CODE
public class WatchWidget extends AppWidgetProvider{
private static final String TAG = "WatchWidget";
#Override
public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ){
Log.i(TAG, "* onUpdate");
EBWeaterData ebwd=new EBWeaterData();
EBWeatreUtils.getWeatherFeeds(context, ebwd, "my url to get data");
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main);
RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.test);
//get data
String day=ebwd.getDay_1()+ebwd.getDay_suffix_1()+" "+ebwd.getDay_name_1();
String minmaxtemp="Max Temp "+ebwd.getDay_max_temp_1()+"°C "+"Min Temp "+ebwd.getDay_min_temp_1()+"°C";
//set dat to views
newView.setTextViewText(R.id.textView_day_name, day);
newView.setTextViewText(R.id.textView_minmaxtemp, minmaxtemp);
newView.setImageViewResource(R.id.ImageView_icon, R.drawable.sunny);
views.addView(R.id.view_container, newView);
ComponentName thisWidget = new ComponentName(context,WatchWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, views);
}
}
i have a button on that widget now i want to update the widget view with different values when user clicks on the button.I know I have to do with it pendingIntent like following.
Intent intent = new Intent(context, activitytogetNewdata.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.imageView1, pendingIntent);
But it will start another activity i dont want to go to anther activity.I just need to do is to update the same widget view with new values after button click.Any Idea??
I have found the problem of my code.when i going to update my view using pendingintent it will dynamically add view on each and every button click because i have used 2 layout hear so i solved the problem as follows.(i use one layout instead of using two)
CODE
public class WatchWidget extends AppWidgetProvider{
private static final String TAG = "WatchWidget";
#Override
public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ){
Log.i(TAG, "* onUpdate");
EBWeaterData ebwd=new EBWeaterData();
EBWeatreUtils.getWeatherFeeds(context, ebwd, "my url to get data");
RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.test);
//get data
String day=ebwd.getDay_1()+ebwd.getDay_suffix_1()+" "+ebwd.getDay_name_1();
String minmaxtemp="Max Temp "+ebwd.getDay_max_temp_1()+"°C "+"Min Temp "+ebwd.getDay_min_temp_1()+"°C";
//set dat to views
newView.setTextViewText(R.id.textView_day_name, day);
newView.setTextViewText(R.id.textView_minmaxtemp, minmaxtemp);
newView.setImageViewResource(R.id.ImageView_icon, R.drawable.sunny);
ComponentName thisWidget = new ComponentName(context,WatchWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, newView);
}
Go through this tutorial.
Visit http://www.developer.com/ws/android/programming/Handling-User-Interaction-with-Android-App-Widgets-3837531.htm
They have solved the problem what you have.

Categories

Resources