Search code examples
javalocation

Passing a variable from MainActivity to a Fragment


This is a Java question and not Android:). In my MainActivity I get the phone's location (log and lat) which is shown in the below code:

public class MainActivity extends AppCompatActivity implements  
GoogleApiClient.OnConnectionFailedListener,

GoogleApiClient.ConnectionCallbacks{
private static final int PLAY_SERVICES_CODE = 90;
GoogleApiClient googleApiClient;
private static final String TAG = "Location";
private static final String TODAY_FRAGMENT = "today_fragment";

public static double lat,log;
TodayForecast ff;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fragmentManager = getSupportFragmentManager();
    ff = (TodayForecast) fragmentManager.findFragmentByTag(TODAY_FRAGMENT);

    if (savedInstanceState != null) {
        //Restore the fragment's instance
        ff = (TodayForecast) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
    }

    if(ff == null) {
        ff = new TodayForecast();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(android.R.id.content, ff);
        fragmentTransaction.commit();
    }

    if(checkPlayServices()){
        initializeGoogleApiClient();
    }
}

private void initializeGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addOnConnectionFailedListener(this)
            .addConnectionCallbacks(this)
            .build();

}

public boolean checkPlayServices(){
    int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    if(result!= ConnectionResult.SUCCESS){
        if(GooglePlayServicesUtil.isUserRecoverableError(result)){
            GooglePlayServicesUtil.getErrorDialog(result, this, PLAY_SERVICES_CODE).show();
        }
        return false;
    }
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}


@Override
public void onConnected(@Nullable Bundle bundle) {

    Location loc = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    if(loc!=null){
        lat = loc.getLatitude();
        log = loc.getLongitude();

        Log.v(TAG,"lat: "+lat);
        Log.v(TAG,"lon: "+log);

    }else{
        Toast.makeText(getApplicationContext(),"No location obtained",Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();

    if(googleApiClient.isConnected()){
        googleApiClient.disconnect();
    }
}
}

I want to pass the values of log and lat seen inside the onConnected method to a fragment.

@Override
public void onConnected(@Nullable Bundle bundle) {

Location loc =  
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

if(loc!=null){
    lat = loc.getLatitude();
    log = loc.getLongitude();

    Log.v(TAG,"lat: "+lat);
    Log.v(TAG,"lon: "+log);

}else{
    Toast.makeText(getApplicationContext(),"No location   
    obtained",Toast.LENGTH_SHORT).show();
   }
 }

I tried this but both values are 0:(

public class TodayForecast extends Fragment {
public static String URL= "http://api.openweathermap.org/data/2.5/weather?";
public static String BASE_URL= "";


String IMG_URL = "http://api.openweathermap.org/img/w/";
double lat;
double lot;
public TodayForecast() {
    // Required empty public constructor
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    lat = MainActivity.lat;
    lot = MainActivity.log;

    BASE_URL = URL + "lat=" + lat + "&lot=" + lot + "&appid=" + "MY KEY";


    return inflater.inflate(R.layout.fragment_today_forecast, container,   
    false);



   }

 }

My fragment's XML is:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/main_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#ff1ba1ee"
tools:context="testing.theo.newweatherapp.TodayForecast">

<TextView
    android:id="@+id/cityText"
    android:textColor="#fff"
    android:textSize="18sp"
    android:textStyle="bold"
    android:layout_centerHorizontal="true"
    android:text="City of Spokane, US"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:id="@+id/thumbnailIcon"
    android:layout_below="@+id/cityText"
    android:layout_marginTop="10dp"


    android:layout_width="100dp"
    android:layout_height="100dp" />

<TextView
    android:id="@+id/tempText"
    android:layout_marginTop="25dp"
    android:text="12 deg"
    android:textStyle="normal"
    android:textSize="41sp"
    android:textColor="#fff"
    android:layout_below="@+id/cityText"
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/rainText"
    android:textSize="16sp"
    android:textColor="#fff"
    android:text=""
    android:layout_below="@+id/thumbnailIcon"
    android:layout_marginTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/windText"
    android:layout_below="@+id/rainText"
    android:layout_marginTop="35dp"
    android:textColor="#fff"
    android:text="Wind"
    android:textSize="16sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/cloudText"
    android:textSize="16sp"
    android:layout_marginTop="5dp"
    android:layout_below="@+id/windText"
    android:textColor="#fff"
    android:text="Cloudness"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/pressureText"
    android:textSize="16sp"
    android:layout_marginTop="5dp"
    android:textColor="#fff"
    android:text="Pressure"
    android:layout_below="@+id/cloudText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/humidText"
    android:textSize="16sp"
    android:text="Humidity"
    android:layout_marginTop="5dp"
    android:textColor="#fff"
    android:layout_below="@+id/pressureText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/riseText"
    android:text="Sunrise"
    android:textSize="16sp"
    android:textColor="#fff"
    android:layout_marginTop="5dp"
    android:layout_below="@+id/humidText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/setText"
    android:text="Sunrise"
    android:layout_marginTop="5dp"
    android:textColor="#fff"
    android:textSize="16sp"
    android:layout_below="@+id/riseText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />


<TextView
    android:id="@+id/updateText"
    android:text="Last update"
    android:layout_marginTop="5dp"
    android:layout_centerHorizontal="true"
    android:textColor="#fff"
    android:textSize="16sp"
    android:layout_below="@+id/setText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</RelativeLayout>

Any ideas?


Solution

  • What I am doing is shown below

    For Calling a fragment

    getSupportFragmentManager().beginTransaction().replace(R.id.main_container, MyMeetings.newInstance(user_type), "My Meeting").commit();
    

    user_type is a String

    In Fragment created a new Instance to get the data like below

     public static MyMeetings newInstance(String user_type) {
            MyMeetings fragment = new MyMeetings();
    
            mUserType = user_type;
            return fragment;
        }
    

    Hope this help.

    Edit

    Paste the below code in your XML file of Main Activity

           <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/main_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_below="@+id/view" />
    

    and then all the fragment will open inside this Frame Layout if you use the about code