Activity crashes if GPS not on, possible to use COARSE_LOCATION if GPS unavailable?
<p>At the moment when I load this activity with the GPS turned off on the device it crashes the application. </p>

<p>How would I go about fixing this?</p>

<p>If possible it would also be amazing if the GPS was turned off to instead use the COARSE_LOCATION, not sure how easy that would be.</p>

<p>Any help would be hugely appreciated, code is below:</p>

<pre><code>public class SunriseSunset extends Activity implements OnClickListener {

    public Button getLocation;
    public Button setLocationJapan;
    public TextView LongCoord;
    public TextView LatCoord;
    public double longitude;
    public double latitude;
    public LocationManager lm;
    public Spinner Locationspinner;
    public DateDialogFragment frag;
    public Button date;
    public Calendar now;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sunrisesunset);
        // Show the Up button in the action bar.
                setupActionBar();

        //Setting onClickListener for Calculate Sunrise/Sunset Button
        findViewById(R.id.CalculateSunriseSunset).setOnClickListener(this);

        //Sets up LocationManager to enable GPS data to be accessed.
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
                new MyLocationListener());

        //Declares Latitude and Longitude TextViews
        LatCoord = (TextView) findViewById(R.id.LatCoord);
        LongCoord = (TextView) findViewById(R.id.LongCoord);

        //Declares for Location Spinner/Dropdown
        addListenerOnSpinnerItemSelection();

        //Date shit
        now = Calendar.getInstance();
        date = (Button)findViewById(R.id.date_button);
        date.setText(DateFormat.format("dd MMMM yyyy", Calendar.getInstance()));
        date.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog();
            }
        });

    }
    /**
     * Set up the {@link android.app.ActionBar}.
     */
    private void setupActionBar() {

        getActionBar().setDisplayHomeAsUpEnabled(true);

    }

    // More date shit
    @SuppressLint("CommitTransaction")
    public void showDialog() {  
        FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment   
        frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){      

        public void updateChangedDate(int year, int month, int day){                     
        now.set(year, month, day);
        date.setText(DateFormat.format("dd MMMM yyyy", now));             
        }  
          }, now);
        frag.show(ft, "DateDialogFragment");     }



    public interface DateDialogFragmentListener{
        //this interface is a listener between the Date Dialog fragment and the activity to update the buttons date
        public void updateChangedDate(int year, int month, int day);
    }

    public void addListenerOnSpinnerItemSelection() {
        Locationspinner = (Spinner) findViewById(R.id.Locationspinner);
        Locationspinner
                .setOnItemSelectedListener(new LocationOnItemSelectedListener(
                        this));
    }

    //Sets locations for all the cities in the spinner
    public void setLocationAuckland() {LatCoord.setText("-36.85248273");LongCoord.setText("174.76391734");}
    public void setLocationBuenoAires() {LatCoord.setText("-34.606358325");LongCoord.setText("-58.38727463");}
    public void setLocationCalgary() 

    protected void showCurrentLocation() {
        // TODO Auto-generated method stub
        // This is called to find current location based on GPS data and sends
        // these values to the LongCoord and LatCoord TextViews
        Location location = lm
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }

    @Override
    public void onClick(View arg0) {
        Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
        b.setClickable(false);
        new LongRunningGetIO().execute();
    }

    public class LongRunningGetIO extends AsyncTask&lt;Void, Void, String&gt; {
        //Reads in the web service
        protected String getASCIIContentFromEntity(HttpEntity entity)
                throws IllegalStateException, IOException {
            InputStream in = entity.getContent();
            StringBuffer out = new StringBuffer();
            int n = 1;
            while (n &gt; 0) {
                byte[] b = new byte[4096];
                n = in.read(b);
                if (n &gt; 0)
                    out.append(new String(b, 0, n));
            }
            return out.toString();
        }

        private final ProgressDialog dialog = new ProgressDialog(SunriseSunset.this);

        protected void onPreExecute() {
           this.dialog.setMessage("Calculating...");
           this.dialog.show();
        }

        @SuppressLint("SimpleDateFormat")
        @Override
        protected String doInBackground(Void... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();

            // Finds todays date and adds that into the URL in simple date format DD/MM
            SimpleDateFormat df = new SimpleDateFormat("dd/MM");
            String formattedDate = df.format(now.getTime());

            String finalURL = "http://www.earthtools.org/sun/"
                    + LatCoord.getText().toString().trim() + "/"
                    + LongCoord.getText().toString().trim() + "/"
                    + formattedDate + "/99/0";
            HttpGet httpGet = new HttpGet(finalURL);
            String text = null;

            try {
                HttpResponse response = httpClient.execute(httpGet,
                        localContext);
                HttpEntity entity = response.getEntity();
                text = getASCIIContentFromEntity(entity);
            } catch (Exception e) {
                return e.getLocalizedMessage();
            }
            return text;
        }

        protected void onPostExecute(String results) {
            //Closes dialog box onPostExecute
            if (this.dialog.isShowing()) {
                  this.dialog.dismiss();
               }
            //Finds TextViews for Sunrise and Sunset values and posts results
            if (results != null) {
                try {

                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                            .newInstance();
                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                    InputSource s = new InputSource(new StringReader(results));
                    Document doc = dBuilder.parse(s);
                    doc.getDocumentElement().normalize();
                    TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
                    TextView tvSunset = (TextView) findViewById(R.id.Sunset);
                    tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent());
                    tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
            b.setClickable(true);
        }
    }



    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home, menu);
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        //  preparation code here
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        if (item.getItemId() == R.id.LessonsTutorials) {
            startActivity(new Intent(this, Lessons.class));
        }
        if (item.getItemId() == R.id.PhotoTools) {
            startActivity(new Intent(this, Tools.class));
        }
        if (item.getItemId() == R.id.Glossary) {
            startActivity(new Intent(this, Glossary.class));
        }
        if (item.getItemId() == R.id.Help) {
            startActivity(new Intent(this, Help.class));
        }
        return super.onOptionsItemSelected(item);
    }

}
</code></pre>

<p>Thank you for looking</p>

<p><strong>EDIT:</strong></p>

<p>LogCat output as requested:</p>

<pre><code>04-19 11:45:06.211: I/Adreno200-EGL(29691): Build Date: 12/10/12 Mon
04-19 11:45:06.211: I/Adreno200-EGL(29691): Local Branch: 
04-19 11:45:06.211: I/Adreno200-EGL(29691): Remote Branch: m/partner-android/jb-mr1-dev
04-19 11:45:06.211: I/Adreno200-EGL(29691): Local Patches: NONE
04-19 11:45:06.211: I/Adreno200-EGL(29691): Reconstruct Branch: NOTHING
04-19 11:45:06.241: D/OpenGLRenderer(29691): Enabling debug mode 0
04-19 11:45:10.215: D/AndroidRuntime(29691): Shutting down VM
04-19 11:45:10.215: W/dalvikvm(29691): threadid=1: thread exiting with uncaught exception (group=0x414a1930)
04-19 11:45:10.225: E/AndroidRuntime(29691): FATAL EXCEPTION: main
04-19 11:45:10.225: E/AndroidRuntime(29691): java.lang.NullPointerException
04-19 11:45:10.225: E/AndroidRuntime(29691):    at richgrundy.learnphotography.SunriseSunset.showCurrentLocation(SunriseSunset.java:148)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at richgrundy.learnphotography.LocationOnItemSelectedListener.onItemSelected(LocationOnItemSelectedListener.java:20)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at android.widget.AdapterView.access$200(AdapterView.java:49)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at android.os.Handler.handleCallback(Handler.java:725)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at android.os.Looper.loop(Looper.java:137)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at android.app.ActivityThread.main(ActivityThread.java:5041)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at java.lang.reflect.Method.invokeNative(Native Method)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at java.lang.reflect.Method.invoke(Method.java:511)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-19 11:45:10.225: E/AndroidRuntime(29691):    at dalvik.system.NativeStart.main(Native Method)
</code></pre>

<p>EDIT:</p>

<p>Is it because I'm calling the GPS_PROVIDER here:</p>

<pre><code>protected void showCurrentLocation() {
        // TODO Auto-generated method stub
        // This is called to find current location based on GPS data and sends
        // these values to the LongCoord and LatCoord TextViews
        Location location = lm
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        LongCoord.setText(Double.toString(longitude));
        LatCoord.setText(Double.toString(latitude));
    }
</code></pre>
