当intent将变量传递给另一个活动时,app会崩溃

时间:2013-05-02 23:40:08

标签: java android android-intent android-activity

我正在创建一个跟踪用户的应用程序并跟踪理论上将成为动物的另一个用户。 我的应用程序是这样的,你注册一个用户名然后通过,完成后,用户可以通过重新输入正确的用户名和密码登录到地图。这是问题的开始。 在创建屏幕时,地图加载用户当前位置并自动向“动物”电话发送短信以请求gps详细信息,然后发回2个sms消息,1包含gps信息。我有一个SmsReceiver类,它读取此信息并提取经度和纬度数据,将其转换为double,然后将其传递给map活动,转换为lnglat变量并使用标记显示在Google地图上。现在我遇到的问题是,使用gps信息返回短信可能需要几分钟时间,当完成此操作并且使用intent将坐标发送到地图页面时必须单击一个按钮以便经度和纬度被组合到AnimalCoordinate中并显示标记,但是因为时间间隔是在检索短信的同时按下按钮是不可能的,并且当数据从smsreceiver类发送到没有任何内容时它会导致崩溃另一方面,如果我从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;
}}

我也想为代码的布局道歉,这是我第一次在这个网站上粘贴代码。 再次感谢。

1 个答案:

答案 0 :(得分:0)

说实话,我不确定你说的是哪个Button。我看到的唯一一个是在AlertDialog,除非我错过了什么。无论如何,您可以停用Button,直到任何数据都有值,或者onClick()如果是null

则无法执行任何操作
//inside your Button
if (data != null)
{
     ...do stuff in here
}

如果您需要更多说明,请在代码中注明您正在谈论的数据和Button但我认为您明白了。