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;
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am currently trying to create a calendar app in android studio. The app contains a calendar with different "Views" e.g. monthly view, weekly view, and daily view.
The app uses fragments as pages and each view is an activity.
This is the code for the fragment and buttons to initialise each view
public class CalendarFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
Button btn1 = (Button) v.findViewById(R.id.openCalendar);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(),CalendarActivity.class);
startActivity(intent);
}
});
Button btn2 = (Button) v.findViewById(R.id.openWeek);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), WeekViewActivity.class);
startActivity(intent);
}
});
return v;
}
The first button which displays the monthly view of the calendar called "CalendarActivity" in code works fine but when the second button is clicked which displays the weekly view of the calendar, causes the app to crash and gives the following error in the logcat
2022-05-13 14:44:59.642 15183-15183/com.example.finalyearproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalyearproject, PID: 15183
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalyearproject/com.example.finalyearproject.WeekViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3685)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at com.example.finalyearproject.CalendarUtils.monthYearFromDate(CalendarUtils.java:16)
at com.example.finalyearproject.WeekViewActivity.setWeekView(WeekViewActivity.java:40)
at com.example.finalyearproject.WeekViewActivity.onCreate(WeekViewActivity.java:29)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Activity.performCreate(Activity.java:8034)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1341)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
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 am not sure what the problem is as I have been following a tutorial and the other features work. I have also included the code for each activity below.
Monthly View
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void nextMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusMonths(1);
setMonthView();
}
public void previousMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusMonths(1);
setMonthView();
}
Weekly View
public class WeekViewActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);
initWidgets();
setWeekView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setWeekView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> days = daysInWeekArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(days, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void previousWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusWeeks(1);
setWeekView();
}
public void nextWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusWeeks(1);
setWeekView();
}
Any suggestions would be greatly appreciated.
My suggestions:
Firstly you didn't initialized CalendarUtils.selectedDate
Cover code with breakpoints for. debugging or with Log.d() messages to find, which variable is null
I have created an activity that I am using for barcode scanning. The onCreate looks like this:
public class GradeScreenScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
public static final int REQUEST_CAMERA = 1;
protected ZXingScannerView scannerView;
protected FirebaseFirestore db;
protected String scanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
db = FirebaseFirestore.getInstance();
}
}
Once I have a result I am then wanting to launch a new fragment like so:
android.app.FragmentManager fragmentManager = getFragmentManager();
ScreenFragment screenFragment = new ScreenFragment();
screenFragment.db = db;
screenFragment.serialNumberScanned = serialNumberScanned;
fragmentManager.beginTransaction()
.addToBackStack("screen")
.replace(R.id.content_frame, screenFragment)
.commit();
But I get the following error that I am not sure how to deal with:
java.lang.IllegalArgumentException: No view found for id 0x7f08005a (uk.wefix:id/content_frame) for fragment ScreenFragment{6262536 #1 id=0x7f08005a}
Just in case, the fragments onCreate looks like this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.grade_screens_layout, container, false);
return myView;
}
Help appreciated.
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_frame"/>
Was missing from the xml in the activity view. My error, well spotted Umair
yes , usually when you get No view found for id or nullPointer i suggest you to check:
1-android:id="#+id/
2- findViewById
3- in the java class the variable declaration
in most cases it works ;)
good luck.
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
I'm quite new working with Android/Java, so please bear with me.
I moved code from LoginActivity > onCreate into a fragment I created FragmentLogin to method onCreate where many classes no longer resolve, such as findViewById. I'm assuming that somewhere I didn't pass the context of the container Activity properly.
Or some other newbie mistake...
Here is LoginActivity.java [relevant parts copied]
public class LoginActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize Fragments //
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
setContentView(R.layout.fragment_login);
}
}
and FragmentLogin.java:
public class FragmentLogin extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
final ValidationManager Check = new ValidationManager();
final SessionManager Session = new SessionManager(this);
final EditText textEmail = (EditText) findViewById(R.id.login_email);
final EditText textPassword = (EditText) findViewById(R.id.login_pass);
final Button buttonLogIn = (Button) findViewById(R.id.button_login);
final Button buttonSignup = (Button) findViewById(R.id.button_signup);
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final Button forgottenPassword = (Button) findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.fragment_forgotten_password);
}
});
... more code ...
}
}
The variables/methods that were working when the second block of code was residing in the onCreate method of the Activity but no longer resolve after I moved the code to onCreateView of the FragmentLogin fragment class:
findViewById, setContentView
Basically, this is a login form where the default fragment should be login, and a button on that page (Button forgottenPassword) would open another fragment (FragmentForgottenPassword).
Can anyone tell me what I'm doing wrong?
In your activity layout xml file, add something similar to this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="your.package.FragmentLogin"
android:id="#+id/fragment_login"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
In your LoginActivity: remove the fragment manager stuff. You don't need it yet.
public class LoginActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
}
}
In your FragmentLogin, move the return statement to the end and use the inflated view to find your views by id:
public class FragmentLogin extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final view view = inflater.inflate(R.layout.fragment_login, container, false);
final ValidationManager Check = new ValidationManager();
final SessionManager Session = new SessionManager(this);
final EditText textEmail = (EditText) view.findViewById(R.id.login_email);
final EditText textPassword = (EditText) view.findViewById(R.id.login_pass);
final Button buttonLogIn = (Button) view.findViewById(R.id.button_login);
final Button buttonSignup = (Button) view.findViewById(R.id.button_signup);
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final Button forgottenPassword = (Button) view.findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.fragment_forgotten_password);
}
});
... more code ...
return view;
}
}
You should get subviews from layout while it's being inflated. The layout usually inflated in OnCreateView method.
View layout = inflater.inflate( R.layout.fragment_login, null );
final EditText textEmail = (EditText) layout.findViewById(R.id.login_email);
final EditText textPassword = (EditText) layout.findViewById(R.id.login_pass);
...
return layout;
I am guessing you want to the fragment to be shown within the activity. Try this:
public class LoginActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//put the setContentView() before the fragment initialization also, I noticed your activity layout is the same as your fragment layout,this should not be so, hence I changed that
setContentView(R.layout.activity_login);
// Initialize Fragments //
//you did not initialize the fragments completely, it should be like
//this
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.fragment_container, new FragmentLogin()).commit();
}}
then in the Login fragment, it should be like this:
public class FragmentLogin extends Fragment {#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_login, container, false);
final ValidationManager Check = new ValidationManager();
final SessionManager Session = new SessionManager(this);
final EditText textEmail = (EditText) view.findViewById(R.id.login_email);
final EditText textPassword = (EditText) view.findViewById(R.id.login_pass);
final Button buttonLogIn = (Button) view.findViewById(R.id.button_login);
final Button buttonSignup = (Button) view.findViewById(R.id.button_signup);
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final Button forgottenPassword = (Button) view.findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//you cant call setContentView in a fragment
}
});
... more code ...
}}
I am not totally sure I caught all your mistakes but I think you should read these: one and two; they are online tutorials on fragments, you can also browse for more. I think it is a good starting point. All the best
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'