Question

I built my application yesterday and it worked fine, and then i tried it again later on and it just came up with the error message

Log Cat

03-04 08:32:17.238: D/AndroidRuntime(836): Shutting down VM
03-04 08:32:17.238: W/dalvikvm(836): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-04 08:32:17.248: E/AndroidRuntime(836): FATAL EXCEPTION: main
03-04 08:32:17.248: E/AndroidRuntime(836): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.fragments/com.example.android.fragments.MainActivity}: java.lang.ClassCastException: com.example.android.fragments.MainActivity@40ce2278 must implement OnHeadlineSelectedListener
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.os.Looper.loop(Looper.java:137)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.ActivityThread.main(ActivityThread.java:5041)
03-04 08:32:17.248: E/AndroidRuntime(836):  at java.lang.reflect.Method.invokeNative(Native Method)
03-04 08:32:17.248: E/AndroidRuntime(836):  at java.lang.reflect.Method.invoke(Method.java:511)
03-04 08:32:17.248: E/AndroidRuntime(836):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-04 08:32:17.248: E/AndroidRuntime(836):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-04 08:32:17.248: E/AndroidRuntime(836):  at dalvik.system.NativeStart.main(Native Method)
03-04 08:32:17.248: E/AndroidRuntime(836): Caused by: java.lang.ClassCastException: com.example.android.fragments.MainActivity@40ce2278 must implement OnHeadlineSelectedListener
03-04 08:32:17.248: E/AndroidRuntime(836):  at com.example.android.fragments.MainActivity$HeadlinesFragment.onAttach(MainActivity.java:178)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:825)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:505)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.Activity.performStart(Activity.java:5114)
03-04 08:32:17.248: E/AndroidRuntime(836):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
03-04 08:32:17.248: E/AndroidRuntime(836):  ... 11 more
03-04 08:35:24.997: E/Trace(892): error opening trace file: No such file or directory (2)
03-04 08:35:25.628: D/AndroidRuntime(892): Shutting down VM
03-04 08:35:25.628: W/dalvikvm(892): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-04 08:35:25.638: E/AndroidRuntime(892): FATAL EXCEPTION: main
03-04 08:35:25.638: E/AndroidRuntime(892): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.fragments/com.example.android.fragments.MainActivity}: java.lang.ClassCastException: com.example.android.fragments.MainActivity@40ce3d10 must implement OnHeadlineSelectedListener
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.os.Looper.loop(Looper.java:137)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.ActivityThread.main(ActivityThread.java:5041)
03-04 08:35:25.638: E/AndroidRuntime(892):  at java.lang.reflect.Method.invokeNative(Native Method)
03-04 08:35:25.638: E/AndroidRuntime(892):  at java.lang.reflect.Method.invoke(Method.java:511)
03-04 08:35:25.638: E/AndroidRuntime(892):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-04 08:35:25.638: E/AndroidRuntime(892):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-04 08:35:25.638: E/AndroidRuntime(892):  at dalvik.system.NativeStart.main(Native Method)
03-04 08:35:25.638: E/AndroidRuntime(892): Caused by: java.lang.ClassCastException: com.example.android.fragments.MainActivity@40ce3d10 must implement OnHeadlineSelectedListener
03-04 08:35:25.638: E/AndroidRuntime(892):  at com.example.android.fragments.MainActivity$HeadlinesFragment.onAttach(MainActivity.java:178)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:825)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:505)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.Activity.performStart(Activity.java:5114)
03-04 08:35:25.638: E/AndroidRuntime(892):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
03-04 08:35:25.638: E/AndroidRuntime(892):  ... 11 more

Android Manifest

    <?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.fragments"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.example.android.fragments.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

public class MainActivity extends FragmentActivity {

     public interface OnHeadlineSelectedListener {
         /** Called by HeadlinesFragment when a list item is selected */
         public void onArticleSelected(int position);
     }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create an instance of ExampleFragment
            HeadlinesFragment firstFragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);

        } else {
            // If the frag is not available, we're in the one-pane layout and must swap        frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }

    public class ArticleFragment extends Fragment {
        final static String ARG_POSITION = "position";
        int mCurrentPosition = -1;

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

            // If activity recreated (such as from screen rotate), restore
            // the previous article selection set by onSaveInstanceState().
            // This is primarily necessary when in the two-pane layout.
            if (savedInstanceState != null) {
                mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
            }

            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.article_view, container, false);
        }

        @Override
        public void onStart() {
            super.onStart();

            // During startup, check if there are arguments passed to the fragment.
            // onStart is a good place to do this because the layout has already been
            // applied to the fragment at this point so we can safely call the method
            // below that sets the article text.
            Bundle args = getArguments();
            if (args != null) {
                // Set article based on argument passed in
                updateArticleView(args.getInt(ARG_POSITION));
            } else if (mCurrentPosition != -1) {
                // Set article based on saved instance state defined during onCreateView
                updateArticleView(mCurrentPosition);
            }
        }

        public void updateArticleView(int position) {
            TextView article = (TextView) getActivity().findViewById(R.id.Article);
            article.setText(Articles[position]);
            mCurrentPosition = position;
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);

            // Save the current article selection in case we need to recreate the fragment
            outState.putInt(ARG_POSITION, mCurrentPosition);
        }
    }

    public class HeadlinesFragment extends ListFragment {
        OnHeadlineSelectedListener mCallback;




        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // We need to use a different list item layout for devices older than Honeycomb
            int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                    android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

            // Create an array adapter for the list view, using the Ipsum headlines array
            setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Headlines));
        }

        @Override
        public void onStart() {
            super.onStart();

            // When in two-pane layout, set the listview to highlight the selected list item
            // (We do this during onStart because at the point the listview is available.)
            if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            }
        }

        @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 = (OnHeadlineSelectedListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                        + " must implement OnHeadlineSelectedListener");
            }
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            // Notify the parent activity of selected item
            mCallback.onArticleSelected(position);

            // Set the item as checked to be highlighted when in two-pane layout
            getListView().setItemChecked(position, true);
        }
    }

    ArrayAdapter<String> adapter;




    static String Headlines[] = {
            "3D Studio Max 2014",
            "Adobe Creative Suite 6",
            "Agilent Agent",
            "Android SDK",
            "Audacity",
            "C Map Tools",
            "Cedar and Easy 68k",
            "Context",
            "CryEngine 3",
            "Derive V5.0",
            "Dreamweaver CS6",
            "Eclipse",
            "Face Modeller",
            "Flash CS6",
            "Image J",
            "Linux",
            "Matlab R2012A (Computing Toolbase)",
            "Matlab R2012A (Maths)",
            "Microsoft Project",
            "Microsoft SQL Sever Lite",
            "MinecraftEDU",
            "MiniTab 16",
            "MonoGame",
            "NetBeans 7.3.1",
            "Office 2013",
            "Oracle Client",
            "Photoshop CS6",
            "Premiere CS6",
            "Python 3.3.2",
            "QT 5.1",
            "R-Studio",
            "Rational Architect",
            "Steam",
            "SWI Pro Log",
            "Unreal UDK",
            "Visio 2012",
            "Visual Studio 2012",
            "Win A&D 7 Desktop",
            "Windows Mobile SDK",
            "Weka ML",
            "XNA Game Studio"};

   static  String Articles []= { "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",
            "MEA 27\n MEA 34\n",




    };
}

article_view.xml

<?xml version="1.0" encoding="utf-8"?>


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Article"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:textSize="18sp" />

news_article.xml

<?xml version="1.0" encoding="utf-8"?>


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Was it helpful?

Solution

This line is the problem for you:

mCallback = (OnHeadlineSelectedListener) activity

Your activity does not implement the declared interface.

Change:

public class MainActivity extends FragmentActivity

to

public class MainActivity extends FragmentActivity implements OnHeadlineSelectedListener

and you should be good to go.

You do provide the method implementation, but as long as you do not declare that your activity implements the interface you will not be able to upcast.

You can see this line in your stacktrace that helped us identify the issue:

03-04 08:35:25.638: E/AndroidRuntime(892): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.fragments/com.example.android.fragments.MainActivity}: java.lang.ClassCastException: com.example.android.fragments.MainActivity@40ce3d10 must implement OnHeadlineSelectedListener

Also you would face a problem that a class can not implement an interface declared in its body. Please move the interface above the class declaration. This would compile and run successfully:

interface OnHeadlineSelectedListener {
    /** Called by HeadlinesFragment when a list item is selected */
    public void onArticleSelected(int position);
}
public class MainActivity extends FragmentActivity implements OnHeadlineSelectedListener {

OTHER TIPS

you have not implemnt this..,just implement OnHeadlineSelectedListener

public class MainActivity extends FragmentActivity implements OnHeadlineSelectedListener {

Your Activity must implement the interface

public class MainActivity extends FragmentActivity implements OnHeadlineSelectedListener{ 

You already have

public void onArticleSelected(int position) {

in activity

Its clear and you have a comment also that should help fix the problem

        // **This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.**
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener"); // look at this line
        }

Have the interface in a seperate .java class

 public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top