Related
Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
cTrox said:
Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
Click to expand...
Click to collapse
the "checked" solution in that example seems wrong to me. but the second one people voted up seems correct.
You can also set the onDissmissListener which will catch if the user backs out with the back key ( recommended for user friendliness )
have a look here:
http://developer.android.com/refere...id.content.DialogInterface.OnDismissListener)
Also, since DatePickerDialog is a subclass of AlertDialog, you can set the buttons the same way:
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
That should get you started but feel free to post back if you get stuck again. And post the code you are using.
Also, one other thing, it might be useful to keep a private reference to your dialog in your activity class.
All those examples (in the API docs and tutorials) always show a new dialog created when "onCreateDialog(int ID)" is called by the OS on your activity and they never save any sort of reference to it. They give you just enough code to hang yourself
Anyways, while this is a perfectly normal way to do things, it doesnt give you a chance to follow what is actually happening with the dialog. It also makes it harder to reference your dialog from elsewhere in the activity.
Keeping a reference, and exploring the onPrepareDialog(int ID) method are good for learning what the OS is doing with your dialog. (IMHO)
hth
Thanks a lot for your answers. But I still can't figure out how to do it.
Here's my current Code:
Code:
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datePicker, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
// do some more stuff...
}
};
Code:
protected Dialog onCreateDialog(int id) {
Calendar cDate = Calendar.getInstance();
int cyear = cDate.get(Calendar.YEAR);
int cmonth = cDate.get(Calendar.MONTH);
int cday = cDate.get(Calendar.DAY_OF_MONTH);
switch(id){
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
return null;
}
With that I can just call showDialog(DATE_DIALOG_ID); and I get the dialog. Now, where do I have to implement this OnDismissListener and how?
Thanks!
there are lots of ways to do this but I broke it out into several parts so hopefully it seems more obvious what is happening.
Code:
//here's our field reference we could use later or reuse or whatever
private DatePickerDialog dateDialog = null;
protected Dialog onCreateDialog(int id)
{
//your calendar code here... just removed to save space
switch(id)
{
case DATE_DIALOG_ID:
dateDialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dateDialog.setButton ( DialogInterface.BUTTON_NEGATIVE, android.R.string.cancel, cancelBtnListener );
dateDialog.setOnDismissListener ( listener );
break;
}
return dateDialog;
}
//our dismiss listener
protected DialogInterface.OnDismissListener dismissListener = new OnDismissListener( )
{
@Override
public void onDismiss ( DialogInterface dialog )
{
// do your thang here
}
};
//our click listener
protected DialogInterface.OnClickListener cancelBtnListener = new OnClickListener( )
{
@Override
public void onClick ( DialogInterface dialog, int which )
{
dialog.dismiss ( );
// since we dismiss here, the next listener to get called
// is the dismiss listener. now we'll have consistent behavoir
}
};
Ah thank you very much! I was always confused, where to set the Button and the OnDismissListener.
It works perfectly like that!
In my Android app, I have a sound that I want to play when a certain selection has been made from a spinner, but I want it to play the when the user actually makes the proper selection (or just after). My problem is that although the sound does play when they make the correct selection, as long as that selection stays chosen, it also plays every time the app starts up, when it should ONLY play at the time it's chosen. I think I need to change my setOnItemSelectedListener to setOnItemClickListener, but I'm not sure how (still pretty new to java). Can any generous soul out there show me how to change this up (assuming that's how to best solve this problem)?
Here is the code I have now:
Code:
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(
this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.bowchica);
mp.start();
} if(position == 4) {
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.debbie2);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I haven't try the below code but you can try it on your own and tell us.
In onCreate() declare MediaPlayer mp;
In every if statement that you use for check insert this code:
Code:
if(mp!=null){mp.release();}
int resid = R.raw.yoursound;
mp = MediaPlayer.create(this, resid);
After that override the methods onPause() and onResume() and insert this:
if(mp!=null){mp.release();}
If it is still playing a sound when you start your app, then you should check your code again if you have set as default option any of your selection options.
I would LOVE to try this out...Unfortunately, I'm way too dumb at this point point ot figure out exactly where those code snippets would go inside of what I already have.
Does anyone have a couple of minutes to show me where it would go?
Below is a sample code. Since i don't know your code I give you a snippet that you should adjust it to your code.
Code:
public class SampleSound extends Activity{
private Spinner fitnessSpinner;
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//here goes your layout
setViews();//here you will set all your views(spinners buttons textviews etc..)
setAdapters();//set your adapters here
setListeners();//
}
private void setListeners() {
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
if(mp!=null){mp.release();}
int resid = R.raw.bowchica;
mp = MediaPlayer.create(this, resid);
mp.start();
} if(position == 4) {
if(mp!=null){mp.release();}
int resid = R.raw.debbie2;
mp = MediaPlayer.create(this, resid);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void setAdapters() {
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
}
private void setViews() {
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
}
public void onResume(){
super.onResume();
if(mp!=null){mp.release();}
}
public void onPause(){
super.onPause();
if(mp!=null){mp.release();}
}
}
I really appreciate the help. I put the code in my routine, but it still plays the sound every time the activity is loaded (as long as the selection in the spinner is correct). It should only play the sound when the correct selection is made.
Any other ideas?
I am sure that your Spinner is set to some value (since you have values to display). Because your Spinner points to a selection (doesn't matter if you have selected or it is selected by default) your sound plays (even when you start the app).
A way to stop the sound playing at start is to declare and an other Item like you did with the previous 4 and set it as default selection of your Spinner.
To sum up:
1.You have to append in R.array.fitness_array an Item (like you did with the previous Items) and give it a name.
2.At the end of method setAdapters() insert this:
Code:
fitnessSpiner.setSelection(5);// or whatever is your selection number
Now it should work but you should know that this is not a good practice and you should try make a ListView or something else.
I'd be happy to change this out to a listview, or whatever would work. I just have to give my user a choice of 4 or 5 items, from which they can choose only one. Something like a drop down box, but in Android, I thought my only option was a spinner. But whatever I use, I have to be able to play a sound when certain items are chosen, but ONLY when those items are chosen, NOT whenever the activity is called up.
Any specific ideas of what I might change to?
What if I had another control like a textview or an edittext (with it's visibility property set to false) that I programatically populated with the users selection (when it's the selection that I want) and then have an OnItemClcickListener set to play the sound?
Could that work?
I will answer from the last to the top of your questions.
1.You can do whatever you want with android. You want TextViews and EditTexts with complex and nested Layouts you can do it. Write services that will communicate with your contacts through a content provider? You can do it.
Write, read and test code. Only this way you will actually learn.
2.Read developer.android.com. Read the android tutorials from there and specifically the Notepad example. You will learn a lot.
A good resource with small examples for ListViews is this.
3.Have you tried the changes I told you from the last post? Did it worked?
Since you just started with android and programming you must first be happy if you have the expected result and then read more to make your code better
Your suggested changes (fitnessSpiner.setSelection(5);// or whatever is your selection number) would stop the sound from playing, but defeat the apps purpose. Every time this activity is loaded, the spinners hit preferences to load the previously stored data. So if I force the spinner to a different selection to NOT play sound when the activity loads, then I would be displaying the wrong data for the user.
Yes you are right. So it is better to make a ListActivity. Read developer.android.com and the link i gave you before. You will be ok with this!
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Lakers16 said:
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Click to expand...
Click to collapse
onClickListener doesn't work for the spinner...I wish it did.
I REALLY need the drop down functionality of teh spinner, so I guess I'm going to try and figure out a way to have an invisible edittext that I set to the spinner selection and then use onClickListener or onChange...
i was struggling with creating an onClickListener for an Appwidget so instead of setting it in onUpdate i was doing it in one of the later intents in onRecieve. are the Intents used to create AppWidgets the same for all android phones? cause they have some pretty dubious names for CM7 on my Inspire 4G? can anyone confirm that these are the same on another build of Android?
I/GITextCloud(32189): android.appwidget.action.APPWIDGET_ENABLED
I/GITextCloud(32189): android.appwidget.action.APPWIDGET_UPDATE
I/GITextCloud(32189): com.motorola.blur.home.ACTION_SET_WIDGET_SIZE
I/GITextCloud(32189): mobi.intuitit.android.hpp.ACTION_READY
are these the same for every build of android? i am using CM7 on an Inspire 4G so why is a motorola blur intent being sent? or an intuitit intent? can i rely on these being there for all builds of android? not just CM7?
---------------------
i rambled in my original post. it was quite insane. it is in the second post.
I have had a rather strange problem with one of my AppWidgets i am writing. i have it so when the widget is clicked gmail opens. the problem arrises from when the setOnClickListener is run.
normally one would recommend setting your onClickListeners in the onUpdate() method as it is the easiest since all the info you need is passed to it. but when it is like this the onClickListener is set before the widget exists on the screen and thus the onClickListener doesnt attach. clicking the widget does nothing.
Code:
/** Called when the activity is first created. */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//attach an onClick intent to the layout
final Intent onClick = new Intent(context, GITextCloud.class);
onClick.setAction(LAUNCH_GMAIL_GAPPS);
PendingIntent onClickPending = PendingIntent.getBroadcast(context, 0, onClick, 0);
RemoteViews rv1 = new RemoteViews(context.getPackageName(), R.layout.gitc_widget_html);
rv1.setOnClickPendingIntent(R.id.full_widget, onClickPending);
for (int appWidgetId : appWidgetIds) {
appWidgetManager.updateAppWidget(appWidgetId, rv1);
}
}
so i decided i would perform my setOnClickListener action after returning from WidgetConfig Activity. upon exiting the Config i sent a delayed broadcast to my widget which i would catch in the onRecieve method like so
Code:
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
// other intent catches....
if (intent.getAction().equals(SETUP_DELAY)) {
Toast.makeText(context, "setup delay over", Toast.LENGTH_LONG).show();
//attach an onClick intent to the layout
final Intent onClick = new Intent(context, GITextCloud.class);
onClick.setAction(LAUNCH_GMAIL_GAPPS);
PendingIntent onClickPending = PendingIntent.getBroadcast(context, 0, onClick, 0);
RemoteViews rv1 = new RemoteViews(context.getPackageName(), R.layout.gitc_widget_html);
rv1.setOnClickPendingIntent(R.id.full_widget, onClickPending);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, GITextCloud.class));
for (int id : ids) {
manager.updateAppWidget(id, rv1);
}
}
// other intent catches....
}
now that works great as long as you press ok on the AppWidget size confirmation before the time on the delayed broadcast from my Config Activity runs out.
so i decided i would look at what intents the appwidget was receiving and perform the setOnClickListener at the last intent received.
they are as follows...
I/GITextCloud(32189): android.appwidget.action.APPWIDGET_ENABLED
I/GITextCloud(32189): android.appwidget.action.APPWIDGET_UPDATE
I/GITextCloud(32189): com.motorola.blur.home.ACTION_SET_WIDGET_SIZE
I/GITextCloud(32189): mobi.intuitit.android.hpp.ACTION_READY
are these the same for every build of android? i am using CM7 on an Inspire 4G so why is a motorola blur intent being sent? or an intuitit intent? can i rely on these being there for all builds of android? not just CM7?
Click to expand...
Click to collapse
rambling and quite unnecessary
are we devoid of any knowledge of this?
Hello,
I am developing an app related to alarm service and facing an issue of Intent not being called.
I have registered for event in manifest file:
<receiver android:name="com.example.myfirstapp.EventTriggerManager" >
</receiver>
And have implemented EventTriggerManager class extended from BroadcastReceiver:
public class EventTriggerManager extends BroadcastReceiver
{
@override
public void onReceive(Context context, Intent intent)
{
System.out.println("Alarm raised");
Toast.makeText(context, "Don't panik You have an alarm!!!!.", Toast.LENGTH_LONG).show();
}
}
Adding an alarm from the Activity class:
Intent intent = new Intent(this, EventTriggerManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 12345678, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, totalTime, pendingIntent);
But alarm is not getting triggered when totalTime is reached in the system.
Note: totalTime is absolute time used.
Pls point my mistake why the expected output is not seen.
Regards,
Sunil
Sunil K said:
Hello,
I am developing an app related to alarm service and facing an issue of Intent not being called.
I have registered for event in manifest file:
<receiver android:name="com.example.myfirstapp.EventTriggerManager" >
</receiver>
And have implemented EventTriggerManager class extended from BroadcastReceiver:
public class EventTriggerManager extends BroadcastReceiver
{
@override
public void onReceive(Context context, Intent intent)
{
System.out.println("Alarm raised");
Toast.makeText(context, "Don't panik You have an alarm!!!!.", Toast.LENGTH_LONG).show();
}
}
Adding an alarm from the Activity class:
Intent intent = new Intent(this, EventTriggerManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 12345678, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, totalTime, pendingIntent);
But alarm is not getting triggered when totalTime is reached in the system.
Note: totalTime is absolute time used.
Pls point my mistake why the expected output is not seen.
Regards,
Sunil
Click to expand...
Click to collapse
use this one :
Code:
Intent myIntent = new Intent(Current.this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
insted of :
Code:
Intent intent = new Intent(this, EventTriggerManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 12345678, intent, 0);
mohamedrashad said:
use this one :
Code:
Intent myIntent = new Intent(Current.this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
insted of :
Code:
Intent intent = new Intent(this, EventTriggerManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 12345678, intent, 0);
Click to expand...
Click to collapse
My EventTriggerManager extends BroadcastReceiver and it is not service right? Correct me if wrong.
I tried with the above changes but facing error:
04-19 21:25:00.019: W/ActivityManager(885): Unable to start service Intent { flg=0x4 cmp=com.example.myfirstapp/.EventTriggerManager (has extras) }: not found
Sunil K said:
My EventTriggerManager extends BroadcastReceiver and it is not service right? Correct me if wrong.
I tried with the above changes but facing error:
04-19 21:25:00.019: W/ActivityManager(885): Unable to start service Intent { flg=0x4 cmp=com.example.myfirstapp/.EventTriggerManager (has extras) }: not found
Click to expand...
Click to collapse
sorry I copied this from an old app I made, change get service => get broadcast and the notify.class to your reciver
mohamedrashad said:
sorry I copied this from an old app I made, change get service => get broadcast and the notify.class to your reciver
Click to expand...
Click to collapse
That is what I had done right:
Intent intent = new Intent(this, EventTriggerManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 12345678, intent, 0);
Here eventTriggerManager is my receiver class. But alarm is not recevied by application
Sunil K said:
That is what I had done right:
Intent intent = new Intent(this, EventTriggerManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 12345678, intent, 0);
Here eventTriggerManager is my receiver class. But alarm is not recevied by application
Click to expand...
Click to collapse
Try this
PHP:
int time;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
br = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
yourMethod();
//called when alarmmanager triggers pending intent
}
};
registerReceiver(br, new IntentFilter("com.your.packagename"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.your.packagename"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
if (you want repeating alarm ?) {
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
1000 * time, pi);
} else {
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000 * time, pi);
}
And please use the CODE tags, next time you want to post some code
gh0stslayer said:
Try this
PHP:
int time;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
br = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
yourMethod();
//called when alarmmanager triggers pending intent
}
};
registerReceiver(br, new IntentFilter("com.your.packagename"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.your.packagename"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
if (you want repeating alarm ?) {
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
1000 * time, pi);
} else {
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000 * time, pi);
}
And please use the CODE tags, next time you want to post some code
Click to expand...
Click to collapse
Hello,
Alarms are getting received only when activity is running it is not otherwise.
Googled and tried below flag for intent :
Code:
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
Also applied below permissions for app:
Code:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"></uses-permission>
But nothing worked though. Can you please help me finding solution to it?
Sunil K said:
Hello,
Alarms are getting received only when activity is running it is not otherwise.
Googled and tried below flag for intent :
Code:
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
Also applied below permissions for app:
Code:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"></uses-permission>
But nothing worked though. Can you please help me finding solution to it?
Click to expand...
Click to collapse
If you want to keep it running in the background you should put that code in a background service. You can get lots of examples on google. Start the service when you want to use it. You can use boot receiver to start the service if you want the alarm intent to start every time the app boots.
Sent from my Galaxy Nexus using Tapatalk
gh0stslayer said:
If you want to keep it running in the background you should put that code in a background service. You can get lots of examples on google. Start the service when you want to use it. You can use boot receiver to start the service if you want the alarm intent to start every time the app boots.
Sent from my Galaxy Nexus using Tapatalk
Click to expand...
Click to collapse
Thank you, I will explore this more
Sunil K said:
Thank you, I will explore this more
Click to expand...
Click to collapse
good luck, post again if you face some problems.
Sent from my Galaxy Nexus using Tapatalk
Hello,
I got a question. I'm trying to develop an app with some traffic light, it is made out of open source images. It is from a learn to develop android apps couse from udemy. I wanted to add something, I thought about a button with an automatic change function and stop function, with an interval to change the lights on and off. Do you guys have any idea how to do that?
Thanks in advance,
dev_freak
dev_freak said:
Hello,
I got a question. I'm trying to develop an app with some traffic light, it is made out of open source images. It is from a learn to develop android apps couse from udemy. I wanted to add something, I thought about a button with an automatic change function and stop function, with an interval to change the lights on and off. Do you guys have any idea how to do that?
Thanks in advance,
dev_freak
Click to expand...
Click to collapse
I think you can use this :
Code:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
/* Put below your new function. */
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 5000);
Second parameter is the interval in seconds. (eg: 5 seconds = 5000)
eng.ahmed.android said:
I think you can use this :
Code:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
/* Put below your new function. */
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 5000);
Second parameter is the interval in seconds. (eg: 5 seconds = 5000)
Click to expand...
Click to collapse
A bit late, but it didn't work