简体   繁体   中英

How to get a variable from a class to the main activity?

In my Android application (Wheather app), I have a main activity (displaying the wheater on the screen) and a class (getting the current location of the phone). The "Position" class gets the latitude and longitude, which I would like to send in my main activity to use them. To do that, I tried to use getters but that does not seem to work. Here is the code for both classes :

Location class: (just pay attention to the getters at the end)

public class Position extends AppCompatActivity implements LocationListener {

private double longitude;
private double latitude;
private LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);

    onLocationChanged(location);


}

@Override
public void onLocationChanged(Location location) {
    longitude=location.getLongitude();
    latitude=location.getLatitude();

}

public double getLongitude1() {
    return this.longitude;
}

public double getLatitude1() {
    return this.latitude;
}

Main_Activity: (again just pay attention to the last four lines where I i'm trying to use latitude and longitude)

public class MainActivity extends AppCompatActivity {

TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;

Typeface weatherFont;

Position position = new Position();

private double latitude1;
private double longitude1;
private String latitude2;
private String longitude2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);


    weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");

    cityField = (TextView)findViewById(R.id.city_field);
    updatedField = (TextView)findViewById(R.id.updated_field);
    detailsField = (TextView)findViewById(R.id.details_field);
    currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
    humidity_field = (TextView)findViewById(R.id.humidity_field);
    pressure_field = (TextView)findViewById(R.id.pressure_field);
    weatherIcon = (TextView)findViewById(R.id.weather_icon);
    weatherIcon.setTypeface(weatherFont);


    Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
        public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {

            cityField.setText(weather_city);
            updatedField.setText(weather_updatedOn);
            detailsField.setText(weather_description);
            currentTemperatureField.setText(weather_temperature);
            humidity_field.setText("Humidity: "+weather_humidity);
            pressure_field.setText("Pressure: "+weather_pressure);
            weatherIcon.setText(Html.fromHtml(weather_iconText));

        }
    });
    latitude1 = position.getLatitude1();
    longitude1 = position.getLongitude1();
    latitude2 = String.valueOf(latitude1);
    longitude2 = String.valueOf(longitude1);
    asyncTask.execute(latitude2, longitude2); //  asyncTask.execute("Latitude", "Longitude")

}

Why do I always get latitude2 = 0.0 and longitude2 = 0.0 in my android monitor ?

You have two different activities. Not an activity and a background service. There is only a single UI thread that runs the Activities. So when MainActivity is running, the Position activity is in the background and not running. And you can't create an object of an Activity using Position position = new Position(); .

Why is your Position class an Activity ? The onCreate method will never be called there unless you start the class as an Activity . Remove the AppCompatActivity from it and move the onCreate method in a separate method eg getLocation .

You also want to pass the Context to the Position class. Create a constructor for that

public Position(Context context) {
    this.context = context;
}

and use that for the system calls.

Private variables can't be shared. Change it to.

public double longitude1;
public double latitude1;

You don't really need Position extend from an Activity. I can understand what you are trying to do, you just want to get the location from LocationManager , and send the result to the MainActivity . It should be fine if you just make a LocationManager instance in your MainActivity and pass the result of the location to whatever you want inside MainActivity .

public class MainActivity extends AppCompatActivity {

TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;

Typeface weatherFont;

Position position = new Position();

private double latitude1;
private double longitude1;
private String latitude2;
private String longitude2;

private LocationManager mLocationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);


    weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");

    cityField = (TextView)findViewById(R.id.city_field);
    updatedField = (TextView)findViewById(R.id.updated_field);
    detailsField = (TextView)findViewById(R.id.details_field);
    currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
    humidity_field = (TextView)findViewById(R.id.humidity_field);
    pressure_field = (TextView)findViewById(R.id.pressure_field);
    weatherIcon = (TextView)findViewById(R.id.weather_icon);
    weatherIcon.setTypeface(weatherFont);


    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // do check permission staff as you post before

    Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);

    // do what you want with the location now.

Basically I think you don't have to make a Position class. You can get location directly and just use it then.

I suggest you to add following reforms to your code.

  1. You need to create object of Position class inside onCreate() method of MainActivity. As onCreate() runs before everything else, it's necessary to have the definition of Position class inside this method.

  2. Make your variables for longitude and latitude public to make them accessible in other class.

  3. Position class need not to extend AppCompatActivity. Instead of using this and OnCreate() method, you can use Constructor and define all your stuff there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM