К несчастью приложение прекратило затмение

-2 user3092467 [2014-03-04 11:59:00]

Вчера я построил свое приложение, и он работал нормально, а затем я попробовал его позже, и он просто придумал сообщение об ошибке

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.MainActivi[email protected] 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: [email protected] 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: [email protected] 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: [email protected] 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 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" />

java android eclipse android-emulator


3 ответа


4 Решение Boris Strandjev [2014-03-04 12:03:00]

Эта строка является для вас проблемой:

mCallback = (OnHeadlineSelectedListener) activity

Ваша активность не реализует объявленный интерфейс.

Изменить:

public class MainActivity extends FragmentActivity

в

public class MainActivity extends FragmentActivity implements OnHeadlineSelectedListener

и вам должно быть хорошо идти.

Вы предоставляете реализацию метода, но пока вы не заявляете, что ваша деятельность реализует интерфейс, вы не сможете ускорить процесс.

Вы можете увидеть эту строку в вашей stacktrace, которая помогла нам определить проблему:

03-04 08: 35: 25.638: E/AndroidRuntime (892): java.lang.RuntimeException: не удалось запустить Activity ComponentInfo {com.example.android.fragments/com.example.android.fragments.MainActivity}: java.lang.ClassCastException: [email protected] должен реализовать OnHeadlineSelectedListener

Также вы столкнулись бы с проблемой, что класс не может реализовать интерфейс, объявленный в его теле. Переместите интерфейс над объявлением класса. Это будет скомпилировано и успешно запущено:

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

3 rajshree [2014-03-04 12:04:00]

вы не реализуете это.., просто реализуйте OnHeadlineSelectedListener

public class MainActivity extends FragmentActivity implements OnHeadlineSelectedListener {

2 Raghunandan [2014-03-04 12:03:00]

Ваша деятельность должна реализовывать интерфейс

public class MainActivity extends FragmentActivity implements OnHeadlineSelectedListener{ 

У тебя уже есть

public void onArticleSelected(int position) {

в деятельности

Это ясно, и у вас есть комментарий, который должен помочь исправить проблему

        // **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
        }

Использовать интерфейс в отдельном классе.java

 public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}