Pass data from an Activity to a Fragment

Asked

Viewed 1,745 times

0

I need to pass the String result that is in Homeactivity for Mapsfragment, but I do not know how to do, I am beginner and do not understand much about the subject.

Homeactivy

package mundosenai.mundosenai.com.mundosenai;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class HomeActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{

private Button botaoPostar;
private FragmentManager fragmentManager;
double lat;
double longi;
private GoogleApiClient mGoogleApiClient;

String url = "";
String parametros ="";

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

   setContentView(R.layout.activity_home);

    botaoPostar = (Button) findViewById(R.id.botaoPostarId);


    buildGoogleApiClient();
    mGoogleApiClient.connect();

    fragmentManager = getSupportFragmentManager();

    FragmentTransaction transaction = fragmentManager.beginTransaction();

    transaction.add(R.id.container, new MapsFragment(), "MapsFragment");

    transaction.commitAllowingStateLoss();

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

                    return;
                }
                Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                if (location != null) {

                    //EU PRECISO PASSAR ESSES DOIS DADOS PARA O MAPSFRAGMENT
                    lat = location.getLatitude();
                    longi = location.getLongitude();
                    String.valueOf(lat);
                    String.valueOf(longi);

                    // verificação para saber se está funcionando  System.out.println("ahoasj "+lat+" aheooo" +longi);



                } else {
                    showSettingsAlert();

                }
            }*/






    botaoPostar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent abrePost = new Intent(HomeActivity.this, PostActivity.class);
            String id_user = getIntent().getExtras().getString("id_user");

            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            boolean GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

                String txt = "";
                txt = id_user.toString();
                Bundle bundle = new Bundle();

                bundle.putString("txt", txt);
                abrePost.putExtras(bundle);
                startActivity(abrePost);

        }
    });

    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    String nome = null, mensagem = null, lat = null, longi = null;

    url = "http://192.168.0.101:80/Login/mensagem_listar.php";

    parametros = "nome=" + nome + "&mensagem=" + mensagem + "&lat=" + lat + "&longi=" + longi;

    new SolicitaDados().execute(url);

}

protected  synchronized  void buildGoogleApiClient(){
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public  void onConnected(Bundle bundle) {


}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public boolean GetLocalization(Context context) {
    int REQUEST_PERMISSION_LOCALIZATION = 221;
    boolean res = true;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(HomeActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(HomeActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            res = false;
            ActivityCompat.requestPermissions((Activity) context, new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_PERMISSION_LOCALIZATION);

        }
    }
    return  res;
}

public void showSettingsAlert() {
    android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(HomeActivity.this);

    alertDialog.setTitle("GPS");

    alertDialog.setMessage("Gps não está Habilitato. Deseja configurar?");

    alertDialog.setPositiveButton("Configurar", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            HomeActivity.this.startActivity(intent);

        }
    });

    alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }
    );


    alertDialog.show();
}



private class SolicitaDados extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        return Conexao.postDados(urls[0], parametros);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {


        //Parte em que converto os dados, terei que fazer isso na Fragment
        //String[] dados = result.split(",");

       // for (int i = 0; i < dados.length;i++){
            //Parte de verificação dos dados

            //if(i < dados.length - 3){
             //   System.out.println("nome:" + dados[i] + " mensagem: " + dados[i+1] + " Lat " + dados[i+2] + " Longi " + dados[i+3]);
             //   i += 3;
           // }
        }
    }
}
}

Mapsfragment

package mundosenai.mundosenai.com.mundosenai;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.content.Context;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

 import android.content.Intent;
 import android.widget.Button;

 public class MapsFragment extends SupportMapFragment implements OnMapReadyCallback {

private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getMapAsync(this);



}




@Override
public void onMapReady(GoogleMap map) {

    LatLng sydney = new LatLng(-27.1330088,-51.4638369);

    //map.setMyLocationEnabled(true);
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

    map.addMarker(new MarkerOptions()
            .title("Elvis")
            .snippet("Primeira mensagem ")
            .position(sydney));


}
}

1 answer

0

You can use a Bundle

MapsFragment mapsFragmet = new MapsFragment();
Bundle data = new Bundle();
data.put("chave","valor");
mapsFragment.setArguments(data);

In Mapsfragment uses

Bundle data = getArguments();
String valor = data.getString("chave");
  • It is not going, it does not pull the libraries of the put and the mapsFragment, because I am inside a private class.

  • @Marcoskropp what you said doesn’t make sense, you have to create the object mapsFragment the way Tiago put it and then pass it to transaction.add()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.