I am really new to Android Studio (and relatively new to Java too), and I am trying to create an app that will allow the user to input a time and have a timer start counting down when that time occurs. After looking into it, it seems like using an intent is the best way to go, but I am having some issues understanding how to use it. Right now, I have the following code in my main activity file (called Countdown):   public class Countdown extends AppCompatActivity { EditText mHours; EditText mMinutes; TextView mDisplay; public static long finalTime = 0; private AlarmManager alarmMgr; private PendingIntent alarmIntent; Context context;  @Override public void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);     setContentView(R.layout.activity_countdown);     mHours = (EditText) findViewById(R.id.text1);     mMinutes = (EditText) findViewById(R.id.text2);     mDisplay = (TextView) findViewById(R.id.display);     Button button = (Button) findViewById(R.id.button1);      button.setOnClickListener(new View.OnClickListener() {         public void onClick(View v) {             Calendar calendar = Calendar.getInstance();             calendar.setTimeInMillis(System.currentTimeMillis());             calendar.set(Calendar.HOUR_OF_DAY, 11);             calendar.set(Calendar.MINUTE, 22);             Intent intent = new Intent(context, Countdown.class);             alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);              alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);             alarmMgr.set(AlarmManager.RTC, calendar.getTimeInMillis(), alarmIntent);              final long hourInput = Long.parseLong(mHours.getText().toString());             final long minuteInput = Long.parseLong(mMinutes.getText().toString());             finalTime = (hourInput * 3600000) + (minuteInput *  60000);        } } );}}   And in my receiver file I have:   public class CountdownStarter { TextView mDisplay; public void onRecieve() {      final CountDownTimer aCounter = new CountDownTimer(Countdown.finalTime, 1000) {          public void onTick(long millisUntilFinished) {             mDisplay.setText("Seconds remaining: " + millisUntilFinished / 1000);         }          public void onFinish() {             mDisplay.setText("Finished");         }     };     aCounter.start(); } }   Right now, running the debugger I get this message:  E/AndroidRuntime: FATAL EXCEPTION: main               Process: com.example.android.timerexample, PID: 32276               java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference                   at android.content.ComponentName.&lt;init&gt;(ComponentName.java:128)                   at android.content.Intent.&lt;init&gt;(Intent.java:5283)                   at com.example.android.timerexample.Countdown$1.onClick(Countdown.java:42)                   at android.view.View.performClick(View.java:5702)                   at android.widget.TextView.performClick(TextView.java:10888)                   at android.view.View$PerformClick.run(View.java:22533)                   at android.os.Handler.handleCallback(Handler.java:739)                   at android.os.Handler.dispatchMessage(Handler.java:95)                   at android.os.Looper.loop(Looper.java:158)                   at android.app.ActivityThread.main(ActivityThread.java:7229)                   at java.lang.reflect.Method.invoke(Native Method)                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)   I was trying to look into it but I just don't understand why I am getting the NullPointerException or how to fix it - I am definitely doing some stuff wrong here but I can't figure out what the next step is. Any assistance would be very helpful!
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
78110
Is there any advantage of using     instead of  ?   As far as I can tell the following fragments are almost equivalent:  1. Semaphore  final Semaphore sem = new Semaphore(0); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         sem.release();       }     }   };   t.start(); }  sem.acquire(num_threads);   2: CountDownLatch  final CountDownLatch latch = new CountDownLatch(num_threads); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         latch.countDown();       }     }   };   t.start(); }  latch.await();   Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)  So in what situation might the latch be preferable?
47726
At the moment a default entry looks something like this:  Oct 12, 2008 9:45:18 AM myClassInfoHere INFO: MyLogMessageHere   How do I get it to do this?  Oct 12, 2008 9:45:18 AM myClassInfoHere - INFO: MyLogMessageHere   Clarification I'm using java.util.logging
67689
Is there a way to pass a parameter into a schedulable class execute method? We were trying to pass a string from another scheduled class into this scheduled class but it looks like we can't do that?  As quick context we have the scheduled date and time as a record in a custom object so we are trying to pass that info into our scheduled class.  global class MturkVSSchedule implements Schedulable{      global void execute(SchedulableContext SC, **String s**){   Putting String S throws a compile error. Is there a different way that I'm missing?
103564
I have the below If statements using some hard coded strings and I want to make them use as custom labels. I have created custom labels with the same String names as given below. So how can I make these statements to use the Custom Labels I created ?  if(monitoringFrequency == 'daily'){             return dateValue.addDays(1);         }else if(monitoringFrequency == 'weekly'){             return dateValue.addDays(7);         }else if(monitoringFrequency == 'monthly'){             return dateValue.addMonths(1);
116296
Anytime I have to handle dates/times in java it makes me sad   I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class.  "Exception in thread "main" java.lang.Error: Unresolved compilation problem:  The method setDate(int, Date) in the type PreparedStatement is not applicable for the arguments (int, Date)"  Eh WTF?  Here is the offending code.  for(int i = 0; i &lt; flights.size(); i++){      String[] details = flight[i].toString().split(":");      DateFormat formatter ;      formatter = new SimpleDateFormat("ddMMyyyy");     Date date = formatter.parse(details[1]);       PreparedStatement pstmt = conn.prepareStatement(insertsql);     pstmt.setString(1, details[0]);     pstmt.setDate(2, date);     pstmt.setString(3, details[2] + "00");     pstmt.setString(4, details[3]);     pstmt.setString(5, details[4]);     pstmt.setString(6, details[5]);     pstmt.setString(7, details[6]);     pstmt.setString(8, details[7]);     pstmt.setString(9, details[8]);     pstmt.executeUpdate();  }
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.
64159
I made a redstone clock that involves a command block with /testfor and a comparator attached to it. Whenever the /testfor works, the comparator turns on, but completely.(meaning it does not turn off after that) I want it to turn on, have a small delay, then turn off. is there some way that i should change this clock, or should I be doing something different with the comparator?
58610
This is a follow-up to .     When I click a link to an SE site in the Android app, it gives me an "open with" pop-up that has two options:         Chrome   Stack Exchange         I can then choose to open SE posts like this "Just once" or "Always."      The problem is that when I set the SE app to "always," and I click "open in browser,"   Except, the app crashes when trying to open it in browser.  LogCat (just right after selecting "Open in browser")  01-22 18:03:36.354: E/AndroidRuntime(16064): FATAL EXCEPTION: main 01-22 18:03:36.354: E/AndroidRuntime(16064): Process: com.stackexchange.marvin, PID: 16064 01-22 18:03:36.354: E/AndroidRuntime(16064): java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.stackexchange.marvin.utils.Helpers.getNonMarvinViewIntent(Helpers.java:452) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.stackexchange.marvin.ui.question.QuestionDialog$1.onClick(QuestionDialog.java:39) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1108) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AdapterView.performItemClick(AdapterView.java:310) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AbsListView.performItemClick(AbsListView.java:1145) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AbsListView$3.run(AbsListView.java:3903) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.os.Handler.handleCallback(Handler.java:739) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.os.Handler.dispatchMessage(Handler.java:95) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.os.Looper.loop(Looper.java:148) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.app.ActivityThread.main(ActivityThread.java:5417) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at java.lang.reflect.Method.invoke(Native Method) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)   I suspect it's related to , but not sure.  Specs:   Device model: Nexus 5 Android version: Android 6.0.1 SE app version: 1.0.82 (beta) Installed browser: Chrome 47.0.2526.83 (latest at current writing)
106358
Most of what I have read about retry operations is that they are vaguely complicated and indepth. I have written the code below which seems to accomplish this without too much confusion - I'm wondering if there are any pitfalls I am not seeing here.   The class uses a top-level schedulable class, which calls a queueable class to make the callout, and if the callout is unsuccessful, it just schedules the top level class again five minutes later. After testing it appears this works indefinitely.   A simple string token, assigned at the first invocation, is also passed between the classes, and I have tested and found that the token does persist, even when runs are scheduled for a later time.   Thanks for helpful thoughts!  public class SelfServe implements Schedulable {      public String Token = null;      public void execute(SchedulableContext ctx) {                  RetrieveMachineDetails Job = new RetrieveMachineDetails();             Job.Token = Token;             System.enqueueJob(Job);      }           public class RetrieveMachineDetails implements Queueable, Database.AllowsCallouts {          public String Token = null;          public void execute(QueueableContext context){                                            Http http = new Http();             HttpRequest request = new HttpRequest();                             request.setEndpoint('https://app.endpoint.com/api');                     request.setMethod('POST');                     request.setHeader('Content-Type', 'application/json;charset=UTF-8');                                      request.setBody('{"query":  "$message_=\'METRIC\' &amp;&amp; $tier=\'customer\' "}');                                                                                                                                                                                    HttpResponse response = http.send(request);                            if (response.getStatusCode() == 200) {                 //do stuff                  }              else { //retry                  DateTime Dt = system.now().addMinutes(5);                                String day = string.valueOf(Dt.day());                                        String month = string.valueOf(Dt.month());                                          String hour = string.valueOf(Dt.hour());                                       String minute = string.valueOf(Dt.minute());                                                       String year = string.valueOf(Dt.year());                                   String ScheduledTime = '0 ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ?' + ' ' + year;                  SelfServe Job = new SelfServe();                     Job.Token = Token;                 System.schedule('SelfServe Job'+Dt, ScheduledTime, Job);              }         }        }  }
113519
I'm having a save method with several Conditions in it.Here is my apex class  invoiceset = [select SiteUrl__c, Prefix__c,Seperator__c,Seperator1__c,DateValue__c,DateValue1__c,Date_Format__c,Incrementer__c,Counter_Val1__c,counter__c from Invoice_setting__c limit 1];        if(invoiceSet[0].DateValue__c == 'Date' &amp;&amp; invoiceSet[0].DateValue1__c == 'Date'){         if(invoiceSet[0].Date_Format__c == 'dd-mm-yyyy'){              datenow = DateTime.now().format('dd-MM-yyyy');                   }else if(invoiceSet[0].Date_Format__c == 'MM-dd-yyyy'){              datenow = DateTime.now().format('MM-dd-yyyy');                     }else if(invoiceSet[0].Date_Format__c == 'dd/MM/yyyy'){              datenow = DateTime.now().format('dd/MM/yyyy');          }else if(invoiceSet[0].Date_Format__c == 'mm/dd/yyyy'){              datenow = DateTime.now().format('mm/dd/yyyy');          }else if(invoiceSet[0].Date_Format__c == 'yy'){              datenow = DateTime.now().format('yy');          }else if(invoiceSet[0].Date_Format__c == 'yyyy'){              datenow = DateTime.now().format('yyyy');          }           prefixName = invoiceset[0].prefix__c + invoiceSet[0].seperator__c + datenow + invoiceset[0].Seperator1__c + datenow;       }      else if(invoiceSet[0].DateValue__c == 'Counter' &amp;&amp; invoiceSet[0].DateValue1__c == 'Counter'){       if(invoiceSet[0].counter_val1__c == null){          invoiceSet[0].Counter_Val1__c = invoiceset[0].Counter__c;        }else if(invoiceSet[0].Counter_Val1__c == invoiceset[0].Counter__c){            intt = integer.valueof(invoiceSet[0].Counter__c) + integer.valueOf(invoiceSet[0].Incrementer__c) ;            invoiceSet[0].Counter_Val1__c = string.valueOf(intt) ;        }else {             intt = integer.valueof(invoiceSet[0].Counter_Val1__c) + integer.valueOf(invoiceSet[0].Incrementer__c) ;            invoiceSet[0].Counter_Val1__c = string.valueOf(intt) ;        }        update invoiceset;         prefixName = invoiceset[0].prefix__c + invoiceSet[0].seperator__c + invoiceSet[0].Counter_Val1__c + invoiceset[0].Seperator1__c +invoiceset[0].Counter_Val1__c;       } &amp;&amp; so on........   Inorder to cover all this conditions should I write those many methods or any other easy way?  Here is my Test Code  public static testmethod void test(){    invoice_setting__c setng = new invoice_setting__c(Name='Invoice Settings',SiteUrl__c='www.google.com',Prefix__c='Test',Seperator__c = '-',dateValue__c = 'Date',Seperator1__c = '/',dateValue1__c = 'Date',date_format__c='dd-mm-yyyy');     insert setng; } public static testmethod void test1(){     invoice_setting__c setng1 = new invoice_setting__c(Name='Invoice Settings',Prefix__c='Test',Seperator__c = '-',dateValue__c = 'Counter',Seperator1__c = '/',Counter_Val1__c=null,dateValue1__c = 'Counter',date_format__c='dd-mm-yyyy',Incrementer__c='10');     insert setng1; } &amp; so on......   Any Suggestions for this please
103713
Trying to create an alarm of sorts.  Task runs fine, computer wakes up from sleep fine, but the screen's black till there's user input. Anyway I can get the screen to light up upon waking?
87780
I have a legacy WinForms Mdi App in VB.Net 2.0 which I am adding functionality to. One of the additions is a warning which needs to be raised when the current time nears a specified value (a deadline). My intention is to check the time once an hour until there is less than an hour until the deadline, then display warnings at specified intervals until the time's up.  The user needs to be able to continue to use the app up to and even after the deadline, but they need to periodically be made aware of the deadline's proximity.   The app does not use System.Threading yet and my knowledge of it is limited at this time. I do know that there are 3 different Timer() methods available:    System.Threading.Timer(), Windows.Forms.Timer() and  System.Timers.Timer()   My question is, which is the best way to go with this? I attempted to use the threaded timer, but since WinForms are not thread safe I got a run time error trying to access another class. Is it worth making the class/form thread safe? Am I completely off track?  Thanks.
68352
I read some information about Java layout managers and the recommendation was . My problem is, that I didn't found any tutorial or easy step-by-step documentation.  So I want to know how this all works, but I don't know how.  Hope, it's not to trivial.  Thanks in advance, guerda
31292
In using the Android app for the first time today, I quickly discovered several things that I would like to suggest for improvement.  Being a dedicated SOer and dutiful alpha tester, I tried to use the Android app to post these questions here to Meta.  Which leads me to this question. I composed my second question and hit "preview", to be greeted with:     A creation of question can only be performed once every 900 seconds   Aside from the grammer [sic], the 900 second timeout seems rather long -- 15 minutes.  Can this be reduced, perhaps based on rep?
57448
So, I've been spending considerable more time on SO recently than I normally have, and one thing that I've noticed is quite a few people saying stuff like "There's a Null Pointer Error in this block of code, please help me fix it", with a huge amount of code posted, and no real clue as to where the NPE is. So my question is, what can we do to accomplish 2 goals?   Help the person asking the question become a better programmer. Help them to solve their problems.
31170
i am instantiating prefab cars ... the clones had a random countdown timer with each one off them and its working very well but the its not  decreasing its not counting down the timer is inside the spawn method the spawn method is inside the WHILE loop and the while loop is inside the UpDate() ... i  tried  to move the countdown to Update() but didnn't worked ... any ideas ...Thank You!  void Update() {     p -= Time.deltaTime;           while (carNumber &lt; cars &amp;&amp; p &lt;= 0 )         {              SpawnCars();             print(carNumber);             p = 5;                    }  }   and this is the spawn method:   public void SpawnCars() {     if (spawnAllowed)     {         // choose a random strat point 1/6              randomSpawnPoint = Random.Range(0, spawnPoints.Length);         // choose a random car 1/6         randomSpawnCars = Random.Range(0, Cars.Length);         // clone randomly a car(1/6) from a random pre_set-points(1/6)         GameObject obj = Instantiate(Cars[randomSpawnCars], spawnPoints[randomSpawnPoint].position, Quaternion.Euler(-90, 180, 0)) as GameObject;         // carNumber will count how many cloned car          carNumber++;         // destroy the  cloned car after N sec        // Destroy(obj, 8);         // every cloned car will take a tag with it         obj.gameObject.tag = "select" + k;         k++;         rcf = obj.GetComponent&lt;RayCastForward&gt;();         //textCDT         time = Random.Range(4f, time);         TextMesh txt = FindObjectOfType&lt;TextMesh&gt;();   //the Timer:         time -= Time.deltaTime;         coolDown = time.ToString("0");         txt.text = ""+coolDown;      } }   edit: i forgot to tell that the timer  is inside SpawnCars().