Pass a string from an Activity to a fragment maps

Asked

Viewed 724 times

0

In Homeactivity, I get the string result from the server, it contains all the data I need, separated by comma, so with the method I tried to pass to the Fragment of this error

 FATAL EXCEPTION: main
                                                                                  Process: mundosenai.mundosenai.com.mundosenai, PID: 23738
                                                                                  java.lang.NullPointerException
                                                                                      at mundosenai.mundosenai.com.mundosenai.MapsFragment.onMapReady(MapsFragment.java:63)
                                                                                      at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
                                                                                      at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
                                                                                      at android.os.Binder.transact(Binder.java:361)
                                                                                      at xz.a(:com.google.android.gms.DynamiteModulesB:82)
                                                                                      at maps.ad.u$5.run(Unknown Source)
                                                                                      at android.os.Handler.handleCallback(Handler.java:733)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                      at android.os.Looper.loop(Looper.java:136)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5072)
                                                                                      at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                      at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                                                                                      at dalvik.system.NativeStart.main(Native Method)

Homeactivity

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.43.242: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();
}


//AQUI É ONDE EU RECEBO OS DADOS DO SERVIDOR
    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) {   // RESULT É NOME DA STRING (ARRAY) QUE CONTÉM TODOS OS DADOS RESGATADOS DO SERVIDOR
                                                        // SEPARADOS POR VÍRGUA


        /*
            String[] dados = result.split(",");

            for (int i = 0; i < dados.length;i++){

                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;
                }


            }*/

            //AQUI EU ENVIO OS DADOS PARA O FRAGMENT
            MapsFragment mapsFragmet = new MapsFragment();
            Bundle data = new Bundle();
            data.putString("resgatar", result);
            mapsFragmet.setArguments(data);
        }
    }

}

Mapsfragment

public class MapsFragment extends SupportMapFragment implements OnMapReadyCallback {

@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("TESTE")
            .snippet("TESTE ")
            .position(sydney));
    */

   //AQUI EU RECEBERIA O DADO DA HOME ACTIVITY
    Bundle data = getArguments();
    String valor = data.getString("resgatar");
    System.out.println("Teste" +valor+ " funcionou");


}

}

2 answers

1


I switched to passing parameters in the method newInstance, as pointed out in the comments, the previous approach was not a good idea.

Ideally create a method that returns a new Instance of Fragment with its parameters in the Bundle.

public static MapsFragment newInstance(String teste) {
    MapsFragment f = new MapsFragment ();
    Bundle args = new Bundle();
    args.putString("resgatar",teste);
    f.setArguments(args);
    return f;
  }


public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  Bundle args = getArguments();
  if (args != null) {
     String valor = data.getString("resgatar");
     System.out.println("Teste" +valor+ " funcionou");
  }

So now instead of calling

MapsFragment mapsFragment = new MapsFragment();

utilize

MapsFragment mapsFragment = MapsFragment.newInstance("Minha String");

By passing values after instantiating the Fragment, as occurs in your onPostExecute() you will need an interface that makes this communication.

And then create a method in your Fragment that can be called to update the content when you finish a task, for example:

Mapsfragment

 public static void atualizaConteudo(String novaString){
   // atualize o que precisar com a variável

    System.out.println(novaString) // -----> Nova String que veio da Activity, faça o que quiser com ela

  }

Activity

just call MapsFragment.atualizaConteudo("Nova String");

0

You must pass via Bundle in fragmentTransaction

example:

MapsFragment fragment = new MapsFragment();
Bundle bundle = new Bundle();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
fragment.setArguments(bundle);
transaction.commitAllowingStateLoss();
  • did not work, at the time of receiving in Fragment ta giving null

Browser other questions tagged

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