Optimisation: multiple clickevents with same code but differten values - mouseclick-event

I have code below. Is ther a way to write this more efficiently? Because i repeat the code, there are only other values to the class Drank.
private void btnCola_Click(object sender, RoutedEventArgs e)
{
Drank dranken = new Drank
{ Naam = "Cola", Prijs = 1.50M };
lblDrankje.Content = dranken.ToString();
GroupBox1.IsEnabled = false;
}
private void btnWater_Click(object sender, RoutedEventArgs e)
{
Drank dranken = new Drank
{ Naam = "Water", Prijs = 1.00M };
lblDrankje.Content = dranken.ToString();
GroupBox1.IsEnabled = false;
}
private void btnKoffie_Click(object sender, RoutedEventArgs e)
{
Drank dranken = new Drank
{ Naam = "Koffie", Prijs = 1.70M };
lblDrankje.Content = dranken.ToString();
GroupBox1.IsEnabled = false;
}
private void btnSoep_Click(object sender, RoutedEventArgs e)
{
Drank dranken = new Drank
{ Naam = "Soep", Prijs = 1.90M };
lblDrankje.Content = dranken.ToString();
GroupBox1.IsEnabled = false;
}

You could create a method with the logic for all click events
private void DrankClick(string naam, decimal prijs)
{
Drank dranken = new Drank
{ Naam = naam, Prijs = prijs };
lblDrankje.Content = dranken.ToString();
GroupBox1.IsEnabled = false;
}
and then have a method for each event e.g.
private void btnCola_Click(object sender, RoutedEventArgs e)
{
DrankClick("Cola", 1.50M);
}

Related

"'Object reference not set to an instance of an object" When I Started App

I have got some Classes implements IHostedService.
EmailSendService:
public class EMailSendService : IHostedService, IDisposable
{
private Timer _timer;
private IMailAccountService _mailAccountService;
private IMailTaskDAL _mailTaskDal;
private LoggerServiceBase _loggerServiceBase;
public EMailSendService(IMailAccountService mailAccountService, IMailTaskDAL mailTaskDal)
{
_mailAccountService = mailAccountService;
_mailTaskDal = mailTaskDal;
_loggerServiceBase = (LoggerServiceBase)Activator.CreateInstance(typeof(DatabaseLogger));
}
private void SendMail(object state)
{
var isAnyMailSended = false;
var logDetail = new LogDetail
{
UserID = "",
UserAgent = "",
IP = "System",
MethodName = "SENDMAILTASK",
StackTrace = "",
TraceIdentifier = ""
};
try
{
var now = DateTime.Now;
var mailTasks = _mailTaskDal.GetList(op => !op.IsSended && op.NextSendDate < now && op.TryCount < 10);
isAnyMailSended = mailTasks.Count > 0;
foreach (var mailTask in mailTasks)
{
var toList = mailTask.ToList.Split(',');
var sendResult = _mailAccountService.SendMail(toList, mailTask.Subject, mailTask.Body);
mailTask.Result = sendResult.Messages[0].Description;
if (sendResult.Success)
{
mailTask.IsSended = true;
mailTask.SendDate = DateTime.Now;
}
else
{
mailTask.NextSendDate = DateTime.Now.AddMinutes(5);
mailTask.TryCount++;
}
_mailTaskDal.Update(mailTask);
}
}
catch (Exception e)
{
logDetail.ExceptionMessage = e.Message;
logDetail.StackTrace = e.StackTrace;
}
finally
{
if (isAnyMailSended)
_loggerServiceBase.Info(logDetail);
}
}
public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(SendMail, null, TimeSpan.Zero, TimeSpan.FromSeconds(30));
return System.Threading.Tasks.Task.CompletedTask;
}
public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return System.Threading.Tasks.Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
CreateActivityTask:
public class CreateActivityTask : IHostedService, IDisposable
{
private Timer _timer;
private LoggerServiceBase _loggerServiceBase;
public CreateActivityTask()
{
_loggerServiceBase = (LoggerServiceBase)Activator.CreateInstance(typeof(DatabaseLogger));
}
private void CreateActivity(object state)
{
var logDetail = new LogDetail
{
UserID = "",
UserAgent = "",
IP = "System",
MethodName = "CreateActivityTask",
StackTrace = "",
TraceIdentifier = ""
};
try
{
//create activity
}
catch (Exception e)
{
logDetail.ExceptionMessage = e.Message;
logDetail.StackTrace = e.StackTrace;
}
finally
{
_loggerServiceBase?.Info(logDetail);
}
}
public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(CreateActivity, null, TimeSpan.Zero, TimeSpan.FromSeconds(60));
return System.Threading.Tasks.Task.CompletedTask;
}
public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return System.Threading.Tasks.Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
I Use two extension function to add this classes in startup.cs -> ConfigureServices:
services.AddHostedService<EMailSendService>();
services.AddHostedService<CreateActivityTask>();
But if i use like that, program does not run. When i start it, this code throws an error:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run(); // This is where throws error
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Error Detail:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Microsoft.Extensions.Hosting
StackTrace:
at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__9.MoveNext()
If i comment
services.AddHostedService();
Still i get the error. But if i comment all "CreateActivityTask" class and "services.AddHostedService();", then i can run the app.
EmailTaskService can run properly. But if i left "CreateActivityTask" alone (I mean, i commented all "EmailTaskService class etc..), program gets error again.
I can't see any error on CreateActivity class, so i can't find where is the mistake. Could you help me please?

Xamarin Forms - Listview view cell swipe left and right events using xamal

I need to write code (or XAML) for listview viewcell swipe left and right gestures.
When swiping left, delete the records from listview (or observable collection) list and update the remaining listitems in listview. When swiping right, save the records.
I've do it using cs code,You can try it on xaml.
First, you should build swipe compoment using gesture
SwipeGestureGrid.cs
public class SwipeGestureGrid : Grid
{
#region Private Member
private double _gestureX { get; set; }
private double _gestureY { get; set; }
private bool IsSwipe { get; set; }
#endregion
#region Public Member
#region Events
#region Tapped
public event EventHandler Tapped;
protected void OnTapped(EventArgs e)
{
if (Tapped != null)
Tapped(this, e);
}
#endregion
#region SwipeUP
public event EventHandler SwipeUP;
protected void OnSwipeUP(EventArgs e)
{
if (SwipeUP != null)
SwipeUP(this, e);
}
#endregion
#region SwipeDown
public event EventHandler SwipeDown;
protected void OnSwipeDown(EventArgs e)
{
if (SwipeDown != null)
SwipeDown(this, e);
}
#endregion
#region SwipeRight
public event EventHandler SwipeRight;
protected void OnSwipeRight(EventArgs e)
{
if (SwipeRight != null)
SwipeRight(this, e);
}
#endregion
#region SwipeLeft
public event EventHandler SwipeLeft;
protected void OnSwipeLeft(EventArgs e)
{
if (SwipeLeft != null)
SwipeLeft(this, e);
}
#endregion
#endregion
public double Height
{
get
{
return HeightRequest;
}
set
{
HeightRequest = value;
}
}
public double Width
{
get
{
return WidthRequest;
}
set
{
WidthRequest = value;
}
}
#endregion
public SwipeGestureGrid()
{
PanGestureRecognizer panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += PanGesture_PanUpdated;
TapGestureRecognizer tapGesture = new TapGestureRecognizer();
tapGesture.Tapped += TapGesture_Tapped;
GestureRecognizers.Add(panGesture);
GestureRecognizers.Add(tapGesture);
}
private void TapGesture_Tapped(object sender, EventArgs e)
{
try
{
if (!IsSwipe)
OnTapped(null);
IsSwipe = false;
}
catch (Exception ex)
{
}
}
private void PanGesture_PanUpdated(object sender, PanUpdatedEventArgs e)
{
try
{
switch (e.StatusType)
{
case GestureStatus.Running:
{
_gestureX = e.TotalX;
_gestureY = e.TotalY;
}
break;
case GestureStatus.Completed:
{
IsSwipe = true;
//Debug.WriteLine("{0} {1}", _gestureX, _gestureY);
if (Math.Abs(_gestureX) > Math.Abs(_gestureY))
{
if (_gestureX > 0)
{
OnSwipeRight(null);
}
else
{
OnSwipeLeft(null);
}
}
else
{
if (_gestureY > 0)
{
OnSwipeDown(null);
}
else
{
OnSwipeUP(null);
}
}
}
break;
}
}
catch (Exception ex)
{
}
}
}
Next using datatemplate in listview andattach event for Gesturecompoment
Page.cs
ListView lsvData = new ListView()
{
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.Fill,
BackgroundColor = Color.White,
HasUnevenRows = true,
};
List<string> lstData = new List<string>();
public Pages()
{
#region DataTemplate
DataTemplate ListDataTemplate = new DataTemplate(() =>
{
#region DataArea of Template
SwipeGestureGrid gridData = new SwipeGestureGrid()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 60,
RowDefinitions =
{
new RowDefinition { },
},
ColumnDefinitions =
{
new ColumnDefinition { },
}
};
#endregion
#region Base of Template
Grid gridBase = new Grid()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 60,
RowDefinitions =
{
new RowDefinition { },
},
ColumnDefinitions =
{
new ColumnDefinition { }, //Put Cells Data here
new ColumnDefinition { Width = new GridLength(0, GridUnitType.Absolute)}, //Button for Cells here
},
};
#endregion
Label lblText = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
FontAttributes = FontAttributes.Bold,
VerticalTextAlignment = TextAlignment.End,
TextColor = Color.Black,
BackgroundColor = Color.Silver,
LineBreakMode = LineBreakMode.TailTruncation,
FontSize = 18,
};
lblText.SetBinding(Label.TextProperty, ".");
ImageButton btnCellDelete = new ImageButton() { Source = "Delete" };
gridData.Children.Add(lblText, 0, 0);
gridBase.Children.Add(gridData, 0, 0);
gridBase.Children.Add(btnCellDelete, 1, 0);
gridData.SwipeLeft += GridTemplate_SwipeLeft;
gridData.SwipeRight += GridTemplate_SwipeRight; ;
gridData.Tapped += GridTemplate_Tapped; ;
btnCellDelete.Clicked += BtnCellDelete_Clicked; ;
return new ViewCell
{
View = gridBase,
Height = 60,
};
});
#endregion
for (int i = 1; i <= 100; i++)
{
lstData.Add(i.ToString());
}
lsvData.ItemTemplate = ListDataTemplate;
lsvData.ItemsSource = lstData;
Content = lsvData;
}
event
SwipeLeft to show DeleteButton
private void GridTemplate_SwipeLeft(object sender, EventArgs e)
{
try
{
if (sender is SwipeGestureGrid)
{
var templateGrid = ((SwipeGestureGrid)sender).Parent;
if (templateGrid != null && templateGrid is Grid)
{
var CellTemplateGrid = (Grid)templateGrid;
CellTemplateGrid.ColumnDefinitions[1].Width = new GridLength(60, GridUnitType.Absolute);
}
}
}
catch (Exception ex)
{
}
}
swiperight to hide delete button
private void GridTemplate_SwipeRight(object sender, EventArgs e)
{
try
{
if (sender is SwipeGestureGrid)
{
var templateGrid = ((SwipeGestureGrid)sender).Parent;
if (templateGrid != null && templateGrid is Grid)
{
var CellTemplateGrid = (Grid)templateGrid;
CellTemplateGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Absolute);
}
}
}
catch (Exception ex)
{
}
}
Delete button click event
private void BtnCellDelete_Clicked(object sender, EventArgs e)
{
try
{
if (sender is ImageButton)
{
var templateGrid = ((ImageButton)sender);
//templateGrid.Parent = gridBase
//templateGrid.Parent.Parent = cell
if (templateGrid.Parent != null && templateGrid.Parent.Parent != null && templateGrid.Parent.Parent.BindingContext != null && templateGrid.Parent.Parent.BindingContext is string)
{
var deletedate = templateGrid.Parent.Parent.BindingContext as string;
lstData.RemoveAll(f => f == deletedate);
lsvData.ItemsSource = null;
lsvData.ItemsSource = lstData;
}
}
}
catch (Exception ex)
{
}
}
Source can be find in my github
https://github.com/act70255/ListViewSwipeGesture
I've reworked James Lin's class to be command based so that it's MVVM friendly.
public class SwipeGestureGrid : Grid
{
public static readonly BindableProperty SwipeLeftCommandProperty =
BindableProperty.Create("SwipeLeftCommand", typeof(ICommand), typeof(ICommand), null);
public static readonly BindableProperty SwipeRightCommandProperty =
BindableProperty.Create("SwipeRightCommand", typeof(ICommand), typeof(ICommand), null);
public static readonly BindableProperty SwipeUpCommandProperty =
BindableProperty.Create("SwipeUpCommand", typeof(ICommand), typeof(ICommand), null);
public static readonly BindableProperty SwipeDownCommandProperty =
BindableProperty.Create("SwipeDownCommand", typeof(ICommand), typeof(ICommand), null);
public static readonly BindableProperty TappedCommandProperty =
BindableProperty.Create("TappedCommand", typeof(ICommand), typeof(ICommand), null);
private double _gestureStartX;
private double _gestureStartY;
private double _gestureDistanceX;
private double _gestureDistanceY;
public double GestureStartX
{
get => _gestureStartX;
private set
{
_gestureStartX = value;
OnPropertyChanged();
}
}
public double GestureStartY
{
get => _gestureStartY;
private set
{
_gestureStartY = value;
OnPropertyChanged();
}
}
private bool IsSwipe { get; set; }
public ICommand TappedCommand
{
get => (ICommand) GetValue(TappedCommandProperty);
set => SetValue(TappedCommandProperty, value);
}
public ICommand SwipeLeftCommand
{
get => (ICommand)GetValue(SwipeLeftCommandProperty);
set => SetValue(SwipeLeftCommandProperty, value);
}
public ICommand SwipeRightCommand
{
get => (ICommand)GetValue(SwipeRightCommandProperty);
set => SetValue(SwipeRightCommandProperty, value);
}
public ICommand SwipeUpCommand
{
get => (ICommand)GetValue(SwipeUpCommandProperty);
set => SetValue(SwipeUpCommandProperty, value);
}
public ICommand SwipeDownCommand
{
get => (ICommand)GetValue(SwipeDownCommandProperty);
set => SetValue(SwipeDownCommandProperty, value);
}
public SwipeGestureGrid()
{
var panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += PanGesture_PanUpdated;
var tapGesture = new TapGestureRecognizer();
tapGesture.Tapped += TapGesture_Tapped;
GestureRecognizers.Add(panGesture);
GestureRecognizers.Add(tapGesture);
}
private void TapGesture_Tapped(object sender, EventArgs e)
{
try
{
if (!IsSwipe)
TappedCommand?.Execute(this);
IsSwipe = false;
}
catch (Exception ex)
{
}
}
private void PanGesture_PanUpdated(object sender, PanUpdatedEventArgs e)
{
switch (e.StatusType)
{
case GestureStatus.Started:
{
GestureStartX = e.TotalX;
GestureStartY = e.TotalY;
}
break;
case GestureStatus.Running:
{
_gestureDistanceX = e.TotalX;
_gestureDistanceY = e.TotalY;
}
break;
case GestureStatus.Completed:
{
IsSwipe = true;
if (Math.Abs(_gestureDistanceX) > Math.Abs(_gestureDistanceY))
{
if (_gestureDistanceX > 0)
{
SwipeRightCommand?.Execute(this);
}
else
{
SwipeLeftCommand?.Execute(null);
}
}
else
{
if (_gestureDistanceY > 0)
{
SwipeDownCommand?.Execute(null);
}
else
{
SwipeUpCommand?.Execute(null);
}
}
}
break;
}
}
}
We use it in a DataTemplate for a ScrollableListView:
<DataTemplate x:Key="ThreeRowTemplateTemplate" x:DataType="{x:Type tracking:TrackingItem}">
<ViewCell>
<controls:SwipeGestureGrid ColumnSpacing="0" RowSpacing="0" SwipeLeftCommand="{Binding SwipeLeftCommand}">
In this case the bound command has to be on TrackingItem. It seems to work quite well but the detection is sometimes a bit flaky - possibly there's a conflict with the ScrollableListView's gesture handling.

How can I add KeyUp event for my UserControl?

I have a user control that working like WatermarkPasswordBox and I want to add KeyUp event for my user control's PasswordBox's Key Up event. How can I do it?
<UserControl
x:Class="Windows8.StoreApp.Common.CustomControls.WatermarkPasswordTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows8.StoreApp.Common.CustomControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<PasswordBox x:Name="passwordB" GotFocus="PasswordBox_GotFocus" LostFocus="PasswordBox_LostFocus" PasswordChanged="passwordB_PasswordChanged" Style="{StaticResource AkbankControlStyleWatermarkPasswordBoxLoginFormInputPasswordBox}"></PasswordBox>
<TextBlock x:Name="lblWaterMark" Tapped="lblWaterMark_Tapped" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,4,10,4" Opacity="0.8" FontFamily="Segoe UI" FontSize="16" Foreground="#FF8E8E8E" FontWeight="SemiBold"></TextBlock>
</Grid>
public WatermarkPasswordTextBox()
{
this.InitializeComponent();
}
private void PasswordBox_GotFocus(object sender, RoutedEventArgs e)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
private void PasswordBox_LostFocus(object sender, RoutedEventArgs e)
{
if ((sender as PasswordBox).Password.Length == 0)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
}
private void passwordB_PasswordChanged(object sender, RoutedEventArgs e)
{
if ((sender as PasswordBox).Password.Length != 0)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
private void lblWaterMark_Tapped(object sender, TappedRoutedEventArgs e)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
passwordB.Focus(Windows.UI.Xaml.FocusState.Pointer);
}
private string _watermark=String.Empty;
public string Watermark
{
get
{
_watermark = lblWaterMark.Text;
return _watermark;
}
set
{
SetProperty<string>(ref _watermark, value, "Watermark");
lblWaterMark.Text = _watermark;
}
}
private int _lenghtMax;
public int LenghtMax
{
get
{
if (passwordB != null)
{
_lenghtMax = passwordB.MaxLength;
return _lenghtMax;
}
else
{
return 0;
}
}
set
{
if (passwordB != null)
{
SetProperty<int>(ref _lenghtMax, value, "LenghtMax");
passwordB.MaxLength = _lenghtMax;
}
}
}
private string _passText = String.Empty;
public string PassText
{
get
{
if (passwordB != null)
{
_passText = passwordB.Password;
return _passText;
}
else
{
return String.Empty;
}
}
set
{
if (passwordB != null)
{
SetProperty<string>(ref _passText, value, "PassText");
passwordB.Password = _passText;
passwordB_PasswordChanged(passwordB, null);
}
else
{
SetProperty<string>(ref _passText, value, "PassText");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I want to use like this;
and this Key_Up will equal to mycontrol's PasswordBox' key up event.
Thanks.
public event KeyEventHandler RelayedKeyUp
{
add
{
passwordB.KeyUp += value;
}
remove
{
passwordB.KeyUp -= value;
}
}

calling alarm from a service

I designed my service as it will make an alarm when user will go to a certain location.
But it crashes when it go to the certain making the alarm.
public class CheckDestinationService extends Service {
Calendar calender;
double late,longe;
int dis;
String loc;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location) {
mLastLocation.set(location);
final double currlat;
final double currlong;
float[] DistanceArray = new float[1];
currlat = location.getLatitude();
currlong = location.getLongitude();
android.location.Location.distanceBetween(currlat,currlong,late,longe,DistanceArray);
float Distance = DistanceArray[0];
//Toast.makeText(getApplicationContext(), "asdf "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
Log.d("asdfasdas", String.valueOf(currlat)+","+String.valueOf(currlong)+" "+String.valueOf(Distance));
if (Distance<=dis && Distance!=0 && dis!=0)
{
dis = 0;
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(getApplicationContext(), "Reached "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),pendingIntent);
//stopSelf();
}
/*final Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Intent intent = null;
intent.putExtra("lat", currlat);
intent.putExtra("long", currlong);
intent.putExtra("dis", dis);
intent.putExtra("loc", loc);
Toast.makeText(getApplicationContext(), "Sending", Toast.LENGTH_SHORT).show();
sendBroadcast(intent);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);*/
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
late = intent.getDoubleExtra("lat", 0);
longe = intent.getDoubleExtra("long", 0);
dis = intent.getIntExtra("dis", 0);
loc = intent.getStringExtra("loc");
Toast.makeText(getApplicationContext(), "Destination Set to: "+loc+
" and Minimum Distance: "+
String.valueOf(dis) , Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Destroyed", Toast.LENGTH_SHORT).show();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
and my AlarmReceiver class is
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarmreceiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
#Override
public void onBackPressed() {
//MainActivity.iMinDistance = 0;
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
}
}
I tested AlarmReceiver class from other activites and it worked properly
but it not working from the service.
please help!!
initalize Calendar
calender = Calendar.getInstance()

Having trouble showing an Account ID and balance in two textboxes

I can't seem to figure out how to display Account ID and Account Balance into a textbox after the selected index is changed in the listbox. I have a Customer class and a Checking account class(which is a subclass of a Bank Account class). The part of the code that is messing up is at the bottom.
This is the part of my code that I'm having trouble with:
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetAcctNumber();
txtBalance.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetBalance().ToString();
This is the rest of the code:
public partial class frmStart : Form
{
private static List<Customer_Account> customers;
private Customer_Account aCustomer;
private Saving_Account aSaver;
private static List<Saving_Account> savers;
private Checking_Account aChecker;
private static List<Checking_Account> checkers;
public frmStart()
{
InitializeComponent();
customers = new List<Customer_Account>();
checkers = new List<Checking_Account>();
savers = new List<Saving_Account>();
}
#region New form for Savings and Checking
private void lstFrmStartChecking_DoubleClick(object sender, EventArgs e)
{
//Shows Checking form
frmChecking showCheckingForm = new frmChecking();
this.Hide();
showCheckingForm.ShowDialog();
this.Close();
}
private void lstFrmStartSavings_SelectedIndexChanged(object sender, EventArgs e)
{
//Show Savings form
frmSavings showSavingForm = new frmSavings();
this.Hide();
showSavingForm.ShowDialog();
this.Close();
}
#endregion
#region Everything needed for TabPage1
//Sets CheckChanged event handler for either New customer or Existing Customer
private void rdoNewCustomer_CheckedChanged(object sender, EventArgs e)
{
groupBox2.Visible = true;
groupBox3.Visible = false;
}
private void rdoExistingCustomer_CheckedChanged(object sender, EventArgs e)
{
groupBox3.Visible = true;
groupBox2.Visible = false;
}//End of CheckChanged event handler
//Button controls for Adding customer to our bank and Clearing the textboxes
//in the 1st group panel
private void btnAddCustomer_Click(object sender, EventArgs e)
{
AddCustomerAccountToList();
PopulateListBox(customers);
}
private void AddCustomerAccountToList()
{
double socialSecurity;
double phoneNumber;
double zipCode;
if (double.TryParse(txtTab1SocialSecurity.Text, out socialSecurity) && double.TryParse(txtTab1PhoneNumber.Text, out phoneNumber)
&& double.TryParse(txtTab1Zip.Text, out zipCode))
{
aCustomer = new Customer_Account(txtTab1SocialSecurity.Text, txtTab1Name.Text, txtTab1Address.Text, txtTab1City.Text,
txtTab1State.Text, txtTab1Zip.Text, txtTab1PhoneNumber.Text, txtTab1Email.Text);
customers.Add(aCustomer);
}
else
{
MessageBox.Show("Please be sure to use only numeric entries for: \nSocial Security \nPhone Number \nZip Code", "Non-numeric Entry");
}
}//End of AddCustomerAccount
private void btnTab1Clear_Click(object sender, EventArgs e)
{
foreach (Control ctrl in groupBox2.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Clear();
}
txtTab1SocialSecurity.Focus();
}
}//end of button controls for 1st group panel
//Add CheckingAccount to List()
//Populate ListBox for List<>
private void PopulateListBox(List<Customer_Account> aListCustomerAccount)
{
lstTabPage1.Items.Clear();
lstTabPage2Checking.Items.Clear();
foreach (Customer_Account customer in aListCustomerAccount)
{
lstTabPage1.Items.Add(customer.GetCustomerName().ToUpper());
lstTabPage2Checking.Items.Add(customer.GetCustomerName().ToUpper());
}
}//End of Populate listbox
//Search for an existing member with name
private void txtTabPage1Search_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < lstTabPage1.Items.Count; i++)
{
if (string.IsNullOrEmpty(txtTabPage1Search.Text))
{
lstTabPage1.SetSelected(i, false);
}
else if (lstTabPage1.GetItemText(lstTabPage1.Items[i]).StartsWith(txtTabPage1Search.Text.ToUpper()))
{
lstTabPage1.SetSelected(i, true);
}
else
{
lstTabPage1.SetSelected(i, false);
}
}
}//End of search
//This button will open a checking account for the customer
private void btnOpenCheckingAccount_Click(object sender, EventArgs e)
{
string acctID;
acctID = txtAccountID.Text;
aChecker = new Checking_Account(acctID, DateTime.Today, 0,
200, frmStart.GetCustomer()[lstTabPage1.SelectedIndex]);
}
//This button will open a saving account for the customer
private void btnOpenSavingsAccount_Click(object sender, EventArgs e)
{
aSaver = new Saving_Account(txtAccountID.Text, DateTime.Today, 0, 0.05,
frmStart.GetCustomer()[lstTabPage1.SelectedIndex]);
}
private static List<Customer_Account> GetCustomer()
{
return customers;
}
#endregion
#region Everything Needed for TabPage2
//Search TabPage 2 Checkers
private void txtTabPage2SearchChecking_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < lstTabPage2Checking.Items.Count; i++)
{
if (string.IsNullOrEmpty(txtTabPage2SearchChecking.Text))
{
lstTabPage2Checking.SetSelected(i, false);
}
else if (lstTabPage1.GetItemText(lstTabPage2Checking.Items[i]).StartsWith(txtTabPage2SearchChecking.Text.ToUpper()))
{
lstTabPage2Checking.SetSelected(i, true);
}
else
{
lstTabPage2Checking.SetSelected(i, false);
}
}
}//End Search TabPage2 Checkers
//Display values in textboxes depending on user selection in listbox
private void lstTabPage2Checking_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
txtTab2SocialSecurity.Text = customers[lstTabPage2Checking.SelectedIndex].GetSocialSecurity().ToString();
txtTab2Name.Text = customers[lstTabPage2Checking.SelectedIndex].GetCustomerName().ToString();
txtTab2City.Text = customers[lstTabPage2Checking.SelectedIndex].GetCity().ToString();
txtTab2State.Text = customers[lstTabPage2Checking.SelectedIndex].GetState().ToString();
txtTab2Zip.Text = customers[lstTabPage2Checking.SelectedIndex].GetZip().ToString();
txtTab2PhoneNumber.Text = customers[lstTabPage2Checking.SelectedIndex].GetPhoneNumber().ToString();
txtTab2Email.Text = customers[lstTabPage2Checking.SelectedIndex].GetEmail().ToString();
txtTab2Address.Text = customers[lstTabPage2Checking.SelectedIndex].GetAddress().ToString();
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetAcctNumber();
txtBalance.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetBalance().ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
}
(This is what the error message says)
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Welcome to SO, Guy!
It looks to me that you are appending the .ToString() method to all of your controls except for this one:
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartCheck‌​ing.SelectedIndex].GetAcctNumber();
Change your code to:
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartCheck‌​ing.SelectedIndex].GetAcctNumber().ToString();
And you should be fine!