Home » Android » android – java.lang.NoSuchMethodError when use getFragmentManager() with actionbarsherlock library

android – java.lang.NoSuchMethodError when use getFragmentManager() with actionbarsherlock library

Posted by: admin June 15, 2020 Leave a comment

Questions:

My own project uses:

<uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="13" />

To implement action bar, I uses ActionBarSherlock library. I imported the sherlock library into my Eclipse as an existing project. For sherlock, the target platform is Android v3.2 API 13 .

Then, I added sherlock as a library project to my own project. I saw there is Library projects under my own project. Everything seem goes well.

My own project main Activity looks like this:

package com.test;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MyActivity extends FragmentActivity {

    /**
     * hosts a Fragment, and the Fragment will inflate a layout to show
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FragmentManager fragMgr;
        FragmentTransaction fragTrans;

        fragMgr = getFragmentManager(); //error complains here


           FirstFragment list = new FirstFragment();

        fragTrans = fragMgr.beginTransaction();
        fragTrans.add(android.R.id.content, list).commit();

    }
}

But, when I run my application, I got the following error:

java.lang.NoSuchMethodError: com.test.MyActivity.getFragmentManager

Why getFragment can not be resolved as a method?? I have used sherlock as a project library for my own project…

How to&Answers:

The method getFragmentManager() is available only since 3.0, in the Activity class. Since your target sdk is 13, and FragmentActivity extends from Activity there are no problems at compilation time.

But when you run your code on a lower sdk (7 for example) there is no such method in that Activity class. So the solution is to use :

 getSupportFragmentManager();

which will work on all Android versions.

Answer:

You need to use

FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();

and make sure you are importing:

import android.support.v4.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;