2

I'm wondering how to pass data/variables through classes?

Class.java

public class AddItem extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
         mlocListener = new CurrentLocation();
         mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    }   
}

public void sendDataDetail(View v){
    // This is where my HTTPPOST goes, need the location here
}

public class CurrentLocation implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        // TODO Auto-generated method stub
        loc.getLatitude();
        loc.getLongitude();
        String Text = "My Current Location is: " + "Lat = " + loc.getLatitude() + "Long = " + loc.getLongitude();
        Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
    }
}

SO basically, I have CurrentLocation() in onCreate, and then I have an HTTPPOST script in sendDataDetail. And then I have a class that gets the location.

How do I get that location and send it to sendDataDetail? What methods should I take?

Please note that I'm still learning android,

Thank you in advance!

hellomello
  • 8,219
  • 39
  • 151
  • 297

3 Answers3

1

In Android, sharedpreferences are used to pass information between classes.

This is the simplest example I know to explain how it works. http://android-er.blogspot.com/2011/01/example-of-using-sharedpreferencesedito.html

Kalaji
  • 425
  • 1
  • 4
  • 13
0

One way is to Extend the Application class and get the instance with the data, populate it in one class and use it in another. See this question on StackOverflow.

Basically what you do is that you extend the Application object and add your fields (location in your case) and set it at one place and get it at another. Here is the example code from the link I have mentioned:

class MyApp extends Application {

  private String myState;

  public String getState(){
    return myState;
  }
  public void setState(String s){
    myState = s;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
  }
}

There are other ways, but this solution is pretty good!

Community
  • 1
  • 1
SpeedBirdNine
  • 4,610
  • 11
  • 49
  • 67
0

In some use cases, you can put a static variable somewhere for both classes to reference. That would be easiest, and it would give pedants the shivers, which is always a good thing. Well, except when they're right, of course.

Yusuf X
  • 14,513
  • 5
  • 35
  • 47