BaRud
BaRud

Reputation: 3218

access the inner class variable to another method

Kindly help. I am not a regular java writer, so I can't solve this: The getLastLocation() in onCreate method is returning 0.0 for Lat and Lang, while the value is correct withing getLastLocation() method itself. Also, in getLastLocation, AndroidStudio says, the argument Lat and Lang is never used.

Kindly help me correct this puzzle.

 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = new Bundle();
    bundle.putDouble  ("loclat", 25.4358);
    bundle.putDouble("loclang", 81.8463);
    Fragment SunFragment = new SunFragment();
    SunFragment.setArguments(bundle);
    setContentView(R.layout.activity_main);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    getLastLocation(Lat, Long);
    //Value is 0 here
    Toast.makeText(getApplicationContext(),Double.toString(Lat), Toast.LENGTH_LONG).show();  
      SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this,
          getSupportFragmentManager(), Lat, Long);
      ViewPager viewPager = findViewById(R.id.view_pager);
      viewPager.setAdapter(sectionsPagerAdapter);
      TabLayout tabs = findViewById(R.id.tabs);
      tabs.setupWithViewPager(viewPager);

  }
  @SuppressLint("MissingPermission")
  public void getLastLocation(double Lat, double Long){
    if (checkPermissions()) {
      if (isLocationEnabled()) {
        mFusedLocationClient.getLastLocation().addOnCompleteListener(
            new OnCompleteListener<Location>() {
              @Override
              public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
                if (location == null) {
                  requestNewLocationData();
                } else {
                 final double Lat = location.getLatitude();
                 final double Long = location.getLongitude();
                 // Giving the value here
                 Toast.makeText(getApplicationContext(),"Long"+ Long, Toast.LENGTH_LONG).show();   
                }
              }
            }
        );
      } else {
        Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
      }
    } else {
      requestPermissions();
    }
  }

Upvotes: 0

Views: 54

Answers (2)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15423

Try to setup ViewPager with Tab after getting data for Lat and Long

private Double Lat;
private Double Long;

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

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    getLastLocation();
}

private void setupViewPager() {
    Toast.makeText(getApplicationContext(),Double.toString(Lat), Toast.LENGTH_LONG).show();
    SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this,
            getSupportFragmentManager(), Lat, Long);
    ViewPager viewPager = findViewById(R.id.view_pager);
    viewPager.setAdapter(sectionsPagerAdapter);
    TabLayout tabs = findViewById(R.id.tabs);
    tabs.setupWithViewPager(viewPager);
}

@SuppressLint("MissingPermission")
public void getLastLocation(){
    if (checkPermissions()) {
        if (isLocationEnabled()) {
            mFusedLocationClient.getLastLocation().addOnCompleteListener(
                    new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            Location location = task.getResult();
                            if (location == null) {
                                requestNewLocationData();
                            } else {
                                Lat = location.getLatitude();
                                Long = location.getLongitude();
                                // Giving the value here
                                Toast.makeText(getApplicationContext(),"Long"+ Long, Toast.LENGTH_LONG).show();

                                setupViewPager();
                            }
                        }
                    }
            );
        } else {
            Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    } else {
        requestPermissions();
    }
}

Suggestions: Instead of passing data to fragment you can use callback to communicate between Activity and Fragment. Check this to learn how to communicate between Activity and Fragment

Upvotes: 1

Christopher Schneider
Christopher Schneider

Reputation: 3915

You have a lot of issues here. You cannot do what you're trying to do with things the way they are right now. I'm a bit surprised this actually compiles. Long is a class name. I'd suggest sticking to convention, and use lowercase. So longitude and latitude. Your code is confusing to read.

First, the line: getLastLocation(Lat, Long);

You're passing a double which is pass by value. You are not modifying the values you passed in. You cannot do this with primitive types. You would need to encapsulate primitives inside an object and pass that object. e.g.

public class Coordinates {

  private double longitude;

  private double latitude;

  // getters and setters
}

I'm not really familiar with Android, but it seems that a similar object already exists, and it's in your code. That's Location. You should use that instead of passing around double.

Second, even if you could pass around primitives like that, you're creating and assigning new variables with these two lines:

final double Lat = location.getLatitude();
final double Long = location.getLongitude();

Finally, you're dealing with an asynchronous call. So assuming you solve the above problems, you're still going to have issues:

mFusedLocationClient.getLastLocation().addOnCompleteListener(
            new OnCompleteListener<Location>() { ... });

There is no guarantee that this action will be completed by the time getLastLocation returns, so when you call Toast.makeText in onCreate you're still likely to get 0.

So what can you do?

Well, it seems like you need to retrieve location data before this onCreate method is called and cache it. Then, in this onCreate, you can just assume that it's set.

Alternately, as Mike M. suggests, there's another method you can take advantage of: onComplete

Upvotes: 0

Related Questions