2016-05-03 3 views
0

Помощь! Это мое первое приложение за пределами простого курса Udacity, пожалуйста, будьте добрыми.Сбой я подозреваю с onLocationChanged не знаю, что ошибка

Я хочу gps точно один раз. Пользователю моего приложения не понадобятся обновления gps. Тем не менее, я считаю, что мне нужен прослушиватель onLocationChanged, чтобы получить точное чтение gps.

Он падает. В MainActivity он может попасть во второй тост после вызова класса MyLocationListener. Который предположил бы ошибку в GetGPS от MainActivity. Но я не вижу, где. Предполагаю, что слушатель позволяет MainActivity продолжать, пока он ищет GPS?

GPS на моем телефоне работает Я загрузил приложение для тестеров. Я выгляжу, хотя, оставляя дом на своих Y-фронтах.

Вот трассировка стека от crashalytics.

http://crashes.to/s/54d65de993b

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference 
    at android.widget.Toast.<init>(Toast.java:101) 
    at android.widget.Toast.makeText(Toast.java:258) 
    at com.example.android.carfinder.MyLocationListener.onLocationChanged(MyLocationListener.java:28) 
    at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:281) 
    at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:210) 
    at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:226) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Method.java) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

Так вопросы,

1. what's causing the crash? 
    2. When I've got a gps, how do I turn the listener off, till the button is re-pressed? 
    3. Why doesn't progressDialog show while it searches for gps? 

MainActivity, getGPS активируется с событием OnClick:

public void getGPS(View view) { 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    getSystemService(Context.LOCATION_SERVICE); 

    if(displayGpsStatus() == false) { 
     Log.i("getGPS", "GPS turned off"); 
     return; 
    } 
    // GPS is working 
    //progressBar.setVisibility(View.VISIBLE); 
    ProgressDialog progressDialog = ProgressDialog.show(this, "Getting GPS lock", "Not much longer love"); 

    Log.i("getGPS", "trying for new co-ords"); 
    LocationListener locationListener = new MyLocationListener(); 
    try { 
     Toast.makeText(this, "activating locationListener", Toast.LENGTH_SHORT).show(); 
     locationManager.requestLocationUpdates(
       LocationManager.GPS_PROVIDER, 0, 0, locationListener); //5000, 10 
     Log.i("getGPS", "just returned from MyLocationListener Class"); 
    } 
    catch (SecurityException e) { 
     Log.i("getGPS", "no permission to use GPS"); 
     progressBar.setVisibility(View.GONE); 
     Toast.makeText(this, "Did you block GPS permission on install?", Toast.LENGTH_LONG).show(); 
     progressDialog.dismiss(); 
     return; 
    } 
    Toast.makeText(this, "continuing, is address and time updated?", Toast.LENGTH_LONG).show(); 
    // Got GPS so hide the progress bar 
    //progressBar.setVisibility(View.GONE); 
    progressDialog.dismiss(); 

    // update the date and address views 
    //saveDateTime(); 
    //updateAddressView(); 
    return; 
} 

MyLocationListener:

public class MyLocationListener extends MainActivity implements LocationListener { 
    String TAG = "MyLocationListener Class"; 

@Override 
public void onLocationChanged(Location loc) { 
    Log.i("onLocationChanged", "in outside class"); 

    Toast.makeText(
      getBaseContext(), 
      "Location changed: Lat: " + loc.getLatitude() + " Lng: " 
        + loc.getLongitude(), Toast.LENGTH_SHORT).show(); 
    String longitude = "Longitude: " + loc.getLongitude(); 
    Log.i(TAG, longitude); 
    String latitude = "Latitude: " + loc.getLatitude(); 
    Log.i(TAG, latitude); 
    // TODO need to check latitude and longitude accessible from MainActivity 

    /*------- To get city name from coordinates -------- */ 
    // from here we're reverse geo-coding to get the address 
    String address = null; 
    String city = null; 
    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault()); 
    List<Address> addresses; 
    try { 
     addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); 
     if (addresses.size() > 0) { 
      //System.out.println(addresses.get(0).getLocality()); 
      address = addresses.get(0).getAddressLine(0); 
      city = addresses.get(0).getLocality(); 
     } 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
     Log.i("MyLocationListener", "No address found"); 
    } 
    String savedAddress = address + ", " + city; 
    if(address == null && city == null) { 
     savedAddress = "couldn't fathom address, tap view on map to check"; 
    } 
    TextView addressTextView = (TextView) findViewById(R.id.approxAddress); 
    addressTextView.setText(savedAddress); 
    // save it to permanent memory 
    SharedPreferences.Editor mEditor = mPrefs.edit(); 
    mEditor.putString("savedAddress", savedAddress).apply(); 
    mEditor.putString("savedLongitude", longitude).apply(); 
    mEditor.putString("savedLatitude", latitude).apply(); 

    Log.i("MyLocationListener", "SAVED address, gps: "); 
} 

@Override 
public void onProviderDisabled(String provider) { 
    Toast.makeText(getBaseContext(), "MyLocListener: GPS disabled DOH!", Toast.LENGTH_LONG).show(); 
} 

@Override 
public void onProviderEnabled(String provider) { 
    Toast.makeText(getBaseContext(), "MyLocListener: GPS enabled :)", Toast.LENGTH_LONG).show(); 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    Toast.makeText(getBaseContext(), "MyLocListener: GPS status changed?", Toast.LENGTH_LONG).show(); 
} 
} 
+1

Что такое журнал аварий? – Nathanael

+0

где инициализация вашего progressBar? – Opiatefuchs

+0

Как я могу получить журнал аварий? Мой компьютер не может покинуть дом, поэтому я не могу запустить свой телефон, подключенный к моему отладчику. Я проиндексировал progressBar в onCreate. Я изменил его на ProgressDialog, потому что это позволяет избежать возиться с xml, просто плавает сверху. Но это не показывает, grrr. –

ответ

1

Ошибка происходит от звонка до Toast.makeText. Я предполагаю, что вы пытаетесь использовать Toast (и вместе с ним getBaseContext) перед созданием Activity. Контекст пока не существует.

Попробуйте заменить свои звонки Toast.makeText по телефонам Log.i. Если это избавится от ошибки, и вам нужен Toast, просто проверьте контекст, чтобы он не был пустым, прежде чем вы вызовете Toast.makeText.

+1

Может быть, хорошая идея создать конструктор в MyLocationListener, где вы можете передать по параметру контекст базы приложений, чтобы убедиться, что использует правильный контекст. –

+0

Эй, ребята, это отличные предложения. Да, это определенно getBaseContext(). Я удалил все тосты, но при создании объекта геокодирования «Geocoder gcd = new Geocoder (this.getBaseContext(), Locale.getDefault()) оставил один вызов getBaseContext.». Я попытался передать в контексте конструктору, но когда я пытаюсь создать объект MyLocationListener, он не любит «new MyLocationListener (this)»; или любые варианты, такие как «getApplicationContext()». Grrrr. Я думаю, мне нужно больше узнать. Спасибо за вашу помощь :) –

Смежные вопросы