Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Android Location

Options
  • 02-10-2012 10:29am
    #1
    Registered Users Posts: 8,324 ✭✭✭


    I've been banging my head against the wall with this!
    package cs4084.panic.button;
    
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.database.CursorJoiner.Result;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.media.MediaPlayer;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Toast;
    
    
    
    public class ConfirmScreen extends Activity{
    	
    	String mapCoord = "http://maps.google.com";
    	
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_confirm_screen);
        
           
            LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            LocationListener mLocListener = new MyLocationListener();
            mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, mLocListener);
            
            
            sendEmail();
            playSound();
            
        }
        
    
        public void backHome(View view) 
    	{
    		Intent intent = new Intent (this, MainScreen.class);
        	startActivity(intent);
    	}
        
        // Method to start playing and looping a sound.
        
        public void playSound()
        {
        	MediaPlayer clickSound = MediaPlayer.create(this, R.raw.warning);
        	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        	Boolean soundCheck = sp.getBoolean("SOUND", false);
        	if (soundCheck)
        	{
        		clickSound.start();
        	}
        		
        		
        		
        }// method end
        
        
        
        public void sendEmail()
        {
        	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        	String nameValue = sp.getString("NAME", "failed to get name");
        	String emailValue = sp.getString("EMAIL", "failed to get email");
        	Intent i = new Intent(Intent.ACTION_SEND);
        	i.setType("message/rfc822");
        	i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailValue});
        	i.putExtra(Intent.EXTRA_SUBJECT, "Email sent from DON'T PANIC - A Chris O'Brien Project");
        	i.putExtra(Intent.EXTRA_TEXT, "Hi there\n" + nameValue + " is in mortal danger. Please see the co-ords attached and run to their rescue!" +
        			" If you don't see any co-ords, they didn't check the box and assume you know where they are.\nKind Regards\nDon't Panic! \n\n\n" +  mapCoord);
        	
        	try
        	{	startActivity(Intent.createChooser(i, "Send mail...."));
        	} 
        	catch (android.content.ActivityNotFoundException ex){
        		
        		Toast.makeText(ConfirmScreen.this, "There are no email clients installed or set up", Toast.LENGTH_SHORT).show();
        	}
        }
     
        public class MyAsyncTask extends AsyncTask<Void, Void, Result>{
    
        	private Activity activity;
        	private ProgressDialog progressDialog;
    
        	private double longitude;
        	private double latitude;
        	private String countryCode;
    
        	public MyAsyncTask(Activity activity, double longitude, double latitude) {
        	    super();
        	    this.activity = activity;
        	    this.longitude = longitude;
        	    this.latitude = latitude;
        	}
    
        	@Override
        	protected void onPreExecute() {
        	    super.onPreExecute();
        	    ProgressDialog.show(activity, "", "Looking for GPS satellites...");
        	}
    
        	@Override
        	protected Result doInBackground(Void... v) {
        	    Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
        	    List<Address> addresses;
        	    try {
        	        addresses = geocoder.getFromLocation(latitude, longitude, 1);
        	        countryCode = addresses.get(0).getAddressLine(2);
        	    }catch (IOException e) {
        	        // TODO Auto-generated catch block
        	        e.printStackTrace();
        	        Toast.makeText(activity, "Location is not available, please try again later.", Toast.LENGTH_LONG).show();
        	    }
        	    if(countryCode==null){
        	        Toast.makeText(activity, "Location is not available, please try again later.", Toast.LENGTH_LONG).show();
        	    }
        	    Toast.makeText(activity, countryCode, Toast.LENGTH_LONG).show();
        	    return null;
        	}
    
        	@Override
        	protected void onPostExecute(Result result) {
        	    progressDialog.dismiss();
        	    Toast.makeText(activity.getApplicationContext(), "Finished.", 
        	    Toast.LENGTH_LONG).show();
        	}
        	}
        
        
        
        //Location Listener
        public class MyLocationListener implements LocationListener
        {
        	
    
    		@Override
    		public void onLocationChanged(Location location) {
    			double lng = location.getLatitude();
    			double lat = location.getLongitude();
    			MyAsyncTask task = new MyAsyncTask(ConfirmScreen.this, lng, lat);
    	        task.execute();
    	        Toast.makeText(getApplicationContext(), "Done :D", Toast.LENGTH_LONG).show();
    			
    			String text = "Current Location is \nLat: " + lng + " \nLng: " + lat;
    			mapCoord =  Double.toString(lng) + " " + Double.toString(lat);
    			
    			Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    			
    		}
    
    		@Override
    		public void onProviderDisabled(String provider) {
    			Toast.makeText(getApplicationContext(), "GPS Disabled", Toast.LENGTH_SHORT).show();
    		}
    
    		@Override
    		public void onProviderEnabled(String provider) {
    			Toast.makeText(getApplicationContext(), "GPS Enabled", Toast.LENGTH_SHORT).show();
    			
    		}
    
    		@Override
    		public void onStatusChanged(String provider, int status, Bundle extras) {
    			// TODO Auto-generated method stub
    			
    		}
    		
        	
        	
        	
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_confirm_screen, menu);
            return true;
        }
    
    	
    	
    
    	
    		
    	}
        
    

    Compiles with no errors but it doesn't do what I intend. I've been read others code and trying to implement onto my own but I'm probably messing up something.

    1) onCreate gets location
    2) A dialog box should pop up until GPS co-ords are received
    3) Those co-ords should be passed to a String
    4) An email is sent with the co-ords (this works fine)
    5) Sound plays if box checked (again this works)

    I was getting the co-ords but the difficulty was that the email method was being called before the app has the chance to get the co-ords. I don't want to use lastKnownCo-ords.


Comments

  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    I don't know java but it looks like it the results for the location are only updated on the onLocationChanged event.

    Possibly put the send email inside onLocationChanged


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    You should call the sendEmail method if/when MyAsyncTask.doInBackground successfully brings back coordinates.

    Alternatively try getting the location synchronously:
    LocationManager locationManager = 
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    
    double lat = location != null ? location.getLatitude() : 0;
    double lon = location != null ? location.getLongitude() : 0;
    


  • Registered Users Posts: 8,324 ✭✭✭chrislad


    That helped somewhat (as in the activity crashed but you could re-enter it and it would get the data, not ideal but at least it put me on the right track)

    I've done the following now, trying to get my head around async and background processes. The activity crashes though. It seems to crash at the creation of the async on onCreate.
    package cs4084.panic.button;
    
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.database.CursorJoiner.Result;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.media.MediaPlayer;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Toast;
    
    
    
    public class ConfirmScreen extends Activity{
    	
    	ProgressDialog progressDialog;
    	double longitude, latitude;
    	Location location;
    
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
     
    
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
     
    
        protected LocationManager locationManager;
    
    	
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_confirm_screen);
        	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        	Boolean locationCheck = sp.getBoolean("LOCATION", false);
          if(locationCheck){
        	   	GPSLocation task = new GPSLocation();
        	   	task.execute();
           	}
           else
           {
            sendEmail();
            playSound();
           }
            
        }
        
        public double getLatitude()
        {
        	if (location != null)
        	{
        		latitude = location.getLatitude();
        	}
        	
        	return latitude;
        }
        
        public double getLongitude()
        {
        	if (location !=  null)
        	{
        		longitude = location.getLongitude();
        	}
        	return longitude;
        }
        
        public class GPSLocation extends AsyncTask<Void, Void, Void> implements LocationListener
        {  
            boolean running =true;
                    @Override
                    protected void onPreExecute()
                    {  
                        super.onPreExecute(); 
                        progressDialog = new ProgressDialog(ConfirmScreen.this);
                        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
                              public void onCancel(DialogInterface dialog) {
                                  //getgps.cancel(true);  
                              }
                        });
                        
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            		if (location != null) {
                            				latitude = location.getLatitude();
                            				longitude = location.getLongitude();  
                            				progressDialog.setCancelable(true);
                            				progressDialog.setMessage("Getting GPS Location...");
                            				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                            				progressDialog.setProgress(1);
                            				progressDialog.show();
                            		}
                        }
    
                    } 
    
                    @Override 
                    protected void onProgressUpdate(Void... values) {
                        super.onProgressUpdate(values);
                        // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
                     }
    
                    @Override 
                    protected void onPostExecute(Void result)
                    {  
                            progressDialog.cancel(); 
                            sendEmail("GPS: ", Double.toString(longitude).trim(), Double.toString(latitude).trim());
                    }
    
                    @Override
                    protected Void doInBackground(Void... params) {  
                        boolean isDataSubmitted = false;
    
                        while(!isDataSubmitted)
                        {  
                            if(longitude !=0 && latitude!=0)
                            { 
                            	sendEmail(); //Send Email without co-ords
                                isDataSubmitted = true;  
                            }  
                        } 
    
                        return null;    
                    }
    
    				@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
    					
    				} 
         } 
        
    
        public void backHome(View view) 
    	{
    		Intent intent = new Intent (this, MainScreen.class);
        	startActivity(intent);
    	}
        
        // Method to start playing and looping a sound.
        
        public void playSound()
        {
        	MediaPlayer clickSound = MediaPlayer.create(this, R.raw.warning);
        	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        	Boolean soundCheck = sp.getBoolean("SOUND", false);
        	if (soundCheck)
        	{
        		clickSound.start();
        	}
        		
        		
        		
        }// method end
        
        public void sendEmail()
        {
        	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        	String nameValue = sp.getString("NAME", "failed to get name");
        	String emailValue = sp.getString("EMAIL", "failed to get email");
        	Intent i = new Intent(Intent.ACTION_SEND);
        	i.setType("message/rfc822");
        	i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailValue});
        	i.putExtra(Intent.EXTRA_SUBJECT, "Email sent from DON'T PANIC - A Chris O'Brien Project");
        	i.putExtra(Intent.EXTRA_TEXT, "Hi there\n" + nameValue + " is in mortal danger. They didn't include co-ords as they assume you know where they are..\nKind Regards\nDon't Panic! \n\n\n");
        	
        	try
        	{	startActivity(Intent.createChooser(i, "Send mail...."));
        	} 
        	catch (android.content.ActivityNotFoundException ex){
        		
        		Toast.makeText(ConfirmScreen.this, "There are no email clients installed or set up", Toast.LENGTH_SHORT).show();
        	}
        }
     
        
        public void sendEmail(String a, String b, String c)
        {
        	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        	String nameValue = sp.getString("NAME", "failed to get name");
        	String emailValue = sp.getString("EMAIL", "failed to get email");
        	Intent i = new Intent(Intent.ACTION_SEND);
        	i.setType("message/rfc822");
        	i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailValue});
        	i.putExtra(Intent.EXTRA_SUBJECT, "Email sent from DON'T PANIC - A Chris O'Brien Project");
        	i.putExtra(Intent.EXTRA_TEXT, "Hi there\n" + nameValue + " is in mortal danger. Please see the co-ords attached and run to their rescue!" +
        			" If you don't see any co-ords, they didn't check the box and assume you know where they are.\nKind Regards\nDon't Panic! \n\n\n" + 
        			a + b + c);
        	
        	try
        	{	startActivity(Intent.createChooser(i, "Send mail...."));
        	} 
        	catch (android.content.ActivityNotFoundException ex){
        		
        		Toast.makeText(ConfirmScreen.this, "There are no email clients installed or set up", Toast.LENGTH_SHORT).show();
        	}
        }
     
       
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_confirm_screen, menu);
            return true;
        }
    
    	
    	
    
    	
    		
    	}
        
     
     
      
    

    LogCat
    10-02 22:35:56.595: W/dalvikvm(2523): threadid=1: thread exiting with uncaught exception (group=0x41d77300)
    10-02 22:35:56.600: E/AndroidRuntime(2523): FATAL EXCEPTION: main
    10-02 22:35:56.600: E/AndroidRuntime(2523): java.lang.RuntimeException: Unable to start activity ComponentInfo{cs4084.panic.button/cs4084.panic.button.ConfirmScreen}: java.lang.NullPointerException
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.ActivityThread.access$600(ActivityThread.java:140)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.os.Handler.dispatchMessage(Handler.java:99)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.os.Looper.loop(Looper.java:137)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.ActivityThread.main(ActivityThread.java:4898)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at java.lang.reflect.Method.invokeNative(Native Method)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at java.lang.reflect.Method.invoke(Method.java:511)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at dalvik.system.NativeStart.main(Native Method)
    10-02 22:35:56.600: E/AndroidRuntime(2523): Caused by: java.lang.NullPointerException
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at cs4084.panic.button.ConfirmScreen$GPSLocation.onPreExecute(ConfirmScreen.java:97)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.os.AsyncTask.execute(AsyncTask.java:534)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at cs4084.panic.button.ConfirmScreen.onCreate(ConfirmScreen.java:54)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.Activity.performCreate(Activity.java:5184)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
    10-02 22:35:56.600: E/AndroidRuntime(2523): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
    


  • Registered Users Posts: 8,324 ✭✭✭chrislad


    Got it working! Hadn't initialised LocationManager!


Advertisement