Button declaration in Fragment results in null Android

I've followed different links and forums to solve this problem, but I couldn't solve it. So I think I am missing something important in my code but I don't get what.

The situation is the following. I'm trying to invoke some click listeners to three buttons. When I initialized them (I've tried in onCreateView() and in OnViewFragment() method, Also in OnCreate()) It's in a fragment. I attach my XML below (a part, for sure), I tried to invoke it using getActivity().findViewById(R.id.the_id_of_each_button) and also with

View view = inflater.inflate(R.layout.fragment_profile, container, false);
one_of_my_buttons =(Button) getActivity().findViewById(R.id.the_id_of_one_of_my_buttons);

I think It's because I've my buttons into some layouts, but I didn't find how to solve this.

My XML (Right now):

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".profileFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollableView">

        <ImageView
            android:id="@+id/profilePicture"
            android:layout_width="0dp"
            android:layout_height="225dp"
            android:background="@color/azulito"
            android:src="@drawable/default_prfile_picture"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/buttons_to_edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="4dp"
            android:backgroundTint="#FFFFFF"
            android:focusable="true"
            android:tint="@color/azulito"
            android:src="@drawable/ic_baseline_add_24"
            app:backgroundTint="@color/azulito"
            app:borderWidth="0.5dp"
            app:layout_constraintBottom_toBottomOf="@id/profilePicture"
            app:layout_constraintEnd_toEndOf="@id/profilePicture" />


        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/edit_profile_picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:focusable="true"
            android:visibility="invisible"
            android:layout_marginBottom="64dp"
            android:backgroundTint="#FFFFFF"
            android:src="@drawable/ic_baseline_image_24"
            android:tint="@color/azulito"
            app:backgroundTint="@color/azulito"
            app:borderWidth="0.5dp"
            app:fabSize="mini"
            app:layout_constraintBottom_toTopOf="@id/buttons_to_edit"
            app:layout_constraintEnd_toEndOf="@+id/buttons_to_edit"
            app:layout_constraintStart_toStartOf="@+id/buttons_to_edit"
            app:rippleColor="@color/azulito" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/edit_profile"
            android:visibility="invisible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_marginEnd="8dp"
            android:focusable="true"
            android:layout_marginBottom="4dp"
            android:backgroundTint="#FFFFFF"
            android:src="@drawable/ic_baseline_edit_24"
            app:backgroundTint="@color/azulito"
            app:borderWidth="0.5dp"
            app:fabSize="mini"
            app:layout_constraintBottom_toTopOf="@id/edit_profile_picture"
            app:layout_constraintEnd_toEndOf="@+id/edit_profile_picture"
            app:layout_constraintStart_toStartOf="@+id/edit_profile_picture" />


      <!-- here is more XML code, but nothing really relevant for this purposes-->


    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

And my Java code (for this particular fragment because others are working fine):

package com.janus.janusapp;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link profileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class profileFragment extends Fragment{



    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    private Animation rotateOpen ;
    private Animation rotateClose ;
    private Animation fromBottom ;
    private Animation toBottom ;
    //Here is where I declare those three buttons
    private Button more_buttons;
    private Button edit_profile_picture;
    private Button edit_profile;
    private boolean clicked = false;

    /**====================================================================================================*/


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


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

    public static profileFragment newInstance(String param1, String param2) {
        profileFragment fragment = new profileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);

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


    }
    /*==================================================================================================
     * Here are some functions used by the buttons, but there's not where it fails, so, I just mention it.
    /*
    private void deployMoreButtons();
    private void setVisibility(boolean clicked);
    private void setAnimation(boolean clicked);
    private void setClickable(boolean clicked);

   /*=====================================The onCreateView() Method====================================*/
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile, container, false);


        rotateOpen = AnimationUtils.loadAnimation(getActivity(),R.anim.rotate_open_anim);
        rotateClose = AnimationUtils.loadAnimation( getActivity(),R.anim.rotate_close_anim);
        fromBottom = AnimationUtils.loadAnimation(getActivity(),R.anim.from_bottom_anim);
        toBottom = AnimationUtils.loadAnimation( getActivity(),R.anim.to_bottom_anim);
        /* I initialize my buttons right here, In the ways I tried before. When I use getActivity() it passes but the value of the burron seems to be null, and in the other way it just fails*/

        more_buttons =(Button) getActivity().findViewById(R.id.buttons_to_edit);
        edit_profile = (Button)getActivity().findViewById(R.id.edit_profile);
        edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);

        /* My button SetOnClickListeners, here is where my execution fails using getActivity()*/
        more_buttons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deployMoreButtons();
            }
        });
        edit_profile_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Do Something
            }
        });

        edit_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Do Something
            }
        });
        return view;
    }

}

So what I'm doing wrong and what can I do? Thanks for your help.

Upvotes: 0

Views: 104

Answers (5)

Okay, now maybe I'm going to gain some hate...

The class of the buttons I had are FloatingActionButton that's why they didn't work using view inflater. Now it works fine. I used the solutions everyone took here. Thanks.

Upvotes: 0

mr. groot
mr. groot

Reputation: 374

As you declared the inflated layout for the fragment as "view", now if you want to call anything from the view so you have to use it as...

view.edit_profile

Here when you type view. Is means you are calling view from the layout you inflated as view.

Upvotes: 2

Ayush Pal
Ayush Pal

Reputation: 154

In onCreateView use

view.findViewById(YourId);

Upvotes: 0

Wahdat Jan
Wahdat Jan

Reputation: 4156

You are using activity reference to find the id of the buttons, but the button is in your Fragment xml which you have inflated and then you can find the id's of buttons defined in fragment xml using view as shown below

View view = inflater.inflate(R.layout.fragment_profile, container, false);
one_of_my_buttons =(Button) view.findViewById(R.id.the_id_of_one_of_my_buttons);

Upvotes: 0

S T
S T

Reputation: 1134

you use Fragment and already Inflate. So

more_buttons =(Button) getActivity().findViewById(R.id.buttons_to_edit);
        edit_profile = (Button)getActivity().findViewById(R.id.edit_profile);
        edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);

to

more_buttons =(Button) view.findViewById(R.id.buttons_to_edit);
        edit_profile = (Button) view.findViewById(R.id.edit_profile);
        edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);

Upvotes: 0

Related Questions