Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

android - App crashes whenever I try to change some attribute of a fragment from inside the Fragment java file

So basically the issue I am facing is that my app is crashing whenever I try to assign some value like .settext() to some view.

Basically, I have Main activity from where I have created a navigation drawer. From the Navigation drawer I have two menu options each of which when clicked on open up a fragment. Also as the first fragment is also the home screen so I launch the first fragment whenever I open Main activity.

Now, the second fragment is where I face issue. I have a fragment layout with some views as well as a Fragment java file. When ever I try to assign those views some value from the java file the app crashes. I have pasted both the code of my fragment xml file and java file as well as the error below.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    android:orientation="vertical"
    tools:context=".ProfileFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/up"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1.4">

            <com.scwang.wave.MultiWaveHeader
                app:mwhVelocity="2"
                app:mwhStartColor="@color/colorAccent"
                app:mwhCloseColor="@color/colorPrimaryDark"
                app:mwhGradientAngle="-90"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/waveview"
                />


            <TextView
                android:id="@+id/name_display"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="10dp"
                android:text="User"
                android:textColor="#ffff"
                android:textSize="25sp" />

        </RelativeLayout>

      
    </LinearLayout>
</FrameLayout>

My java file is:

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

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

    public ProfileFragment() {
        // 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 ProfileFragment.
     */
    // TODO: Rename and change types and number of parameters
    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;
    }

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

        }
    final TextView profile_name = getActivity().findViewById(R.id.name_display);
    profile_name.setText("Hi");
    }


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

}

The error I get is:

2021-01-27 15:31:22.641 29226-29226/com.appname.app E/AndroidRuntime: FATAL EXCEPTION: main Process: com.appname.app, PID: 29226 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.appname.app.ProfileFragment.onCreate(ProfileFragment.java:71) at androidx.fragment.app.Fragment.performCreate(Fragment.java:2586) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838) at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1197) at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1080) at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:119) at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866) at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824) at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727) at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:221) at android.app.ActivityThread.main(ActivityThread.java:7542) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

So The error I guess is somewhere around:

  profile_name.setText("Hi");

I have removed unnecessary code for simplicity.

question from:https://stackoverflow.com/questions/65917328/app-crashes-whenever-i-try-to-change-some-attribute-of-a-fragment-from-inside-th

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have your code defined here:

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

        }
    final TextView profile_name = getActivity().findViewById(R.id.name_display);
    profile_name.setText("Hi");
    }

but this isn't the correct lifecycle method to use for fragments, instead, you should override and make use of onViewCreated:

@Override
public void onViewCreated(@NotNull View view, @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // your code here
    
}

More info here, but specifically:

The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().

so at this point in time, there isn't yet a view, so that's why your code is crashing


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...