mvasco
mvasco

Reputation: 5101

Android exception when inserting onClick method in a fragment

In a fragment I have included a map and a button on a RelativeLayout. The button above and the map below it.

This is the code for the fragment activity:

public class Tab2 extends Fragment implements OnMapReadyCallback {

    private View view;
    private Context mContext;

    private double latitud_del_hotel, longitud_del_hotel;
    private String nombre_del_hotel;

    private static final String url = "..hidden here..";
    private ProgressDialog pDialog;
    private List<Hotel> hotelList = new ArrayList<Hotel>();

    private Button mostrarButton;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.tab_2, container, false);



        mContext = getActivity();

        nombre_del_hotel = getActivity().getIntent().getStringExtra("nombre_hotel");
        latitud_del_hotel = getActivity().getIntent().getDoubleExtra("latitud_hotel", 0);
        longitud_del_hotel = getActivity().getIntent().getDoubleExtra("longitud_hotel",0);


        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        SupportMapFragment fragment = new SupportMapFragment();
        transaction.add(R.id.mapView, fragment);
        transaction.commit();

        fragment.getMapAsync(this);


        mostrarButton = (Button) getActivity().findViewById(R.id.boton_mostrar);
        mostrarButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                pDialog = new ProgressDialog(getActivity());
                pDialog.setMessage("Procesando datos de marcadores...");
                pDialog.show();

            }
        });

        return view;
    }


    @Override
    public void onMapReady(GoogleMap map) {
        //map is ready
        // latitude and longitude
        double latitude = latitud_del_hotel;
        double longitude =longitud_del_hotel;

        // create marker
        MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(nombre_del_hotel).icon(BitmapDescriptorFactory.fromResource(R.drawable.poi));

        // Changing marker icon
        // marker.icon(BitmapDescriptorFactory
        // .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

        // adding marker
        map.addMarker(marker);
        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(latitud_del_hotel, longitud_del_hotel)).zoom(15).build();
        map.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
    }
}

What I need is to click on the button and then show more markers on the map. As it is now, the app throws an exception at line

=>this is line 107 mostrarButton.setOnClickListener(new OnClickListener() {

09-26 15:34:08.400 1513-1513/com.solinpromex.elpasojuarezexperience

This is the exception output:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.solinpromex.elpasojuarezexperience, PID: 1513
    java.lang.NullPointerException
            at com.solinpromex.elpasojuarezexperience.Tab2.onCreateView(Tab2.java:107)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
            at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1334)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1532)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1211)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6282)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
            at android.view.Choreographer.doCallbacks(Choreographer.java:591)
            at android.view.Choreographer.doFrame(Choreographer.java:560)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
            at android.os.Handler.handleCallback(Handler.java:808)
            at android.os.Handler.dispatchMessage(Handler.java:103)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            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:825)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
            at dalvik.system.NativeStart.main(Native Method)

How could I resolve this issue? Thank you.

NOTE: Prior to inserting the setOnclickListener the map is shown as expected.

Upvotes: 0

Views: 55

Answers (2)

TBridges42
TBridges42

Reputation: 1879

You are getting that error because mostrarButton is null, which means findViewById is not finding R.id.boton_mostrar in your activity.

If R.id.boton_mostrar is in R.layout.tab_2, then you could use

mostrarButton = (Button) view.findViewById(R.id.boton_mostrar);

If it is indeed in your activity's layout, I recommend not interacting with the calling activity until onActivityCreated is called. In theory, the activity is available starting in onAttach, but I find it is not safe to interact with the activity until onActivityCreated.

Upvotes: 1

mohax
mohax

Reputation: 4595

Yours problen in that line

mostrarButton = (Button) getActivity().findViewById(R.id.boton_mostrar);

You can't get Activity in onCreateView() method of Fragment because fragment in not added to Activity yet. So in line above you get null reference on Button.

The only way is to initialize yours button from activity in onAttach(Activity activity) (or later methods of Fragments lifecicle) method of Fragment.

See the example code:

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);
    mostrarButton = (Button) getActivity().findViewById(R.id.boton_mostrar);
}

Upvotes: 1

Related Questions