I'm trying to declare a Button on my APP (It's on a fragment), what I've tried is:
TextView tvPregunta = (TextView) getActivity().findViewById(R.id.tvPregunta);
It does not give me an error, but when I'm launching the APP it does...
My LogCat error is :
01-30 08:22:18.865 16165-16165/joancolmenero.taulaperiodica.com.taulaperiodicaapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: joancolmenero.taulaperiodica.com.taulaperiodicaapp, PID: 16165
java.lang.NullPointerException
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.seguentelement(JocFragment.java:102)
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.onCreateView(JocFragment.java:90)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
This line is the TextView tvPregunta. :
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.seguentelement(JocFragment.java:102)
And this one is seguentelement(); :
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.onCreateView(JocFragment.java:90)
seguentelement() it's a private void created out of onCreateView, so my question is why is this TextView crashing?
I've got a onCreateView where I've got the rootview and the calls of the voids...
onCreateView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.joc_fragment, container, false);
// Titol del joc
TextView tvJuego = (TextView) rootView.findViewById(R.id.tvJuego);
// shadow del textview
tvJuego.setShadowLayer(1, 0, 3, Color.GRAY);
// creem una variable per a cada ib
// NewGame HIDEEEEEEEEEE
NewGame = (Button)rootView.findViewById(R.id.btNewGame);
NewGame.setVisibility(View.INVISIBLE);
NewGame.setText("");
// IB --> ID imageButton
berijuego=(ImageButton)rootView.findViewById(R.id.ibBeriJuego);
borojuego=(ImageButton)rootView.findViewById(R.id.ibBoroJuego);
cobajuego=(ImageButton)rootView.findViewById(R.id.ibCobaJuego);
indijuego=(ImageButton)rootView.findViewById(R.id.ibIndiJuego);
hidrojuego=(ImageButton)rootView.findViewById(R.id.ibHidroJuego);
ununjuego=(ImageButton)rootView.findViewById(R.id.ibUnunJuego);
plutojuego=(ImageButton)rootView.findViewById(R.id.ibPlutoJuego);
radijuego=(ImageButton)rootView.findViewById(R.id.ibRadiJuego);
promjuego=(ImageButton)rootView.findViewById(R.id.ibPromJuego);
sodijuego=(ImageButton)rootView.findViewById(R.id.ibSodiJuego);
zicrojuego=(ImageButton)rootView.findViewById(R.id.ibZicroJuego);
molijuego=(ImageButton)rootView.findViewById(R.id.ibMoliJuego);
// setOnClickListener para todoos
berijuego.setOnClickListener(this);
borojuego.setOnClickListener(this);
cobajuego.setOnClickListener(this);
indijuego.setOnClickListener(this);
hidrojuego.setOnClickListener(this);
ununjuego.setOnClickListener(this);
plutojuego.setOnClickListener(this);
radijuego.setOnClickListener(this);
promjuego.setOnClickListener(this);
sodijuego.setOnClickListener(this);
zicrojuego.setOnClickListener(this);
molijuego.setOnClickListener(this);
//Nivellactual 12 MAX o aun quedan errores
if ((nivellactual <= 12) || (errores > 0)) {
nivellactual = nivellactual + 1;
seguentelement();
}
return rootView;
}
And then it crashes here :
public void seguentelement() {
switch (nivellactual) {
case 1:
TextView tvPregunta = (TextView) getActivity().findViewById(R.id.tvPregunta);
String pregunta = ("Quin element és el Hidrògen?");
tvPregunta.setText(pregunta);
// int de elemento es la imagebutton
elementcorrecte = (R.id.ibHidroJuego);
break;
Hope you can find my error.
You should not call getActivity() because it returns the parent Activity and NOT the fragment where your TextField is added.
see http://developer.android.com/reference/android/app/Fragment.html#getActivity%28%29
Instead, you can create a global variable TextField and instantiate it in onCreateView() by calling findViewId() of the rootView.
NOTE: Your TextView is in layout joc_fragment right?
TextView tvPregunta;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.joc_fragment, container, false);
...
tvPregunta = (TextView) rootView.findViewById(R.id.tvPregunta); // instantiate here
berijuego=(ImageButton)rootView.findViewById(R.id.ibBeriJuego);
...
return rootView;
}
public void seguentelement() {
switch (nivellactual) {
case 1:
//
String pregunta = ("Quin element és el Hidrògen?");
tvPregunta.setText(pregunta);
// int de elemento es la imagebutton
elementcorrecte = (R.id.ibHidroJuego);
break;
}
...
}
on your seguentelement() method
TextView tvPregunta = (TextView) getActivity().findViewById(R.id.tvPregunta);
here id of tvPregunta not generated so you have to put it on your OnCreateView() like
TextView tvPregunta = (TextView) rootView.findViewById(R.id.tvPregunta);
Inside Fragment class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
//or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
You should use ButterKnife to inject your views into your fragment, like so:
public class YourFragment extends Fragment {
#InjectView(R.id.btnSave)
public Button saveButton;
#OnClick(R.id.btnSave)
public void save(View view) {
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
ButterKnife.inject(this, rootView);
...
}
}
Add the following dependency to use it to your build.gradle file:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.jakewharton:butterknife:6.0.0'
Related
I am making my first app in android studio. So far I have built a bottom navigation bar using fragments. I am now trying to add a calendar feature to one of the fragments, I have copied a tutorial using activities to run the code and think there is a problem with using "View".
This is the code to open for the nav bar to open the fragment.
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.container,homeFragment).commit();
return true;
case R.id.calendar:
getSupportFragmentManager().beginTransaction().replace(R.id.container,calendarFragment).commit();
return true;
case R.id.wellbeing:
getSupportFragmentManager().beginTransaction().replace(R.id.container,wellbeingFragment).commit();
return true;
}
return false;
This is java in my calendar fragment, which when opened from the navigation bar crashes the app
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
initWidgets();
selectedDate = LocalDate.now();
setMonthView();
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
private void initWidgets()
{
calendarRecyclerView = requireView().findViewById(R.id.calendarRecyclerView);
monthYearText = requireView().findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(selectedDate));
ArrayList<String> daysInMonth = daysInMonthArray(selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(),7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
This is the error message I receive in my logcat
2022-05-12 12:45:05.305 10950-10950/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 10950
java.lang.IllegalStateException: Fragment CalendarFragment{c4de180} (94b1c782-ca39-403f-b45b-5d0d7a042f15 id=0x7f080087) did not return a View from onCreateView() or this was called before onCreateView().
at androidx.fragment.app.Fragment.requireView(Fragment.java:1964)
at com.example.myapplication.CalendarFragment.initWidgets(CalendarFragment.java:41)
at com.example.myapplication.CalendarFragment.onCreateView(CalendarFragment.java:30)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I believe there is no error in the calendar code and is something to do with onCreateView in the fragment code.
You cannot call requireView() before returning a non-null value from onCreateView().
Move these lines
initWidgets();
selectedDate = LocalDate.now();
setMonthView();
(where initWidgets() calls requireView()) from onCreateView() to e.g. onViewCreated().
Yes it crashes because findViewById wasn't called from the fragment_calendar layout before returning inflater therefore anything called after the return statement will not be executed and will return a NullPointerException. Unless you override onViewCreated method and put down the codes
So to avoid that, you need to override onViewCreated method or you must return view. Remember, if you want to return view then all codes or public methods must be reached before the return view statement. Else, it'll crash due to exception
Check this codes, it'll fix it correctly
public class TestFragment extends Fragment {
RecyclerView calendarRecyclerView;
TextView monthYearText;
#Nullable
#org.jetbrains.annotations.Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable #org.jetbrains.annotations.Nullable ViewGroup container, #Nullable #org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
selectedDate = LocalDate.now();
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable #org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initWidgets(view);
setMonthView();
}
private void initWidgets(View view) {
calendarRecyclerView = view.findViewById(R.id.calendarRecyclerView);
monthYearText = view.findViewById(R.id.monthYearTV);
}
private void setMonthView() {
monthYearText.setText(monthYearFromDate(selectedDate));
ArrayList<String> daysInMonth = daysInMonthArray(selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, getActivity());
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarAdapter.setAdapter(calendarAdapter);
}
}
I have been through a lot of posts here about starting an activity from a fragment, although none of them seem to be solving my problem. As i say, i am trying to start an activity from a class that extends a fragment. At the minute, when i remove the "android:onClick" from the xml, the button simply becomes dead and it does not let me click it. However when i put in the OnClick method to the xml i receive the following error:
java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'buttonViewDetails'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5653)
at android.view.View$PerformClick.run(View.java:22509)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6144)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I am not quite sure what this means. Here is the code that i have tried:
Button XML inside the class extending fragment:
<Button
android:id="#+id/buttonViewDetails"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#mipmap/info"
android:layout_marginLeft="250dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="14dp"
android:layout_marginBottom="14dp" />
Java Code for the class that extends fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.line_details, container, false);
Bundle extras = getArguments();
if (extras != null) {
String linetype = extras.getString("LineType");
TextView LT = (TextView) getActivity().findViewById(R.id.textViewLineType);
LT.setText(linetype);
Button InfoButton = (Button) getActivity().findViewById(R.id.buttonViewDetails);
InfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), VerifyLine.class);
startActivity(intent);
}
});
}
return myInflatedView;
}
Would anyone be able to help me out?
Thanks!
You are inflating a view myInflatedView and doing findViewById of that view using activity reference.So ust change that getActivity and use myInflatedView to find the Views.Also remove onClick for the button from xml.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.line_details, container, false);
TextView LT = (TextView) myInflatedView.findViewById(R.id.textViewLineType);
Button InfoButton = (Button) myInflatedView.findViewById(R.id.buttonViewDetails);
InfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), VerifyLine.class);
startActivity(intent);
}
});
Bundle extras = getArguments();
if (extras != null) {
String linetype = extras.getString("LineType");
LT.setText(linetype);
}
return myInflatedView;
}
I have a navigation drawer activity where i am attaching different fragments
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, rp_fragment.OnFragmentInteractionListener, sensors_fragment.OnFragmentInteractionListener, stats_fragment.OnFragmentInteractionListener {
I'm trying to modify the text property of a textview contained within a fragment but i keep getting a null pointer exception on the view (java.lang.NullPointerException: Attempt to invoke virtual method 'void com.teicrete.alucard.sempi.sensors_fragment.ctv_tvst(int)' on a null object reference).
Mainactivity:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_camera) {
ft.replace(R.id.fragment_placeholder, new rp_fragment());
ft.commit();
} else if (id == R.id.nav_gallery) {
ft.replace(R.id.fragment_placeholder, new sensors_fragment());
ft.commit();
gentempdata();
sensors_fragment sf = (sensors_fragment)fm.findFragmentById(R.id.fragment_sensors);
sf.ctv_tvst(1);
Fragment:
public class sensors_fragment 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";
TextView ctv_tv;
TextView otv_tv;
View view;
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors, container, false);
TextView ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
...
public void ctv_tvst(int mtext) {
ctv_tv.setText(mtext);
}
I've looked at similar posts here but i was not able to resolve my issue. The only place where i am able to modify the textview is within the onCreateView of the fragment (see code above). If i try to do it from the mainactivity or anywhere else i get the null pointer error.
Any insights?
Edit: Please see my response in android_griezmann's post.
For now, i am doing everything that i need to do, inside the fragment classes themselves and then i load them. I would still like to figure out why i can't access its methods or views externally.
Change those lines from onCreateView:
TextView ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)view.findViewById(R.id.otv_tv);
To:
ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
otv_tv = (TextView)view.findViewById(R.id.otv_tv);
Currently you are assigning reference to new object by TextView ctv_tv but actually you want this reference to be assigned to class field so you don't have to add TextView.
Your problem is Fragment itself not the TextView. You are getting fragment object as null not the textview.
So try to find the fragment like the below.
if (id == R.id.nav_gallery) {
ft.replace(R.id.fragment_placeholder, new sensors_fragment(),"YOUR_TAG_NAME");
ft.commit();
gentempdata();
sensors_fragment sf = (sensors_fragment) fm.findFragmentByTag("YOUR_TAG_NAME");
sf.ctv_tvst(1);
}
Also change this method too!
public void ctv_tvst(int mtext) {
ctv_tv.setText("" + mtext);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView ctv_tv = (TextView)getView().findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)getView().findViewById(R.id.otv_tv);
}
override onactivity created, and then refer your views.. Infact it is the best place to get reference to your views withot getting NullPointer Exception
If you want to pass data while replacing or adding then pass the data in your fragment constructor like below
else if (id == R.id.nav_gallery) {
ft.replace(R.id.fragment_placeholder, new sensors_fragment("your data"));
ft.commit();
Then in your fragmet change the textview value based on the constructor's data
Here is the problem. Just remove the TextView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors, container, false);
**TextView** ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
**TextView** otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
Replace the following code
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors,container, false);
TextView ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
TextView otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
with
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_sensors,container, false);
ctv_tv = (TextView)view.findViewById(R.id.ctv_tv);
otv_tv = (TextView)view.findViewById(R.id.otv_tv);
//ctv_tv.setText("Test"); Only this works
return view;
}
Create a variable String ctv_tv_string and assign the value in ctv_tvst() method do not assign to the TextView. it would not throw an error as you are not referring any ui element after this in oncreateview ctv_tv.setText(ctv_tv_string)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm starting with android and just getting crazy with the implements of multiple fragments.
I have two fragments in my MainActivity: QuestionDetail and QuestionListFragment.
When I use a fragment transactions to replace the QuestionDetail fragment when someone click in one of the QuestionListFragment options I get a NullPointerException error.
I have been trying to fix this issue for hours. Any help is greatly appreciated.
QuestionDetail
public class QuestionListFragment extends Fragment{
private RecyclerView recView;
public static QuestionAdapter adapter;
private QuestionListener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_question_list, container, false);
recView = (RecyclerView) v.findViewById(R.id.recView);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recView.setLayoutManager(layoutManager);
adapter = new QuestionAdapter(QuestionCatalog.getQuestionCatalog().getQuestionList().getList());
adapter.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (listener!=null) {
listener.onQuestionListener(adapter.getItem(recView.getChildAdapterPosition(v)));
}
}
});
recView.setAdapter(adapter);
}
public interface QuestionListener {
void onQuestionListener(Question q);
}
public void setQuestionListener(QuestionListener listener) {
this.listener=listener;
}
QuestionDetail
public class QuestionDetail extends Fragment {
// We use an ID to know which Question we're using
private long questionId;
public QuestionDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_question_detail, container, false);
}
#Override
public void onStart() {
super.onStart();
//Fragments don’t include findViewById(). To get a reference to a view, we use getView()
View view = getView();
if (view != null) {
TextView title = (TextView) view.findViewById(R.id.textQuestion);
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
title.setText(question.getName());
TextView kind = (TextView) view.findViewById(R.id.textKind);
kind.setText(question.getKind());
}
}
public void showDetails(String texto) {
TextView txtName = (TextView)getView().findViewById(R.id.textQuestion);
TextView txtKind = (TextView)getView().findViewById(R.id.textKind);
txtName.setText(texto);
txtKind.setText(texto);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements QuestionListFragment.QuestionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuestionListFragment frg =(QuestionListFragment)getFragmentManager().findFragmentById(R.id.listFragment);
frg.setQuestionListener(this);
}
#Override
public void onQuestionListener(Question q) {
Toast.makeText(this, "num: " + q.getName(),
Toast.LENGTH_LONG).show();
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
QuestionDetail f1 = new QuestionDetail();
f1.showDetails(q.getName());
t.replace(R.id.detailFragment,f1);
t.addToBackStack(null);
t.commit();
}
stacktrace
08-04 09:54:11.914 22277-22277/com.hfad.predictandwin E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.hfad.predictandwin.Fragments.QuestionDetail.showDetails(QuestionDetail.java:50)
at com.hfad.predictandwin.MainActivity.onQuestionListener(MainActivity.java:34)
at com.hfad.predictandwin.Fragments.QuestionListFragment$1.onClick(QuestionListFragment.java:55)
at com.hfad.predictandwin.QuestionAdapter.onClick(QuestionAdapter.java:61)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18786)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
First, don't use getView() in onStart() - You shouldn't have a view to get at that point. Second, you shouldn't be calling methods directly on the Fragment instances from elsewhere, in your case f1.showDetails(q.getName());. There, again, the Fragment has no View. Please see Best practice for instantiating a new Android Fragment for how to pass arguments into Fragment before you load it into the FragmentManager.
Next point - you should initialize your views using findViewById inside of onCreateView just like you did for the other Fragment class. For example,
private TextView txtName, txtKind;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_question_detail, container, false);
txtName = (TextView) rootView.findViewById(R.id.textQuestion);
txtKind = (TextView) rootView.findViewById(R.id.textKind);
// TODO: Read the link how to use these
Bundle arguments = getArguments();
Question question = QuestionCatalog.getQuestionCatalog()
.getQuestionList().getList().get((int) questionId);
showQuestion(question);
return view;
}
private void showQuestion(Question q) {
txtName.setText(q.getName());
txtKind.setText(q.getKind());
}
in QuestionListFragment:
We set click listener for recView, not adapter. You should replace adapter.setOnClickListener with
recView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recView, new ClickListener() {
#Override
public void onClick(View view, int position) {
// do something with position.
}
#Override
public void onLongClick(View view, int position) {
}
}));
in QuestionDetail:
questionId wasn't initialized but you have use it in this line:
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
Based on stacktrace and your code (not sure which one is line #50 in your QuestionDetail) ether txtName or txtKind evaluates to null (maybe both), so for whatever reason getView().findViewById(R.id.textQuestion) returns null. Probably because getView() in that call doesn't get you a parent view of the TextView in question
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am currently getting null pointer exception in a fragment while calling getHolder.
here's the Code for the fragment
public class Camera_Fragment extends Fragment implements IVideoPlayer, View.OnClickListener {
Button up, dowm, right, left;
SurfaceView CamView;
private String VideoUrl = "http://192.168.0.4:81/videostream.cgi?user=admin&password=admin";
private SurfaceHolder Holder;
private Surface surface = null;
private LibVLC libVLC;
private int mVideoHeight;
private int mVideoWidth;
private int mVideoVisibleHeight;
private int mVideoVisibleWidth;
private int mSarNum;
private int mSarDen;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cam1, container, false);
CamView = (SurfaceView) view.findViewById(R.id.Cam1_CamVIew);
up = (Button) view.findViewById(R.id.Cam_up);
dowm = (Button) view.findViewById(R.id.Cam_down);
right = (Button) view.findViewById(R.id.Cam_right);
left = (Button) view.findViewById(R.id.Cam_left);
up.setOnClickListener(Camera_Fragment.this);
dowm.setOnClickListener(Camera_Fragment.this);
right.setOnClickListener(Camera_Fragment.this);
left.setOnClickListener(Camera_Fragment.this);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cam_Play();
}
private void Cam_Play() {
Holder = CamView.getHolder();
try {
libVLC = new LibVLC();
libVLC.setVout(LibVLC.VOUT_ANDROID_SURFACE);
libVLC.setHardwareAcceleration(LibVLC.HW_ACCELERATION_AUTOMATIC);
libVLC.init(getActivity().getApplicationContext());
} catch (LibVlcException e) {
e.printStackTrace();
}
surface = Holder.getSurface();
libVLC.attachSurface(surface, this);
libVLC.playMRL(VideoUrl);
}
The above Code is working flawless in a Activity.. But in the fragment its not .. I am still a biggner in Android development.And i am using fragments for the first time. Any Solution or suggestion.
here's the logcat
11-17 01:03:52.301 5860-5860/com.fyp.tirz.wifisurveillance E/AndroidRuntime: FATAL EXCEPTION: main
11-17 01:03:52.301 5860-5860/com.fyp.tirz.wifisurveillance E/AndroidRuntime: Process: com.fyp.tirz.wifisurveillance, PID: 5860
11-17 01:03:52.301 5860-5860/com.fyp.tirz.wifisurveillance E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.SurfaceHolder android.view.SurfaceView.getHolder()' on a null object reference
11-17 01:03:52.301 5860-5860/com.fyp.tirz.wifisurveillance E/AndroidRuntime: at Fragments.Camera_Fragment.onCreate(Camera_Fragment.java:62)
Remove this.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cam_Play();
}
Add Cam_Play here instead.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cam1, container, false);
CamView = (SurfaceView) view.findViewById(R.id.Cam1_CamVIew);
up = (Button) view.findViewById(R.id.Cam_up);
dowm = (Button) view.findViewById(R.id.Cam_down);
right = (Button) view.findViewById(R.id.Cam_right);
left = (Button) view.findViewById(R.id.Cam_left);
up.setOnClickListener(Camera_Fragment.this);
dowm.setOnClickListener(Camera_Fragment.this);
right.setOnClickListener(Camera_Fragment.this);
left.setOnClickListener(Camera_Fragment.this);
Cam_Play(); //< ----------------( ADD IT HERE )
return view;
}