0

I have an application which requires data to be fetched from a received message and then pass this data to another activity for other uses.I have extracted the data from a received sms but how can I pass this from current java file to use it in other java file ?

public class ReceivelocationActivity extends BroadcastReceiver   {

private LocationManager hdLocMgr;
private String hdLocProvider;

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    Intent m=new Intent(context, ReceivelocationActivity.class);    
      PendingIntent pi=PendingIntent.getBroadcast(context, 0, m, 0); 
    Bundle bundle = intent.getExtras();        
    SmsMessage[] msgs = null;
    String str = ""; 
    String str2="";
    String str3="";
    String autoReplyToken = "Request_Accepted";
    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 += "SMS from " + msgs[i].getOriginatingAddress();                     
            str2=msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
         str3=msgs[i].getMessageBody().toString();
            str += "\n";        
        }
        //---display the new SMS message---
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
      //  int number=Integer.parseInt(str2);

     // retrieve th current location
        Criteria hdCrit = new Criteria();
        hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);
        hdCrit.setAltitudeRequired(false);
        hdCrit.setBearingRequired(false);
        hdCrit.setCostAllowed(true);
        hdCrit.setPowerRequirement(Criteria.POWER_LOW);

        hdLocMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        hdLocProvider = hdLocMgr.getBestProvider(hdCrit, true); 

        Location location = hdLocMgr.getLastKnownLocation(hdLocProvider);

        Double dlat = location.getLatitude();
        Double dlon = location.getLongitude();


        String mymsg = Double.toString(dlat) + " " +Double.toString(dlon) ; 

        boolean isAutoReply = str3.startsWith(autoReplyToken);

        if (!isAutoReply) {
            SmsManager sms = SmsManager.getDefault();
            String autoReplyText = autoReplyToken + " "+mymsg;
            sms.sendTextMessage(str2, null, autoReplyText, pi, null);
        }

      /* Part as suggested by you to pass a string to friendlocation.class  */  
        Intent in = new Intent(context, Friendlocation.class);
        in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        in.putExtra("latlongstring", str3);
        context.startActivity(in);
    }                 
}



    public class Friendlocation extends MapActivity implements LocationListener {
     /** Called when the activity is first created. */
private static final String TAG = "LocationActivity";
LocationManager locationManager; 
  Geocoder geocoder; 
  TextView locationText;
  MapView map;  
  MapController mapController; 
  GeoPoint point;

  class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long   when) 
        {
            super.draw(canvas, mapView, shadow);                   

            //---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(point, screenPts);

            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.androidmarker);            
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);         
            return true;
        }
    } 


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main4);



    locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
    map = (MapView)this.findViewById(R.id.mapview);
    map.setBuiltInZoomControls(true);

    mapController = map.getController(); 
    mapController.setZoom(16);


    String latlon = getIntent().getStringExtra("latlongstring");
    this.friendlocation(latlon);

}



public void friendlocation(String latlon) { 

    String [] location = latlon.split("\\s+");
    double alt=0;
    double bear=0;
    double lat= Double.valueOf(location[0].trim()).doubleValue();
    double lon=Double.valueOf(location[1].trim()).doubleValue();

  String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", lat, 
                lon, alt,bear);
  this.locationText.setText(text);

  try {
    List<Address> addresses = geocoder.getFromLocation(lat, lon,10); //<10>
    for (Address address : addresses) {
      this.locationText.append("\n" + address.getAddressLine(0));
    }

    int latitude = (int)(lat * 1000000);
    int longitude = (int)(lon * 1000000);

    point = new GeoPoint(latitude,longitude);


   mapController.animateTo(point);   
   MapOverlay mapOverlay = new MapOverlay();
   List<Overlay> listOfOverlays = map.getOverlays();
   listOfOverlays.clear();
   listOfOverlays.add(mapOverlay);


    map.invalidate();

  } catch (IOException e) {
    Log.e("LocateMe", "Could not get friend location", e);
  }
}

the entire log cat error :

10-31 23:07:34.884: D/ddm-heap(234): Got feature list request 10-31 23:08:05.443: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:05.443: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:05.475: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:05.593: D/LocationManager(234): Constructor: service = android.location.ILocationManager$Stub$Proxy@44dd4c38 10-31 23:08:05.772: I/MapActivity(234): Handling network change notification:CONNECTED 10-31 23:08:05.772: E/MapActivity(234): Couldn't get connection factory client 10-31 23:08:12.012: D/LocationManager(234): removeUpdates: listener = com.example.gui.SendlocationActivity@44db4af0 10-31 23:08:12.112: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:12.112: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:12.122: W/MapActivity(234): Recycling dispatcher com.google.googlenav.datarequest.DataRequestDispatcher@44db89f0 10-31 23:08:12.142: V/MapActivity(234): Recycling map object. 10-31 23:08:13.472: D/AndroidRuntime(234): Shutting down VM 10-31 23:08:13.472: W/dalvikvm(234): threadid=3: thread exiting with uncaught exception (group=0x4001b188) 10-31 23:08:13.482: E/AndroidRuntime(234): Uncaught handler: thread main exiting due to uncaught exception 10-31 23:08:13.822: E/AndroidRuntime(234): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gui/com.example.gui.Friendlocation}: java.lang.NullPointerException 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.os.Handler.dispatchMessage(Handler.java:99) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.os.Looper.loop(Looper.java:123) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.main(ActivityThread.java:4363) 10-31 23:08:13.822: E/AndroidRuntime(234): at java.lang.reflect.Method.invokeNative(Native Method) 10-31 23:08:13.822: E/AndroidRuntime(234): at java.lang.reflect.Method.invoke(Method.java:521) 10-31 23:08:13.822: E/AndroidRuntime(234): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 10-31 23:08:13.822: E/AndroidRuntime(234): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 10-31 23:08:13.822: E/AndroidRuntime(234): at dalvik.system.NativeStart.main(Native Method) 10-31 23:08:13.822: E/AndroidRuntime(234): Caused by: java.lang.NullPointerException 10-31 23:08:13.822: E/AndroidRuntime(234): at com.example.gui.Friendlocation.friendlocation(Friendlocation.java:110) 10-31 23:08:13.822: E/AndroidRuntime(234): at com.example.gui.Friendlocation.onCreate(Friendlocation.java:89) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 10-31 23:08:13.822: E/AndroidRuntime(234): ... 11 more 10-31 23:08:13.842: I/dalvikvm(234): threadid=7: reacting to signal 3 10-31 23:08:13.972: I/dalvikvm(234): Wrote stack trace to '/data/anr/traces.txt' 10-31 23:08:21.046: I/Process(234): Sending signal. PID: 234 SIG: 9 10-31 23:08:21.574: E/ActivityThread(253): Failed to find provider info for com.google.settings 10-31 23:08:21.574: E/ActivityThread(253): Failed to find provider info for com.google.settings 10-31 23:08:21.593: E/ActivityThread(253): Failed to find provider info for com.google.settings 10-31 23:08:21.733: D/LocationManager(253): Constructor: service = android.location.ILocationManager$Stub$Proxy@44dcb680 10-31 23:08:21.753: D/LocationActivity(253): Location[mProvider=gps,mTime=1319979600000,mLatitude=10.0,mLongitude=10.0,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false,mSpeed=0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=false,mAccuracy=0.0,mExtras=null] 10-31 23:08:21.863: I/MapActivity(253): Handling network change notification:CONNECTED 10-31 23:08:21.863: E/MapActivity(253): Couldn't get connection factory client

dark_shadow
  • 3,503
  • 11
  • 56
  • 81
  • can you post the full stack trace of the exception that prints out in Logcat when your application crashes? There are lots of things that can go wrong, but the stack trace will show us where exactly Android is crashing. – plowman Oct 31 '11 at 17:19
  • @plowman : I have pasted whole log cat.sorry for the bad presentation but I think exactly copying this will make it more clear.If there is anything which you want to ask please feel free to ask and Thanks in advance. – dark_shadow Oct 31 '11 at 17:42
  • According to the stack trace, the problem is `at com.example.gui.Friendlocation.friendlocation(Friendlocation.java:110)` So inside `Friendlocation.java`, inside the `friendlocation()` method, on `line 110`, you're trying to call a method on something that is null. I suspect it is related to `String[] location`, so you should check that `location.length == 2` before calling `location[0]` or `location[1]`. You should also print out `latlon` and `location` before trying to use them so that you can be sure they are what you expect. – plowman Oct 31 '11 at 18:36
  • @plowman : But how to print these values,I mean I can't print them on console as I used to do in java.Can you please how to check latlon and location,please ? – dark_shadow Oct 31 '11 at 18:45
  • Did you try `System.out.println()`? – plowman Oct 31 '11 at 18:52
  • @plowman : I just checked it using Log.d() , and you were right ,actually location[1] and location[2] are containing longitude and latitude and location[0] was containing "Request_Accepted" and I fixed it but still it is showing errors: 11-01 00:32:15.943: E/AndroidRuntime(420): at com.example.gui.Friendlocation.friendlocation(Friendlocation.java:105) 11-01 00:32:15.943: E/AndroidRuntime(420): at com.example.gui.Friendlocation.onCreate(Friendlocation.java:90) Is there anything wrong in friendlocation(latlon); and double lon=Double.valueOf(location[2].trim()).doubleValue(); ? – dark_shadow Oct 31 '11 at 19:07
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4622/discussion-between-plowman-and-code-hacker) – plowman Oct 31 '11 at 19:31

1 Answers1

3

You can pass data between activities using Intents. In the BroadcastReceiver where you receive the SMS, you can do something like this:

@Override
public void onReceive(Context context, Intent intent) {
    byte[] pdu = new byte[0]; //obviously use the real pdu in your app
    Intent intent = new Intent(this, NewActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("smsPdu", pdu);
    context.startActivity(intent);
}

Then, inside of NewActivity, you can do something like this:

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        byte[] pdu = getIntent().getByteArrayExtra("smsPdu");
        SmsMessage message = SmsMessage.createFromPdu(pdu);
}

See the documentation here for a more thorough overview of Intents.

plowman
  • 13,335
  • 8
  • 53
  • 53
  • @ plowman : On writing StartActivity(intent) I get an error showing "create method startActivity() ". My receivingsms class extends BroadcastReceiver.Can you please tell me why is it so ? – dark_shadow Oct 31 '11 at 16:17
  • @code_hacker : I have edited my example to be more clear. You can call startActivity() using any instance of Context as well as from within any method of an Activity. Note the part where I add `intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)` - this is important to avoid crashing. Let me know if this still does not make sense. – plowman Oct 31 '11 at 16:49
  • I have done exactly what you said but my application crashes when a sms is received.I'm putting both the files (receivesms.java and friendlocation.java).Please take a look at it and let me know what can be possible reasons for that? – dark_shadow Oct 31 '11 at 17:05