[android] Intent from Fragment to Activity

I was trying to go to another page using button, but it always fail.

Here is my First Class with its XML:

public class FindPeopleFragment extends Fragment {
    public FindPeopleFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        return rootView;
    }

    public void goToAttract(View v)
    {
        Intent intent = new Intent(getActivity().getApplication(), MainActivityList.class);
        startActivity(intent);
    }
}

Here is my XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:layout_marginBottom="48dp"
    android:onClick="goToAttract"
    android:text="Button" /></RelativeLayout>

Here is my stacktrace..this is the result when i used onclicklistener

12-30 16:54:28.006: E/AndroidRuntime(992): FATAL EXCEPTION: main
12-30 16:54:28.006: E/AndroidRuntime(992): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.slidingmenu/info.androidhive.slidingmenu.MainActivityList}: android.view.InflateException: Binary XML file line #7: Error inflating class <unknown>
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.os.Looper.loop(Looper.java:137)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.app.ActivityThread.main(ActivityThread.java:4340)
12-30 16:54:28.006: E/AndroidRuntime(992):  at java.lang.reflect.Method.invokeNative(Native Method)
12-30 16:54:28.006: E/AndroidRuntime(992):  at java.lang.reflect.Method.invoke(Method.java:511)
12-30 16:54:28.006: E/AndroidRuntime(992):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-30 16:54:28.006: E/AndroidRuntime(992):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-30 16:54:28.006: E/AndroidRuntime(992):  at dalvik.system.NativeStart.main(Native Method)
12-30 16:54:28.006: E/AndroidRuntime(992): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class <unknown>
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.view.LayoutInflater.createView(LayoutInflater.java:606)
12-30 16:54:28.006: E/AndroidRuntime(992):  at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.view.LayoutInflater.onCreateView(LayoutInflater.java:653)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:678)
12-30 16:54:28.006: E/AndroidRuntime(992):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:

This question is related to android xml android-fragments fragment

The answer is


Hope this code will help

public class ThisFragment extends Fragment {

public Button button = null;
Intent intent;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.yourlayout, container, false);

    intent = new Intent(getActivity(), GoToThisActivity.class);
    button = (Button) rootView.findViewById(R.id.theButtonid);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(intent);
        }
    });
    return rootView;
}

You can use this code, make sure you change "ThisFragment" as your fragment name, "yourlayout" as the layout name, "GoToThisActivity" change it to which activity do you want and then "theButtonid" change it with your button id you used.


public class OneWayFragment extends Fragment {

    ImageView img_search;


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.one_way_fragment, container, false);
        img_search = (ImageView) view.findViewById(R.id.search);


        img_search.setOnClickListener(new View.OnClickListener() {
            @Override`enter code here`
            public void onClick(View v) {
                Intent displayFlights = new Intent(getActivity(), SelectFlight.class);
                startActivity(displayFlights);
            }
        });

in your receiving intent use as

Intent intent = getActivity().getIntent();
        ((TextView)view.findViewById(R.id.hello)).setText(intent.getStringExtra("Hello"));

and in your send intent

Intent intent = new Intent(getActivity(),Main2Activity.class);
        intent.putExtra("Hello","Nisar");
        getActivity().startActivity(intent);

remember both are in fragments


use this

public void goToAttract(View v)
{
    Intent intent = new Intent(getActivity(), MainActivityList.class);
    startActivity(intent);
}

be sure you've registered MainActivityList in you Manifest


If you can get a View in that fragment, you can access the context from there:

view.getContext().startActivity(intent);

You need to use getActivity() method from fragment for Intents.

Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);

Try this code once-

public class FindPeopleFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home,
        container, false);
        Button button = (Button) rootView.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        updateDetail();
        }
        });
        return rootView;
        }

public void updateDetail() {
        Intent intent = new Intent(getActivity(), MainActivityList.class);
        startActivity(intent);
        }
}

And as suggested by Raghunandan remove below code from your fragment_home.xml-

android:onClick="goToAttract"

 FragmentManager fragmentManager =  getFragmentManager();
 fragmentManager.beginTransaction().replace(R.id.frame, new MySchedule()).commit();

MySchedule is the name of my java class.


use getContext() instead of MainActivity.this

Intent intent = new Intent(getContext(), SecondActivity.class);
startActivity(start);

Remove this

android:onClick="goToAttract"

Then

View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Button b = (Button)rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
     public void onClick(View v)
     {
        Intent intent = new Intent(getActivity(), MainActivityList.class);
        startActivity(intent);

     } 

});
return rootView;

The error says you need to public void goToAttract(View v) in Activity class

Could not find method goToAttract(View) in the activity class

Reason pls check the answer by PareshMayani @

Android app crashing (fragment and xml onclick)

Edit:

Caused by: java.lang.OutOfMemoryError

I guess you have a image that is too big to fit in and it needs to be scaled down. Hence the OutOfMemoryError.


For Kotlin you can use

val myIntent = Intent(activity, your_destination_activity::class.java)
startActivity(myIntent)

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to fragment

FragmentActivity to Fragment Handling back button in Android Navigation Component android.content.Context.getPackageName()' on a null object reference Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment How to move from one fragment to another fragment on click of an ImageView in Android? Android - save/restore fragment state Intent from Fragment to Activity Get the Application Context In Fragment In Android? Add Items to ListView - Android Using onBackPressed() in Android Fragments