My main fragment code is not being executed - android

I am writing an android app using android studio. So far I have created a tabbed activity to be my main activity, and another activity that would be opened on a click of a button in one of the tabs in my main tabbed activity. The problem is that I have tried to accomplish this in a few ways but it seems like the code in my public View onCreateView just doesn't get executed at all. This is the code I'm trying to run:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button mainSignInButton = (Button) view.findViewById(R.id.mainSignInButton);
mainSignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity() ,LoginActivity.class);
startActivity(i);
}
});
return view;
}
I have also tried to add a simple toast message to this block of code to see if it gets executed but I didnt see the toast pop up as well...

First of all, delegate to Activity the startActivity(). Try something like follow on your fragment:
public class FragmentMain extends Fragment {
private OnInteractionListener mListener;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button mainSignInButton = (Button) view.findViewById(R.id.mainSignInButton);
mainSignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onClickSignInButton()
}
});
return view;
}
public interface OnInteractionListener {
void onClickSignInButton();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null
}
}
On your Activity try like follow:
public class MyActivity extends AppCompatActivity implements FragmentMain.OnInteractionListener {
...
#Override
public void onClickSignInButton() {
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
}
}

Related

How do I access a view from a Fragment from the Parent Activity?

Hi I am trying to find out how to replace a fragment by clicking on a button within a fragment.
I tried looking into this article but it did not work for me.
View view = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getView();
btnGoToSignUp = view.findViewById(R.id.btnGoToSignUp);
I tried this but it comes up with the error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.View android.support.v4.app.Fragment.getView()'
on a null object reference
You could just do this:
Interface:
public interface BtnClickable {
void myClickMethod(View v);
}
Fragment:
public class SomeFragment {
BtnClickable btnClickable;
//...onCreateView, etc.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_add_note, container, false);
Button btnGoToSignUp = root.findViewById(R.id.btnGoToSignUp);
btnGoToSignUp.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
btnClickable.myClickMethod(v);
}
});
}
public static void setClickListener(BtnClickable listener){
btnClickable=listener;
}
Activity:
class MyActivity implements BtnClickable {
//...onCreate etc instantiating your fragments
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filters);
SomeFragment.setClickListener(this);
}
public void myClickMethod(View v) {
// you can listen here for btn clicked
}
}

android- How to make an existing fragment implement an activity's listener?

I'm going from a Fragment -> Activity. In the activity I make an interface and when the user clicks a button I pass in a string to an interface object I create and call finish(). In the fragment I implement that interface and want to get that string. But in the activity I get a crash saying the listener is null.
public class SampleActivity extends AppCompatActivity
{
private Button button;
private MatchActivity.OnMatchCompleteListener onMatchCompleteListener;
public interface OnMatchCompleteListener
{
public void matchComplete(String matchID);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.someButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onMatchCompleteListener.matchComplete("finished");
finish();
}
});
}
}
Fragment
public class SampleFragment extends Fragment implements SampleActivity.OnMatchCompleteListener{
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_login , container, false);
return rootView;
}
#Override
public void matchComplete(String matchID) {
Log.d("TEST",matchID);
}
}
if you have your fragment in the R.layout.activity_main and your fragment id is R.id.fragment use this:
onMatchCompleteListener =
((SampleFragment)getFragmentManager().findFragmentById(R.id.fragment))
otherwise use this solution:
SampleFragment fragment = new SampleFragment();
onMatchCompleteListener = fragment;
getFragmentManager().beginTransaction().add(R.layout.activity_main, fragment, "TAG_SIMPLE").commit();

Which of the following is the proper way to implement a callback.

So question. Which of the two is the proper way to do a callback?(Unless both of these are incorrect) Or does it depend on the case.
For example. Let's say i wanted to return something from a Fragment to its Activity.
1)I implement an interface in the Fragment and then on its onAttach I set the listener, and then implement the interface in the activity.
public class UrgentCareFragment{
public interface TestListener {
void finishedTest();
}
TestListener mEventListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_urgent_care_viewpager_fragment, container, false);
mEventListener.finishedTest();
return v;
}
#TargetApi(23)
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mEventListener = (TestListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement urgentCareListener");
}
}
/*
* Deprecated on API 23
* Use onAttachToContext instead
*/
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < 23) {
try {
mEventListener = (TestListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement urgentCareListener");
}
}
}
}
Activity Class.
public class testActivity extends AppCompatActivity implements TestListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urgent_care);
}
#Override
public void finishedTest(){
//do what you need to do
}
}
2) I create an interface class. In the Fragment I set the listener to the activities context by using getActivity. And then implement the interface in the activity.
Interface Class
public interface TestListener {
void finishedTest();
}
Fragment
public class UrgentCareFragment{
TestListener mEventListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEventListener = (TestListener) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_urgent_care_viewpager_fragment, container, false);
mEventListener.finishedTest();
return v;
}
}
Activity Class.
public class testActivity extends AppCompatActivity implements TestListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urgent_care);
}
#Override
public void finishedTest(){
//do what you need to do
}
}
Which is the correct way? My main concern is the way the listener is set. Could either of these two cause issues. Or is there one i should throw out. Both seem to work properly, I am just trying to make sure what the correct way is, or if both are fine.
Thanks

FragmentTransaction within Fragment

im a new guy on this programming world so i guess this question is simple. So I have one imagebutton on my fragment and I whatI want is that when I click on it, it does a fragment transaction to another fragment; but the thing is that when I run the app and click on the imagebutton, it only "superimposes" the content of the other fragment into the one where the imagebutton is, of course what i want to do is just to go to the other fragment, ive been dealing with this for a while so I hope someone helps me, thanks.
Here is my java code of the fragment
public class inicio extends Fragment {
public inicio() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_inicio,container,false);
ImageButton luces = (ImageButton)view.findViewById(R.id.imageButton);
luces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
interior interior= new interior();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.inicioo, interior).commit();
}
});
}
}
New code added...
public class transaction extends MainActivity
implements com.example.administradora.prueba.inicio.OnSelectedListener{
public void onButtonSelected() {
interior interior= new interior();
getSupportFragmentManager().beginTransaction().replace(R.id.inicioo, interior).commit();
}
}
but i get this error in the logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.administradora.prueba/com.example.administradora.prueba.MainActivity}: java.lang.ClassCastException: com.example.administradora.prueba.MainActivity#20f8fe9b must implement OnSelectedListener
You shouldn't replace a Fragment from another Fragment. Try to do that through the Activity.
Define some interface for the Fragment to hold
public class MyFragment extends Fragment {
OnSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnSelectedListener {
public void onButtonSelected();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnSelectedListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSelectedListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_inicio,container,false);
ImageButton luces = (ImageButton)view.findViewById(R.id.imageButton);
luces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Send the event to the host activity
if (mCallback != null) mCallback.onButtonSelected();
}
});
return view;
}
}
And swap the Fragment container in the interface implementation from the Activity.
public class MainActivity extends Activity
implements MyFragment.OnSelectedListener{
...
public void onButtonSelected() {
interior interior= new interior();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.inicioo, interior)
.commit();
}
}
The first two sections of Communicating with Other Fragments is what you are looking for.

Calling activity method from fragment NullPointerException

I have a problem with accessing activity's method from fragment.
Or anything int the activity from the fragment.
Here's fragment code:
public class MainFragment extends Fragment {
private MainActivity ma = (MainActivity) getActivity();
public SipAudioCall call = null;
public SipManager mSipManager = null;
public SipProfile mSipProfile = null;
public MainFragment() {
// TODO Auto-generated constructor stub
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.main_layout, container, false);
final Button callbtn = (Button) mLinearLayout.findViewById(R.id.callbtn);
final Button endbtn = (Button) mLinearLayout.findViewById(R.id.endbtn);
callbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callbtn.setVisibility(View.GONE);
endbtn.setVisibility(View.VISIBLE);
ma.initiateCall();
}
});
Maybe casting the activity is wrong?
Thx in advance
I'm guessing that the fragment is not attached to the activity when u call getActivity(). Try to initialize the activity reference in the fragment method onAttach().
So something like this:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
ma = (MainActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " Not MainActivity class instance");
}
}

Categories

Resources