107

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)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
mXX
  • 3,595
  • 12
  • 44
  • 61

7 Answers7

287

mFragmentFavorite in your code is a FragmentActivity which is not the same thing as a Fragment. That's why you're getting the type mismatch. Also, you should never call new on an Activity as that is not the proper way to start one.

If you want to start a new instance of mFragmentFavorite, you can do so via an Intent.

From a Fragment:

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

From an Activity

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

If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent.

Also, I recommend changing your class names to be more accurate. Calling something mFragmentFavorite is improper in that it's not a Fragment at all. Also, class declarations in Java typically start with a capital letter. You'd do well to name your class something like FavoriteActivity to be more accurate and conform to the language conventions. You will also need to rename the file to FavoriteActivity.java if you choose to do this since Java requires class names match the file name.

UPDATE

Also, it looks like you actually meant formFragmentFavorite to be a Fragment instead of a FragmentActivity based on your use of onCreateView. If you want mFragmentFavorite to be a Fragment then change the following line of code:

public class mFragmentFavorite extends FragmentActivity{

Make this instead read:

public class mFragmentFavorite extends Fragment {
Michael Celey
  • 12,645
  • 6
  • 57
  • 62
  • Okay, I'll update the code in the first post. But I don't quite understand the mContextReference. I'll update the code with what I have and better names, give me 5 min – mXX Mar 18 '13 at 14:56
  • It's an example of a reference to a `Fragment` or an `Activity`. If you're using the code inside of one of those classes then you can just replace `mContextReference` with either `getActivity()` for `Fragment` or `this` for `Activity` on the first line and `this` for the second line. I'll update the answer to be more clear. – Michael Celey Mar 18 '13 at 15:00
  • Okay, I updated the question with better names and the advice you gave me. I'll try now to implement your suggestion to try and make it work. Thanks for the help – mXX Mar 18 '13 at 15:10
  • Yeah I've changed it back to Fragment but I get the error on the btn to find the ID "The method findViewById(int) is undefined for the type FavoriteActivity" – mXX Mar 18 '13 at 15:13
  • 2
    If you make it a `Fragment` then change `findViewById` to `v.findViewById`. There is no `findViewById` function in `Fragment` so you have to call `getView` first then call `findViewById` on that. In your case though, you already have your view in `onCreateView` and that would be your variable `v`. – Michael Celey Mar 18 '13 at 15:18
  • I understand thanks. But when I press the btn to go to the new activity, the app crashes – mXX Mar 18 '13 at 16:03
  • Make sure your new `Activity` is registered in your manifest. If your original question has been answered here then I'd suggest marking an answer as accepted by clicking the check mark beneath the voting arrows and asking a new question outlining the error/crash you're getting with a copy of the stack trace. Here's a good place to start with your crash though: http://stackoverflow.com/questions/4481903/how-to-register-a-new-activity-in-manifest-xml – Michael Celey Mar 18 '13 at 16:09
  • I get nulllpointerexception. My activity is registered in manifest. – Confuse Sep 26 '14 at 11:14
  • Do you add a `finish();` in the end or you don't? – 4127157 Oct 15 '16 at 21:17
  • Calling `finish()` is entirely use case based. If you're trying to start a new activity while closing the current one, then yes. However, that breaks the stack-based navigation that you get with activities so you have to make sure that you really want to do that instead of maybe finding a better navigation pattern. Now if you're referring to closing the new activity after it's been started, you can do so in code with the `finish()` method or the user can utilize the back button to close the newly started activity. – Michael Celey Oct 15 '16 at 22:52
  • Don't forget to declare also the `Activity` in your `AndroidManifest.xml` like that: `` – Ole Pannier Apr 09 '21 at 21:42
24

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.

liarspocker
  • 2,434
  • 3
  • 17
  • 26
6

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.

Jayakrishnan
  • 4,457
  • 29
  • 29
  • 'If you are using getActivity() then you have to make sure that the calling activity is added already.'- What does this line mean to a newbie? – Palak Jain Apr 07 '19 at 18:00
  • @PalakJain That means activity's state (Active to Destroyed) keep on changing depending on x reasons. An activity should be in active state when you perform anything on it. Activity is in active state if its life in between onResume and onPause. – Jayakrishnan Apr 09 '19 at 15:09
  • Well, that makes sense. Thanks! – Palak Jain Apr 11 '19 at 21:58
3

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;
}
Sara Zakizadeh
  • 137
  • 1
  • 8
2

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);
Abhay Bhusari
  • 139
  • 1
  • 1
1

with Kotlin I execute this code:

requireContext().startActivity<YourTargetActivity>()

Alexandr Kolesnik
  • 1,929
  • 1
  • 17
  • 30
  • 2
    When I try this code I get: ```None of the following functions can be called with the arguments supplied. startActivity(Intent!) defined in android.content.Context startActivity(Intent!, Bundle?) defined in android.content.Context``` – Tim Oct 18 '20 at 01:06
  • @Tim You'll probably need the [Android KTX](https://developer.android.com/kotlin/ktx) in order for the code to work. – Edric Oct 26 '20 at 12:23
  • getContext().startActivity(new Intent(getContext(), ActivityB.class)); – midou Mar 12 '21 at 16:44
0

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

ADL
  • 2,707
  • 1
  • 16
  • 23