java.lang.classcastexception片段无法强制转换为android.app.activity

时间:2014-04-26 08:54:50

标签: android android-fragments android-activity

我在运行时遇到错误: java.lang.classcastexception com.android.homework.AllAppsFragment无法强制转换为android.app.activity。这段代码有什么问题?

  

04-26 08:42:02.065:E / AndroidRuntime(1755):   java.lang.RuntimeException:无法实例化活动   ComponentInfo {com.android.homework / com.andorid.homework.AllAppsFragment}:   java.lang.ClassCastException:com.andorid.homework.AllAppsFragment   无法转换为android.app.Activity

public class AllAppsFragment extends ListFragment {
    private PackageManager packageManager = null;
    private List<ApplicationInfo> applist = null;
    private ApplicationAdapter listadaptor = null;
    private HashMap<ApplicationInfo, Float> appRating = null;
    private SharedPreferences sh = null;
    private SharedPreferences.Editor preferencesEditor = null;
    public static final String MY_PREFERENCES = "myPreferences";

    private OnItemSelectedListener listener;

    public interface OnItemSelectedListener {
        public void onRssItemSelected(String link);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet MyListFragment.OnItemSelectedListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        listener = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_main);

        packageManager = getActivity().getBaseContext().getPackageManager();
        new LoadApplications().execute();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_main, null);
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        inflater.inflate(R.menu.menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
        // return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        boolean result = true;

        switch (item.getItemId()) {
        case R.id.menu_about: {
            displayAboutDialog();

            break;
        }
        default: {
            result = super.onOptionsItemSelected(item);

            break;
        }
        }

        return result;
    }

    private void displayAboutDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity().getBaseContext());
        builder.setTitle(getString(R.string.about_title));

        builder.setItems(new CharSequence[] { getString(R.string.sort_lex),
                getString(R.string.sortuj_lex_desc),
                getString(R.string.sort_ranked),
                getString(R.string.sort_ranked_desc) },
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // The 'which' argument contains the index position
                        // of the selected item
                        sh = getActivity().getBaseContext()
                                .getSharedPreferences(MY_PREFERENCES,
                                        Context.MODE_PRIVATE);
                        preferencesEditor = sh.edit();
                        switch (which) {
                        case 0:
                            listadaptor.sortLex();
                            preferencesEditor.putInt("sort_type", 1);
                            preferencesEditor.commit();
                            dialog.cancel();
                            break;
                        case 1:
                            listadaptor.sortLexDesc();
                            preferencesEditor.putInt("sort_type", 2);
                            preferencesEditor.commit();
                            dialog.cancel();
                            break;
                        case 2:
                            listadaptor.sortRating();
                            preferencesEditor.putInt("sort_type", 3);
                            preferencesEditor.commit();
                            dialog.cancel();
                            break;
                        case 3:
                            listadaptor.sortRaingDesc();
                            preferencesEditor.putInt("sort_type", 4);
                            preferencesEditor.commit();
                            dialog.cancel();
                            break;
                        }
                    }
                });

        builder.create().show();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        ApplicationInfo app = applist.get(position);
        try {
            Intent intent = packageManager
                    .getLaunchIntentForPackage(app.packageName);
            if (null != intent) {
                startActivity(intent);
            }
        } catch (ActivityNotFoundException e) {
            Toast.makeText(getActivity().getBaseContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getActivity().getBaseContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }

    private List<ApplicationInfo> checkForLaunchIntent(
            List<ApplicationInfo> list) {
        ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
        for (ApplicationInfo info : list) {
            try {
                if (null != packageManager
                        .getLaunchIntentForPackage(info.packageName)) {
                    applist.add(info);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return applist;
    }

    private class LoadApplications extends AsyncTask<Void, Void, Void> {
        private ProgressDialog progress = null;

        @Override
        protected Void doInBackground(Void... params) {
            applist = checkForLaunchIntent(packageManager
                    .getInstalledApplications(PackageManager.GET_META_DATA));
            listadaptor = new ApplicationAdapter(
                    getActivity().getBaseContext(), R.layout.snippet_list_row,
                    applist);

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Void result) {

            sh = getActivity().getBaseContext().getSharedPreferences(
                    MY_PREFERENCES, Context.MODE_PRIVATE);
            int sortOrder = sh.getInt("sort_type", 0);
            switch (sortOrder) {
            case 1:
                listadaptor.sortLex();
                break;
            case 2:
                listadaptor.sortLexDesc();
                break;

            case 3:
                listadaptor.sortRating();
                break;

            case 4:
                listadaptor.sortRaingDesc();
                break;

            default:
            }

            setListAdapter(listadaptor);
            progress.dismiss();
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            progress = ProgressDialog.show(getActivity().getBaseContext(),
                    null, "Ładujemy!!");
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }
}

HostActivity

public class HostActivity extends Activity implements OnItemSelectedListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_fragment);
    }

    @Override
    public void onRssItemSelected(String link) {
        // TODO Auto-generated method stub

    }
}

main_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <fragment 
        android:id="@+id/country_fragment"
        android:name="com.android.homework.AllAppsFragment"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

启动应用程序时会抛出异常。它试图启动主要活动,但由于某种原因,它试图启动片段。它会将其转换为Activity,但Fragment不会延伸Activity。您所做的是将片段添加为AndroidManifest.xml中的活动。将其更改为HostActivity