私はここで問題があり、私はそれを働かせることができません... 私は最新のGPS位置を取得したいが、すべて私はnullポインタの例外です。 ファーストクラスのGPSActivityでは動作しますが、2番目のSmsReceiverでは動作しません。Android locationManagerのヌルポインタ例外? (コンテキストを渡す方法?)
私は2番目のクラスにコンテキストを渡さなければならないかもしれないと私は読んでいますが、私はどのように知っているのですか...助けてください!
GPSActivity.class
:
ここでコード来る
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class GPSActivity extends Activity {
long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
long MINIMUM_TIME_BETWEEN_UPDATES = 10000; // in Milliseconds
LocationManager locationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.getAllProviders();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener());
}
public void showCurrentLocation() {
Location location =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Toast.makeText(GPSActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
}
(私は、コードを少し取り除い)
は今、私はshowCurrentLocationを呼び出すことができ、それが長いと緯度の値私をshowes。
どのように私はここにこれを行うことができます。
SmsReceive.class
(SMSを受信したときに、GPS座標を送信)
import ...
public class SmsReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
GPSActivity myGPS;
myGPS = new GPSActivity();
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null) {
//HERE I GET THE NULL POINTER EXCEPTION
Location loc =
myGPS.locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double varLong = loc.getLongitude();
double varLat = loc.getLatitude();
String locationData = "LONG: " + varLong+ " LAT: " + varLat;
Toast.makeText(context, locationData, Toast.LENGTH_SHORT).show();
}
}
}
感謝!