android - Activity crashes if GPS not on, possible to use COARSE_LOCATION if GPS unavailable? -


at moment when load activity gps turned off on device crashes application.

how go fixing this?

if possible amazing if gps turned off instead use coarse_location, not sure how easy be.

any hugely appreciated, code below:

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 activity first created. */     @override     public void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.sunrisesunset);         // show button in action bar.                 setupactionbar();          //setting onclicklistener calculate sunrise/sunset button         findviewbyid(r.id.calculatesunrisesunset).setonclicklistener(this);          //sets locationmanager enable gps data accessed.         lm = (locationmanager) getsystemservice(context.location_service);         lm.requestlocationupdates(locationmanager.gps_provider, 1000, 1,                 new mylocationlistener());          //declares latitude , longitude textviews         latcoord = (textview) findviewbyid(r.id.latcoord);         longcoord = (textview) findviewbyid(r.id.longcoord);          //declares location spinner/dropdown         addlisteneronspinneritemselection();          //date shit         = 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 {@link android.app.actionbar}.      */     private void setupactionbar() {          getactionbar().setdisplayhomeasupenabled(true);      }      // more date shit     @suppresslint("committransaction")     public void showdialog() {           fragmenttransaction ft = getfragmentmanager().begintransaction(); //get 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 listener between date dialog fragment , activity update 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 cities in 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         // called find current location based on gps data , sends         // these values longcoord , 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<void, void, string> {         //reads in web service         protected string getasciicontentfromentity(httpentity entity)                 throws illegalstateexception, ioexception {             inputstream in = entity.getcontent();             stringbuffer out = new stringbuffer();             int n = 1;             while (n > 0) {                 byte[] b = new byte[4096];                 n = in.read(b);                 if (n > 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 , adds 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 sunrise , sunset values , 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);     }  } 

thank looking

edit:

logcat output requested:

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 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):    @ richgrundy.learnphotography.sunrisesunset.showcurrentlocation(sunrisesunset.java:148) 04-19 11:45:10.225: e/androidruntime(29691):    @ richgrundy.learnphotography.locationonitemselectedlistener.onitemselected(locationonitemselectedlistener.java:20) 04-19 11:45:10.225: e/androidruntime(29691):    @ android.widget.adapterview.fireonselected(adapterview.java:892) 04-19 11:45:10.225: e/androidruntime(29691):    @ android.widget.adapterview.access$200(adapterview.java:49) 04-19 11:45:10.225: e/androidruntime(29691):    @ android.widget.adapterview$selectionnotifier.run(adapterview.java:860) 04-19 11:45:10.225: e/androidruntime(29691):    @ android.os.handler.handlecallback(handler.java:725) 04-19 11:45:10.225: e/androidruntime(29691):    @ android.os.handler.dispatchmessage(handler.java:92) 04-19 11:45:10.225: e/androidruntime(29691):    @ android.os.looper.loop(looper.java:137) 04-19 11:45:10.225: e/androidruntime(29691):    @ android.app.activitythread.main(activitythread.java:5041) 04-19 11:45:10.225: e/androidruntime(29691):    @ java.lang.reflect.method.invokenative(native method) 04-19 11:45:10.225: e/androidruntime(29691):    @ java.lang.reflect.method.invoke(method.java:511) 04-19 11:45:10.225: e/androidruntime(29691):    @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:793) 04-19 11:45:10.225: e/androidruntime(29691):    @ com.android.internal.os.zygoteinit.main(zygoteinit.java:560) 04-19 11:45:10.225: e/androidruntime(29691):    @ dalvik.system.nativestart.main(native method) 

edit:

is because i'm calling gps_provider here:

protected void showcurrentlocation() {         // todo auto-generated method stub         // called find current location based on gps data , sends         // these values longcoord , 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));     } 

any provider can unavailable. before requesting update check

if (lm.isproviderenabled(locationmanager.gps_provider)) {     lm.requestlocationupdates(locationmanager.gps_provider, 1000, 1,             new mylocationlistener()); } else if (lm.isproviderenabled(locationmanager.network_provider)) {     lm.requestlocationupdates(locationmanager.network_provider, 1000, 1,             new mylocationlistener()); } 

also locationmanager might unavailable (devices or firmwares without location features). check null also. hardly understand goals, see this

private boolean pending;  private locationlistener listener; private locationmanager lm;  @override protected void oncreate(bundle state) {     //your stuff     listener = new mylocationlistener(); }  @override protected void onpostcreate(bundle state) {     super.onpostcreate(state);     if (lm != null) {         requestlocation();     } }   private void requestlocation() {      if (!pending) {          if (lm.isproviderenabled(locationmanager.gps_provider)) {             lm.requestlocationupdates(locationmanager.gps_provider, 1000, 1,                     listener);             pending = true;         } else if (lm.isproviderenabled(locationmanager.network_provider)) {             lm.requestlocationupdates(locationmanager.network_provider, 1000, 1,                     listener);             pending = true;         }      } }  @override protected void ondestroy() {     super.ondestroy();     if (pending) {         lm.removeupdates();     } } 

edit showcurrentlocation:

protected void showcurrentlocation() {     // these values longcoord , latcoord textviews     location location = lm             .getlastknownlocation(locationmanager.gps_provider);     if (location != null) {         latitude = location.getlatitude();         longitude = location.getlongitude();          longcoord.settext(double.tostring(longitude));         latcoord.settext(double.tostring(latitude));     } } 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -