[android] Start an activity from a fragment

I have 2 fragments with on both fragments a button. When I press the button I'd like to start a new Activity. But I can't get it to work.

The error I'm getting: ERROR here: Type mismatch: cannot convert from mFragmentFavorite to Fragment

What am I doing wrong?

MyFragmentPagerAdapter

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

    final int PAGE_COUNT = 3;

    /** Constructor of the class */
    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    /** This method will be invoked when a page is requested to create */
    @Override
    public Fragment getItem(int arg0) {

        switch(arg0){

        case 0:
            return new FavoriteActivity();
                    //ERROR: Type mismatch: cannot convert from FavoriteActivity to Fragment


        case 1:
            return new SettingsActivity();


        default:
            return null;

        }       
    }

    /** Returns the number of pages */
    @Override
    public int getCount() {
        return PAGE_COUNT;
    }
}

FavoriteActivity

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class FavoriteActivity extends Activity{

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.main_favorite, container, false);


        OnClickListener listnr=new OnClickListener() {
            @Override
            public void onClick(View v) {
                  Intent i= new Intent("aFavorite");
                  startActivity(i);
            }
        };

          Button btn =(Button) v.findViewById(R.id.mainFavorite);
          btn.setOnClickListener(listnr);

          return v;
    }
}

If FavoriteActivity extends fragments, the error is gone but then I get an error at findViewById(R.id.mainFavorite); and the error is

The method findViewById(int) is undefined for the type FavoriteActivity

EDIT:

When I press the button in the fragment to start the activity then the app crashes this is my logcat

03-18 16:01:23.985: E/AndroidRuntime(1985): FATAL EXCEPTION: main
03-18 16:01:23.985: E/AndroidRuntime(1985): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=FavoriteActivityList }
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1569)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1420)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.app.Activity.startActivityForResult(Activity.java:3446)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.app.Activity.startActivityForResult(Activity.java:3407)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:826)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.support.v4.app.Fragment.startActivity(Fragment.java:838)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at com.example.spui.FavoriteActivity$1.onClick(FavoriteActivity.java:24)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.view.View.performClick(View.java:4211)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.view.View$PerformClick.run(View.java:17267)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.os.Handler.handleCallback(Handler.java:615)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.os.Looper.loop(Looper.java:137)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at android.app.ActivityThread.main(ActivityThread.java:4898)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at java.lang.reflect.Method.invoke(Method.java:511)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
03-18 16:01:23.985: E/AndroidRuntime(1985):     at dalvik.system.NativeStart.main(Native Method)

The answer is


I use this in my fragment.

Button btn1 = (Button) thisLayout
            .findViewById(R.id.btnDb1);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getActivity(), otherActivity.class);
            ((MainActivity) getActivity()).startActivity(intent);

        }
    });

    return thisLayout;
}

You should use getActivity() to launch activities from fragments

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

Also, you should be naming classes with caps: MFragmentActivity instead of mFragmentActivity.


If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

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

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.


with Kotlin I execute this code:

requireContext().startActivity<YourTargetActivity>()


Start new Activity From a Fragment:

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

Start new Activity From a Activity:

Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);

You may have to replace getActivity() with MainActivity.this for those that are having issues with this.


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 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 android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to android-fragmentactivity

Manage toolbar's navigation and back button from fragment in android Android check null or empty string in Android Hide/Show Action Bar Option Menu Item for different fragments Android ViewPager with bottom dots How can I access getSupportFragmentManager() in a fragment? Default Activity not found in Android Studio startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment Setting Custom ActionBar Title from Fragment Start an activity from a fragment Android - Activity vs FragmentActivity?