Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6203473
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T04:55:24+00:00 2026-05-24T04:55:24+00:00

I’m using this script by Fedor but I want a little difference: When both

  • 0

I’m using this script by Fedor but I want a little difference: When both GPS and Network Provider is unavailable, I want to app to return null or “unknown” string. I modified the script, but when I run, it force closes, the logcat says:

enter image description here

I have the following codes:

MyLocation.java

package com.example.GetALocation2;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);

        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 20000);

        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             /*
             Location net_loc=null, gps_loc=null;


             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);


             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             */

             locationResult.gotLocation( null );
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

GetALocation2.java

package com.example.GetALocation2;

import com.example.GetALocation2.MyLocation.LocationResult;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class GetALocation2 extends Activity {

    Double latitude;
    TextView tv;
    MyLocation myLocation = new MyLocation();


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "This is the start!", Toast.LENGTH_SHORT).show();
        locationClick();
    }


    private void locationClick() {
        myLocation.getLocation(this, locationResult);
    }

    public LocationResult locationResult = new LocationResult(){
        @Override
        public void gotLocation(final Location location){
            //Got the location!

                if( location == null ){
                    Toast.makeText(getBaseContext(), "Location is unknown.", Toast.LENGTH_SHORT).show();
                }else{
                    GetALocation2.this.latitude = location.getLatitude();
                    Toast.makeText(getBaseContext(), "I got the location! >>> " + location.getLatitude(), Toast.LENGTH_SHORT).show();
                }
            };
    };

}

I’m kinda new to java and android, many thanks for any help! 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T04:55:25+00:00Added an answer on May 24, 2026 at 4:55 am

    Hope this helps:

    private LocationManager lm; 
    private LocationListener ll;
    public static String latitude;
    public static String longitude;
    double lat,lon;
    
    
      lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    
            if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
    //                      Toast.makeText(this,"GPS PROVIDER", Toast.LENGTH_LONG).show();
                ll = new GpsListener(); 
                //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0,ll);
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, ll);
    
            }else if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
    //              Toast.makeText(this,"NETWORK PROVIDER.", Toast.LENGTH_LONG).show();
                ll = new GpsListener();
                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,0, ll);
    
            }else{
                Toast.makeText(this,"GPS is disabled.", Toast.LENGTH_LONG).show();
                prog.dismiss();
            }
    

    Add the above code in your OnCreate method

    and out of the onCreate method create a following class

    private class GpsListener implements LocationListener 
     {
    
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            float acc=-1;
            if(location!=null) {
                Toast.makeText(HomeScreen.hs,"Location Found", Toast.LENGTH_LONG).show();
                System.out.println("IN IF PART");
    
                if(location.hasAccuracy())
                        acc = location.getAccuracy();
    
                lat = location.getLatitude();
                lon = location.getLongitude();
                isLocFound=true;
                latitude = Double.toString(lat);
                longitude = Double.toString(lon);
    
                System.out.println("1)"+acc+" 2) "+latitude+" 3) "+longitude);
    
                lm.removeUpdates(ll);
                lm = null;
    
                stopSelf();
                //stopForeground(true);
    
            }else{
                Toast.makeText(HomeScreen.hs,"No Location Found", Toast.LENGTH_LONG).show();
                System.out.println("IN ELSE PART..");
            }
    
            prog.dismiss();
        }
    
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
    
        }
    
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
    
        }
    
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
    
        }
    
    
    }//end of Class
    

    Hope this helpss

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I want to construct a data frame in an Rcpp function, but when I
I am using Paperclip to handle profile photo uploads in my app. They upload
I am writing an app with both english and french support. The app requests
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.