This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Add several appWidgets with different configuration?
I have a widget which displays a simple textview, which is editable as an edittextfield in a configuration activity. I'm trying to make it possible to add several widgets to the homescreen with different textconfigurations, fx. one widget display: "Buy a lamp.." and another one saying: "I love Bacon".
My problem is that the widgets keeps displaying the same text, and if I edit one widget the other one changes too. I'm using sharedpreferences to save the inputted data for later re-configuration. (I am not using PreferenceActivity)
I've been struggling with this for hours, any help would be much appreciated.
Why doesn't this work:
SharedPreferences sp;
EditText info;
String note;
int appWidgetId;
private void loadPrefs(){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
note = sp.getString("Note", "");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.putString("Note", info.getText().toString());
editor.commit();
}
and then i have a confirm button to end configuration, which calls the savePrefs method
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("Note", info.getText().toString());
Full code configuration activity code:
import java.io.File;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.ToggleButton;
public class WidgetConfig extends Activity implements OnClickListener, OnItemSelectedListener {
AppWidgetManager awm;
int awID;
Context context;
EditText info;
Button b;
String note;
int styleStart = -1, cursorLoc = 0;
int appWidgetId;
SharedPreferences sp;
Spinner spinner;
String[] paths = { "10", "20", "30" };
File path = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
context = WidgetConfig.this;
info = (EditText)findViewById(R.id.etwidgetconfig);
...
b = (Button)findViewById(R.id.bwidgetconfig);
loadPrefs();
b.setOnClickListener(this);
//Getting Info about the widget that launched this activity
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null){
awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID );
}
awm = AppWidgetManager.getInstance(context);
}
...
private void loadPrefs(){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
note = sp.getString("Note", "");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.putString("Note", info.getText().toString());
editor.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("Note", info.getText().toString());
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.tvConfigInput, info.getText());
ComponentName thisWidget = new ComponentName(this, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
Intent in = new Intent(context, WidgetConfig.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.B_EditAgain, pi);
awm.updateAppWidget(awID, views);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK, result);
finish();
}
}
Oh cool, so just set appWidgetId to awID. or even simpler, pass the awID to the methods you are calling sharedPreferences. That should fix it.
Related
I faced error
developer warning for package "package name" fail to post
notification on channel "null" more see in Logcat
can anyone help me with a normal app that uses TimePicker to set the time ..and also uses intents,etc instead of normal comparisons.This is the code that i've done till now.But this is not working. The 'TimePicker' sets the time and on pressing the 'ToggleButton' a 'TextVew' shows that alarm is on .But when the alarmtime is reached,Alarm Ringing message is not shown.Please someone help me out. this is the code of main activity
AlarmNotificationReceiver
package com.example.kishorsinh.yogaapp;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class AlarmNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent in = new Intent(context, ListExercises.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, in, 0);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.yoga)
.setContentTitle("It's About Time")
.setContentText("text.... ")
.setContentInfo("text....")
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_HIGH);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
Setting Page
package com.example.kishorsinh.yogaapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.example.kishorsinh.yogaapp.Database.YogaDB;
import java.util.Calendar;
import java.util.Date;
public class SettingPage extends AppCompatActivity {
Button btnSave;
RadioButton rdiEasy,rdiMedium,rdiHard;
RadioGroup rdiGroup;
YogaDB yogaDB;
ToggleButton switchAlarm;
TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_page);
//init view
btnSave = (Button) findViewById(R.id.btnSave);
rdiGroup = (RadioGroup) findViewById(R.id.rdiogroup);
rdiEasy = (RadioButton) findViewById(R.id.rdioEasy);
rdiMedium = (RadioButton) findViewById(R.id.rdioMedium);
rdiHard = (RadioButton) findViewById(R.id.rdioHard);
switchAlarm = (ToggleButton) findViewById(R.id.switchAlarm);
timePicker = (TimePicker) findViewById(R.id.timePicker);
yogaDB = new YogaDB(this);
int mode = yogaDB.getSettingMode();
setRadioButton(mode);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveWorkoutMode();
saveAlarm(switchAlarm.isChecked());
Toast.makeText(SettingPage.this, "Saved!!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void saveAlarm(boolean checked) {
if(checked)
{
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent;
PendingIntent pendingIntent;
intent = new Intent(SettingPage.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
//Set time for alarm
Calendar calendar = Calendar.getInstance();
Date toDay = Calendar.getInstance().getTime();
if (Build.VERSION.SDK_INT >= 23 ) {
//new version mate
calendar.set(toDay.getYear(), toDay.getMonth(), toDay.getDate(), timePicker.getHour(), timePicker.getMinute());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("DEBUG", "Alarm will wake at" + timePicker.getHour() + ":" + timePicker.getMinute());
}
else
{
//olderversion mate
calendar.set(toDay.getYear(), toDay.getMonth(), toDay.getDate(), timePicker.getCurrentHour(), timePicker.getCurrentMinute());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("DEBUG", "Alarm will wake at" + timePicker.getCurrentHour() + ":" + timePicker.getCurrentMinute());
}
}
else
{
//Cancel Alarm
Intent intent = new Intent(SettingPage.this,AlarmNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
private void saveWorkoutMode() {
int selectedID = rdiGroup.getCheckedRadioButtonId();
if(selectedID == rdiEasy.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 30sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(0);
}
else if(selectedID == rdiMedium.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 20sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(1);
}
if(selectedID == rdiHard.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 10sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(2);
}
}
private void setRadioButton(int mode) {
if(mode == 0)
rdiGroup.check(R.id.rdioEasy);
else if(mode == 1)
rdiGroup.check(R.id.rdioMedium);
else if(mode == 2)
rdiGroup.check(R.id.rdioHard);
}
}
.
.
..
.
.
.
.
...........................................................................................................
I want to create notification daily in my android app. For the purpose I made a createNotification method. Now, I want to call the method at a particular time. My mainactivity.java is as follows:
package com.example.shiza.dailyquranquote;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
Date startDate= new Date("03/31/2015 12:00:00");
Date endDate = new Date();
TextView textView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.verse);
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;
long daysBetween = endDay - startDay;
SharedPreferences sharedPreferences = getSharedPreferences("QuranVerse",0);
String id = ""+ (daysBetween % 365) ;
String verse = sharedPreferences.getString(id, "");
if (verse == null)
{
verse ="Sufficient is Allah for me; There is no power except Him; And in Him I put my trust.";
}
Calendar rightNow = Calendar.getInstance();
textView.setText(verse + "current hour is" + rightNow.HOUR_OF_DAY);
if ( rightNow.HOUR_OF_DAY == 11 )
{
createNotification();
}
}
public void goToInsertVerse(View v)
{
Intent intent = new Intent(this,InsertVerse.class);
startActivity(intent);
}
public void goToGetVerse(View v)
{
Intent intent = new Intent(this,GetVerse.class);
startActivity(intent);
}
public void createNotification(View view) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject").setSmallIcon(R.drawable.background)
.setContentIntent(pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}
Now I need to pass view as a parameter to createNotification. I am unable to do it. How I can achieve it?
user setContent method wich takes "RemoteViews" as parameter
i am working on a project which includes user to put any time chosen by the time picker, but when i exit the app and open it again the chosen time is gone.
is it possible to save timepicker data and use them when the app starts next time? thank you
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.TimePicker.OnTimeChangedListener;
public class AndroidTimeActivity extends Activity {
TimePicker myTimePicker;
Button buttonstartSetDialog;
Button buttonCancelAlarm;
TextView textAlarmPrompt;
private TimePicker timePicker;
CheckBox optRepeat;
SharedPreferences sPref;
final static int RQS_1 = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timePicker = (TimePicker)findViewById(R.id.picker);
optRepeat = (CheckBox)findViewById(R.id.optrepeat);
textAlarmPrompt = (TextView)findViewById(R.id.alarmprompt);
buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
TimePicker dp = (TimePicker)this.findViewById(R.id.picker);
dp.setCurrentHour(1);
//
dp.setCurrentMinute(01);
buttonstartSetDialog.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Calendar calSet = Calendar.getInstance();
calSet.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calSet.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
setAlarm(calSet, optRepeat.isChecked());
}});
buttonCancelAlarm = (Button)findViewById(R.id.cancel);
buttonCancelAlarm.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
cancelAlarm();
}});
}
private void setAlarm(Calendar targetCal, boolean repeat){
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
if(repeat){
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
targetCal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
pendingIntent);
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "Repeat\n"
+ "***\n");
}else{
alarmManager.set(AlarmManager.RTC_WAKEUP,
targetCal.getTimeInMillis(),
pendingIntent);
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "One shot\n"
+ "***\n");
}
}
private void cancelAlarm(){
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm Cancelled! \n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
timePicker.setOnTimeChangedListener(new OnTimeChangedListener(){
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(getApplicationContext(),
"onTimeChanged", Toast.LENGTH_SHORT).show();
}});
}
}
EDIT: thanks to kruczjak i found the solution:
i used this code in the onclick to save the value to the preferences when the button is clicked
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putInt("hour", timePicker.getCurrentHour()); editor.putInt("minute", timePicker.getCurrentMinute()); editor.commit();
and used this code to open the last saved value from the preferences
SharedPreferences prefs = getPreferences(MODE_PRIVATE); timePicker.setCurrentHour(prefs.getInt("hour", 1)); timePicker.setCurrentMinute(prefs.getInt("minute", 01));
Try to override onStop() method in activity and put there code to save somewhere (database, file or even shared preferences) selected time from timePicker.
Then read it and apply to timePicker in onCreate()
See this article about activity lifecycle for more http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
add this code to your save time button
//Pref To save time picker
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putInt("hour", YourTimePicker.getCurrentHour());
editor.putInt("minute", YourTimePicker.getCurrentMinute());
editor.commit();
and call this method in your onCreate() of time picker activity
public void loadTimer(TimePicker timepicker) {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
timepicker.setCurrentHour(prefs.getInt("hour", 1));
timepicker.setCurrentMinute(prefs.getInt("minute", 01));
}
you will write
loadTimer(YourTimePicker);
My code:
package elf.app;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import elf.app.entity.ELFList;
import elf.app.entity.Entry;
import elf.app.test.FakeComm;
// TODO Kunna skicka att något är färdigt (ett rum är städat).
public class RoomListActivity extends ListActivity {
private ELFList eList;
// private FakeComm fakecomm;
private Bundle extras;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.extras = getIntent().getExtras();
eList = new ELFList();
// fakecomm = new FakeComm();
// eList.add(fakecomm.getData());
String[] strArr = {"asd","sdf","dfg"};
eList.add(strArr);
String[] str = eList.returnNames();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, str));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Entry e = eList.getEntry(position);
String roominfo = e.toString();
Intent intent = new Intent(this, RoomInfoActivity.class);
intent.putExtra("entry",roominfo);
this.startActivity(intent);
// old stuff
// String message;
// message = eList.getEntryInfo(position);
// Toast.makeText(getApplicationContext(),
// message, Toast.LENGTH_SHORT).show();
}
});
}
}
I'm getting errors at the following lines:
Intent intent = new Intent(this, RoomInfoActivity.class);
and
this.startActivity(intent);
I don't have much of a clue why I get these errors, the exact output in the editor for these errors are:
"The constructor Intent(new AdapterView.OnItemClickListener(){}, Class ) is undefined"
"The method startActivity(Intent) is undefined for the type new AdapterView.OnItemClickListener(){}"
I'm an Android newbie so please take that into consideration, however I have studied Java for about a year.
Fix
Intent intent = new Intent(this, RoomInfoActivity.class);
to
Intent intent = new Intent(RoomListActivity.this, RoomInfoActivity.class);
The error is because by this you refer to OnClickListener. The problem is fixed, if you refer to the Activity's this. The second error is the same - wrong reference. Just remove this, and startActivity() method will be searched within the enclosing class too.
try this
Intent intent = new Intent(RoomListActivity.this, RoomInfoActivity.class);
intent.putExtra("entry",roominfo);
RoomListActivity.this.startActivity(intent);
I'm diving into Java (this is day 1) and I'm trying to create a button that will trigger a notification when I click it...
This code is based off of the notification documentation here, and UI events documentation here
package com.example.contactwidget;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
public class ContactWidget extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button calc1 = (Button) findViewById(R.id.calc_button_1);
calc1.setOnClickListener(buttonListener);
setContentView(R.layout.main);
}
private static final int HELLO_ID = 1;
//Error: OnClickListener cannot be resolved to a type
private OnClickListener buttonListener = new OnClickListener() {
public void onClick (View v) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence ticketBrief = "Button Pressed Brief";
CharSequence ticketTitle = "Button pressed";
CharSequence ticketText = "You pressed button 1";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, ticketBrief, when);
Intent notificationIntent = new Intent(this, ContactWidget.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), ticketTitle, ticketText, contentIntent);
mNotificationManager.notify(HELLO_ID, notification);
}
}
}
I'm running into a problem: OnClickListener cannot be resolved to a type. The problem here is that I don't see any problems with my code in relation to the example I'm using
Add this import:
import android.view.View.OnClickListener;
If you are using Eclipse, you can use Ctrl+Shift+O to make it import those clases or interfaces automagically.
Make sure you have both these imports:
import android.view.View;
import android.view.View.OnClickListener;
setContentView(R.layout.main);
Should be above the button declaration, just below
super.onCreate(savedInstanceState);