0

I have gone through a lot of question and while this question seems to be duplicate, it is not!

I want to pass 2 strings from an activity to a fragment and I am failing in doing so getting following error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference at com.abc.xyz.PostARequest$2$2.run(PostARequest.java:154)

Here's PostARequest.java(the fragment) file's code:

public class PostARequest extends Fragment {

    Bitmap bitmap;
    ImageView hPic;
    boolean hasDrawable;
    EditText hsDescription;
    TextView hPicTag, hLocationTag, currentCoordinatesTag, currentLat, currentLng;
    LinearLayout latContainer, lngContainer;
    Bundle b;
    TabHost tabHost;
    String latitude, longitude;

    private OnFragmentInteractionListener mListener;

    public PostARequest() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PostARequest.
     */
    // TODO: Rename and change types and number of parameters
    public static PostARequest newInstance(String param1, String param2) {
        PostARequest fragment = new PostARequest();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_post_a_request, container, false);

        // check for location here

        currentCoordinatesTag = (TextView) rootView.findViewById(R.id.currentCoordinatesTag);
        latContainer = (LinearLayout) rootView.findViewById(R.id.latContainer);
        currentLat = (TextView) rootView.findViewById(R.id.currentLat);
        lngContainer = (LinearLayout) rootView.findViewById(R.id.lngContainer);
        currentLng = (TextView) rootView.findViewById(R.id.currentLng);

        currentCoordinatesTag.setVisibility(View.INVISIBLE);
        latContainer.setVisibility(View.INVISIBLE);
        currentLat.setVisibility(View.INVISIBLE);
        lngContainer.setVisibility(View.INVISIBLE);
        currentLng.setVisibility(View.INVISIBLE);

        tabHost = new TabHost(getContext());

        b = this.getArguments();

        hLocationTag = (TextView) rootView.findViewById(R.id.h_location_tag);
        hLocationTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mapsIntent = new Intent(getContext(), MapsActivity.class);
                startActivity(mapsIntent);
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        homelessLocationTag.setVisibility(View.INVISIBLE);
                    }
                }, 500);

                final Handler handler2 = new Handler();
                handler2.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        currentCoordinatesTag.setVisibility(View.VISIBLE);
                        latContainer.setVisibility(View.VISIBLE);
                        currentLat.setVisibility(View.VISIBLE);
                        lngContainer.setVisibility(View.VISIBLE);
                        currentLng.setVisibility(View.VISIBLE);

                        latitude = b.getString("latitude");
                        longitude = b.getString("longitude");

                        currentLat.setText(latitude);
                        currentLng.setText(longitude);

                        tabHost.setCurrentTab(2);

                    }
                }, 15000);

            }
        });
}

Here's MapsActivity.java(the activity) file's code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    FloatingActionButton addLocationFab;
    Double latitude, longitude;
    LatLng userCurrentPosition;
    String coordl1, coordl2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        addLocationFab = (FloatingActionButton) findViewById(R.id.addLocationFAB);

    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(final GoogleMap googleMap) {
        mMap = googleMap;

        googleMap.setMyLocationEnabled(true);

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

                latitude = googleMap.getMyLocation().getLatitude();
                longitude = googleMap.getMyLocation().getLongitude();

                coordl1 = latitude.toString();
                coordl2 = longitude.toString();

                Log.d("latitude", coordl1);
                Log.d("longitude", coordl2);

                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Bundle bundle = new Bundle();
                        bundle.putString("latitude", coordl1);
                        bundle.putString("longitude", coordl2);
                        PostARequest postARequest = new PostARequest();
                        postARequest.setArguments(bundle);
                    }
                }, 5000);
            }
        });

    }

}

I really have no idea about what is wrong here.

Please let me know.

Please cooperate if question is not in good condition, I'm still learning to post good questions.

  • try initializing your string – Iamat8 Jan 10 '16 at 20:00
  • To pass data from activity to fragment: Put this code anywhere Bundle bundle = new Bundle(); bundle.putString("KEY_NAME1", "Abrakadabra"); bundle.putString("KEY_NAME2", "Kadabra"); MyFragment myfragment = new MyFragment(); myfragment.setArguments(bundle); Then in the onCreateView method of the fragment add this code Bundle args = getArguments(); String stringdata1 = args.getString("KEY_NAME1"); String stringdata2 = args.getString("KEY_NAME2"); – suku Jan 11 '16 at 01:26
  • One thing I noticed is that you are trying to send data via bundle to the same fragment created again. I had to do the same once, for that I had to destroy/remove the previous instance of the fragment and then do the procedure that you did. Just remove the fragment before you call the function to send the data. Alternatively if you do not want to destroy the fragment then you have to use interface as I have answered above. – suku Jan 11 '16 at 12:53
  • @suku Could you please answer more briefly? Describing the whole process. –  Jan 11 '16 at 12:55
  • Whole thing. How can I get a string from an activity to a fragment without any errors. Please. –  Jan 11 '16 at 13:09
  • As you are using bundles do this: – suku Jan 11 '16 at 23:28
  • As you are using bundles do this: Fragment fragment = getFragmentManager().findFragmentByTag(TAG_FRAGMENT); if(fragment != null) getFragmentManager().beginTransaction().remove(fragment).commit(); After this run the final Handler handler = new Handler(); I have not gone through your code, but keep all getArgument methods in the on create of the fragment. Do not send data to activity from fragment via a bundle. It won't work. You HAVE TO USE interface. – suku Jan 11 '16 at 23:41

1 Answers1

0

You are not calling newInstance() in Fragment.

Use

PostFragment.newInstance(latitude, longitude);

In Fragment set those global variables:

this.latitude = latitude;
this.longitude = longitude;
Keshav
  • 577
  • 3
  • 10