findViewById() in Fragment returns null - java

Im trying to get the TextViews shown in my faq_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/question_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:text="Title 1"/>
<TextView
android:id="#+id/answer_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:text="Description 1"
android:textColor="#33000000"
android:layout_marginTop="5dp"/>
</LinearLayout>
In my Fragment class
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((TextView)container.findViewById(R.id.question_text)).setText(title);
((TextView)container.findViewById(R.id.answer_text)).setText(description);
return inflater.inflate(R.layout.faq_fragment, container, false);
}
App is crashing and Im getting error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

You need to inflate the view before using it.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.faq_fragment, container, false);
((TextView)view .findViewById(R.id.question_text)).setText(title);
((TextView)view .findViewById(R.id.answer_text)).setText(description);
return view;
}

You should use the inflated view:
Change it to:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.faq_fragment, container, false);
((TextView)view.findViewById(R.id.question_text)).setText(title);
((TextView)view.findViewById(R.id.answer_text)).setText(description);
return view;
}

Related

Why is my app Crashing with RecyclerView?

I'm doing a recycler method in my android studio project but i have a problem.
Everytime i'm trying to findViewById my application is crashing.
Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
And i don't understand why because i'm creating my view in the good way.
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carrito, container, false);
return view;
}
And i'm trying to continue with that
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
...
Log.e("test : ",Integer.toString(R.id.recyclerBuy));
recyView = view.findViewById(R.id.recyclerBuy);
/* recyView.setLayoutManager(new GridLayoutManager(getContext(),RecyclerView.VERTICAL));
recyView.setAdapter(buyAdapter);
*/
}
But i'm crashing at the line recyView = view.findViewById(R.id.recyclerBuy);. My R.id.recyclerBuy is not empty.
And here is my RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ui.carrito.CarritoFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerBuy"
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginBottom="88dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
...
</androidx.constraintlayout.widget.ConstraintLayout>
Anyone have a clue why i'm crashing everytime ?
This happens because onAttach() callback is called before onCreateView().
The easiest way to fix the issue is placing the code where you finding your RecyclerView in onCreateView(). Something like:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carrito, container, false);
recyView = view.findViewById(R.id.recyclerBuy);
// here you recyView won't be null
return view;
}
A good article about fragments lifecycle: https://medium.com/androiddevelopers/the-android-lifecycle-cheat-sheet-part-iii-fragments-afc87d4f37fd

Can't set text to TextView in Android Studio

I had this problem with every TextView. I tried a lot of things but i just can't manage to make it work. If you have any suggestion, please help.
I'm begginer in android but I think this is simple problem, but i just can't fix it.
Thanks in advance.
Code for fragment Home
package com.example.mmreviews;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
View view = lf.inflate(R.layout.fragment_home, container, false);
view.findViewById(R.id.btn_edit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.fragment_container, new EditFragment()).commit();
}
});
view.findViewById(R.id.btn_logout).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LogIn.class);
startActivity(intent);
}
});
TextView textViewUsernameInfo = view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
return view;
}
}
Xml for text i want to set. Maybe i should try some other text view?
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/text1"
android:layout_toRightOf="#id/text1"
android:textColor="#4B83E5"
android:textSize="16sp">
</TextView>
exception that I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmreviews, PID: 6184
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmreviews/com.example.mmreviews.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.mmreviews.HomeFragment.onCreateView(HomeFragment.java:38)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1340)
at android.app.Activity.performStart(Activity.java:7200)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6944) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 
Try this:
TextView textViewUsernameInfo = (TextView)view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
For some reason, you have two inflaters
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//LayoutInflater inflater also inflater, but you decalre another inflater
LayoutInflater lf = getActivity().getLayoutInflater();
//and i assume you try to get lf LayoutInflater from Activity not from Fragment
View view = lf.inflate(R.layout.fragment_home, container, false);
...
}
Try to remove
LayoutInflater lf = getActivity().getLayoutInflater();
and change your view to
assert inflater != null;//not required but try to add
View view = inflater.inflate(R.layout.fragment_home, container, false);
According to docs: onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment and LayoutInflater object can be used to inflate any views in the fragment.
Docs about fragment
UPD: I won't able to recreate your error.
I created simple XML for the main activity and for fragment separately
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="com.example.test.MainFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
main_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainFragment">
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#4B83E5"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
<Button
android:id="#+id/btn_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Created Fragment class and left MainActivity with default
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.main_activity);
}
}
Fragment class
public class MainFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment, container, false);
Button button1 = view.findViewById(R.id.btn_edit);
button1.setOnClickListener(v -> Toast.makeText (requireContext (),"short1",Toast.LENGTH_SHORT).show ());
Button button2 = view.findViewById(R.id.btn_logout);
button2.setOnClickListener(v -> Toast.makeText (requireContext (),"short2",Toast.LENGTH_SHORT).show ());
TextView textViewUsernameInfo = view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
return view;
}}
It is working fine without throwing NullPointerException for me.
You can try ViewBinding from Android Devs or ButterKnife third-party library from JakeWharton (it is deprecated as for 2021 and wouldn't have further updates, because ViewBinding does the same - still you can use it.)

PDF viewer in fragments?

I've made an app and that includes fragments.My PDF viewer works perfectly fine but not in fragments.How can I fix that ? I have asset files and everything.Compiled git hub reference, XML just having trouble with fragments.Thank You
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
//pdfView = getView().findViewById(R.id.pdfView);
//pdfView.fromAsset("tenor-madness.pdf").load();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab1, container, false);
}
XML FİLE
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="liselimanyak.practice.Tag2">
<!-- TODO: Update blank fragment layout -->
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_centerInParent="true"
android:layout_height="match_parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tab1"
android:layout_centerInParent="true"
android:textSize="30dp"/>
</RelativeLayout>
You can't call findViewById() in onCreate() ....do it in onCreateView (using something like following)...or alternatively in onViewCreated (using the view param)
View v = inflater.inflate(R.layout.fragment_tab1, container, false;
pdfView = v.findViewById(R.id.pdfView);
...or, if using onViewCreated
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pdfView = view.findViewById(R.id.pdfView);
pdfView.fromAsset("tenor-madness.pdf").load();
}

Can't change text of textView dynamically when using ViewPager and Fragments

I'm simply trying to change the text of a textView that is located within the actual fragment. It isn't throwing any error but it simply isn't updating. Aside from this the fragment successfully attaches to the activity via a viewpager.
The fragment:
public class FragmentPlotData extends Fragment {
public static TextView textViewPlotData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_plot_data, container, false);
textViewPlotData = (TextView) view.findViewById(R.id.textViewPlotData);
textViewPlotData.setText("Changed text ");
return inflater.inflate(R.layout.fragment_plot_data, container, false);
}
}
The fragment's layout:
<TextView
android:id="#+id/textViewPlotData"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:textColor="#color/black_process_2"
android:text="#string/original text"
android:gravity="center"/>
</RelativeLayout>
You should return view in onCreateView, don't inflate a new layout like that.
Just replace:
return inflater.inflate(R.layout.fragment_plot_data, container, false);
to:
return view;

Fragment Dialog without Title issue

i'm trying to create a fragment dialog and need the full space to display information. so i want to disable the titlebar. But after i disabled it the isn't maximized in width anymore.
public class ArticleSearchFragment extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, getTheme());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.article_search, container, false);
...
}
And the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/searchField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Ean / Name / Produkt Nummer"
android:completionThreshold="1" />
<Button
android:id="#+id/cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/cancel" />
</LinearLayout>
put this code in your onCreateView() of dialog fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_image, null);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
It will remove title bar from Dialog Fragment

Categories

Resources