Java 当意图将变量传递给另一个活动时,应用程序崩溃

Java 当意图将变量传递给另一个活动时,应用程序崩溃,java,android,android-intent,android-activity,Java,Android,Android Intent,Android Activity,我正在制作一个应用程序,跟踪用户和另一个用户,从理论上讲,这将是一个动物。 我的应用程序是这样的,你注册一个用户名并通过,然后当注册完成后,用户可以通过重新输入正确的用户名和密码登录地图。这就是问题的起点。 创建屏幕后,地图加载用户当前位置,并自动向动物手机发送短信以请求gps详细信息,然后发送回2条短信,1条包含gps信息。我有一个SmsReceiver类,它读取这些信息并提取经度和纬度数据,将其转换为double,然后将其传递给map活动,以转换为lnglat变量,并在google地图上显示

我正在制作一个应用程序,跟踪用户和另一个用户,从理论上讲,这将是一个动物。 我的应用程序是这样的,你注册一个用户名并通过,然后当注册完成后,用户可以通过重新输入正确的用户名和密码登录地图。这就是问题的起点。 创建屏幕后,地图加载用户当前位置,并自动向动物手机发送短信以请求gps详细信息,然后发送回2条短信,1条包含gps信息。我有一个SmsReceiver类,它读取这些信息并提取经度和纬度数据,将其转换为double,然后将其传递给map活动,以转换为lnglat变量,并在google地图上显示一个标记。现在我遇到的问题是,sms返回gps信息可能需要几分钟,当完成此操作并使用意图将坐标发送到地图页面时,必须单击一个按钮,以便将经度和纬度合并到动物坐标中,并显示标记,但是,由于存在时间间隔,在检索sms的同时按下按钮是不可能的,当数据从smsreceiver类发送到另一端的nothing时,它会导致崩溃,如果我从onclick方法中去掉了意图,同样的事情会发生,但相反,地图运行着意图,但信息还没有出现,它崩溃了。 任何帮助都将不胜感激,因为这是一场噩梦

我也很抱歉,如果我的解释过于复杂,我想确保它是解释的最好的我可以。 下面是这两个类的代码

Map class

public class MainScreen extends FragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private String provider;
final Context context = this;



   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_screen);
    map = ((SupportMapFragment)getSupportFragmentManager().
    findFragmentById(R.id.map)).getMap();

    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabledGPS = service
            .isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean enabledWiFi = service
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    // Check if enabled and if not send user to the GSP settings
    if (!enabledGPS) {
        Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    // Initialize the location fields
    if (location != null) {
        Toast.makeText(this, "Selected Provider " + provider,
                Toast.LENGTH_SHORT).show();
        onLocationChanged(location);
    } else {

        //do something
    }
    // Sets the map type to be "hybrid"
    map.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    Bundle b = getIntent().getExtras();


    double lat =  location.getLatitude();
    double lng = location.getLongitude();
    Toast.makeText(this, "Location " + lat+","+lng,
            Toast.LENGTH_LONG).show();
    LatLng Usercoordinate = new LatLng(lat, lng);
    Marker User = map.addMarker(new MarkerOptions()
    .position(Usercoordinate)
    .title("You are here")
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
    //Move the camera instantly to user with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(Usercoordinate, 15));

    // Zoom in, animating the camera.
    map.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);

    //Sends sms to 'animal phone'
      String phoneNo = "***********";
      String sms = "GPSLocation";

      try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, sms, null, null);
        Toast.makeText(getApplicationContext(), "SMS Sent!",
                    Toast.LENGTH_LONG).show();
      } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
            "SMS faild, please try again later!",
            Toast.LENGTH_LONG).show();
        e.printStackTrace();
      }

    }

public void map_help(View view) {
    //method for the help button

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);

        // set title
        alertDialogBuilder.setTitle("Help");

        // set dialog message
        alertDialogBuilder
     .setMessage("Click the 'Pet' button to display the pets location." +
                    "This can take a few minutes to retrieve.")
            .setCancelable(false)
    .setPositiveButton("ok",new   DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog,int id)        {
                    // if this button is clicked, close
                    // current activity
                    dialog.cancel();
                }
              });
            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
                                };

public void Find_Pet(View view)
{

      //String phoneNo = "07516909014";
     // String sms = "GPSLocation";

     // try {
    //  SmsManager smsManager = SmsManager.getDefault();
        //smsManager.sendTextMessage(phoneNo, null, sms, null, null);
        //Toast.makeText(getApplicationContext(), "SMS Sent!",
            //      Toast.LENGTH_LONG).show();
//    } catch (Exception e) {
    //  Toast.makeText(getApplicationContext(),
        //  "SMS faild, please try again later!",
            //Toast.LENGTH_LONG).show();
    //  e.printStackTrace();
      //}
}

public void Show_Pet(View view)
{
    //gets coordinates from SmsReceiver
    Bundle b = getIntent().getExtras();
    double AnimalLat = b.getDouble("key");

    Bundle d = getIntent().getExtras();
    double AnimalLon = d.getDouble("key1");

    LatLng Animalcoordinate = new LatLng(AnimalLat, AnimalLon);
    //adds pets marker on map
    Marker Animal = map.addMarker(new MarkerOptions()
    .position(Animalcoordinate)
    .title("Your pet is here")
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
}


/* Request updates at startup */
@Override
protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, this);
}

/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {


}


@Override
public void onProviderDisabled(String provider) {
    Toast.makeText(this, "Enabled new provider " + provider,
            Toast.LENGTH_SHORT).show();

}


@Override
public void onProviderEnabled(String provider) {
    Toast.makeText(this, "Disabled provider " + provider,
            Toast.LENGTH_SHORT).show();

}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}
SmsReceiver类

public class SmsReceiver extends BroadcastReceiver
{
String lat = null;
String lon = null;
String message = null;
final SmsReceiver context = this;

@Override
public void onReceive(Context context, Intent intent) 
{
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();        
    SmsMessage[] msgs = null;
    String str = "";            
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];            
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
            str += msgs[i].getMessageBody().toString();

        }}

            message = str.toString();
            String[] test = message.split("");
            char[] test2 = test[1].toCharArray(); 
            //if the first character of the sms is C then read gps information
            if (test2[0] == 'C' || test2[0] =='c')
            {
            lat = message.substring(45, 56);
            lon = message.substring(67, 78);

            double AnimalLat=Double.parseDouble(lat);
            double AnimalLon=Double.parseDouble(lon);

            //Pass coordinates to MainScreen
            Intent a = new Intent(getApplicationContext(), MainScreen.class);
            Bundle b = new Bundle();
            b.putDouble("key", AnimalLat);
            a.putExtras(b);
            startActivity(a);

            Intent c = new Intent(getApplicationContext(), MainScreen.class);
            Bundle d = new Bundle();
            d.putDouble("key1", AnimalLon);
            c.putExtras(d);
            startActivity(c);

            }else {
            }       

   }

private void startActivity(Intent a) {
    // TODO Auto-generated method stub

}

private Context getApplicationContext() {
    // TODO Auto-generated method stub
    return null;
}}
我还想为代码的布局道歉,这是我第一次在这个网站上粘贴代码。
再次感谢。

老实说,我不知道你在说哪个按钮。我唯一看到的是AlertDialog,除非我错过了什么。无论如何,您可以禁用按钮,直到任何数据都有值为止,或者,如果onClick为null,则您不能在onClick中执行任何操作


如果你需要更多的澄清,那么请在代码中注明你正在谈论的数据和按钮,但我认为你明白了

这是一个很大的问题,但你不能禁用按钮,直到任何对象为空吗?或者,您可以启用它,但如果数据为空,则不运行代码。另外,除了有很多代码外,代码是格式化的fine@codeMagic嗯,我没有想到这一点,老实说,我不认为我能做到这一点,哈哈……所以这就像Bundle b=getIntent.getExtras;double AnimalLat=b.getDoublekey;Bundle d=getIntent.getExtras;double AnimalLon=d.getDoublekey1@codeMagic抱歉并不是要按enter aha,所以代码类似于bundle b和bundle d==null{do nothing}?如果是这样的话,让你评论一个答案,把它封装起来,这样我就可以把它标记为一个:是的,类似这样的。让我知道它是否有效,我会把它作为一个答案。啊,对不起,代码里没有按钮,包裹在外面,但是我也试过了,在一个按钮里面,我现在就试试,然后给你回复,谢谢,如果bundle是在onClick侦听器之外声明的,那么我相信您必须将其声明为final,但内部应该可以工作。如果您仍然有问题,请编辑您的帖子,将bundle和onClick代码放在一起,这样我就可以更好地了解您是如何做到这一点的。让我知道它是如何运行的我忘了说它不会工作,因为SMSReiver中的意图将数据发送到主屏幕,所以意图不能在按钮内,因为意图在按钮内,所以它会崩溃,除非用户及时按下按钮,这是不可能的。问题是我需要oncreate方法或其他方法中的接收意图,如果可能的话,这些方法将起作用,因为sms接收器可能需要5分钟才能接收和转换sms。但是,由于intetn处于oncreate中,并且在加载地图时没有任何信息,这可能是在第一次发送sms的同时发生的。很抱歉,这有点难以解释。基本上,唯一的问题是声明变量double AnimalLat=double.parseDoublelat;和double AnimalLon=double.parseDoublelon;或者如果我把它们转换成LatlngAnimalCoordinat=新的LatLngAnimalLat,AnimalLon;那就意味着在主屏幕上只需要一个变量,但我无法让它工作。
//inside your Button
if (data != null)
{
     ...do stuff in here
}