片段错误 - 无法将ListFragment强制转换为android.app.Activity

时间:2012-02-03 21:38:17

标签: android android-fragments android-activity

我有一个片段视图需要替换另一个片段。

当选择ListFragment项时,通过将Extras传递给活动中的新(或第二)ListFragment,将DetailsFragment替换为另一个ListFragment。我的问题是我得到了“没有找到处理意图的活动{(有额外的)}”。 ListFragment在活动首次启动时工作正常,但是当我将Details活动与另一个ListFragment更新(替换)时,我收到错误。

这是我的第一个Fragment活动,我想我不知道如何在片段之间正确传递Extras。我肯定没有正确使用fragment-manager / transaction类(?)。如果有人能够纠正我的实施,我将非常感激。

更新:我添加了“i.setClass(getActivity(),ListFragment.class);”对于ListFragment类中的意图,现在Log错误已更改为以下内容:

UPDTATE 2:我纠正了自己对Arguments的意图,因为Devunwired已经消瘦了,现在效果很好。 Thnx Devunwired。我现在唯一的问题是,当按下后退键时,后台堆栈不起作用。更正后的课程如下:

LogCat (更新)

     FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.andaero.test/com.andaero.test.fragments.ListFragment}: java.lang.ClassCastException: com.andaero.test.fragments.ListFragment cannot be cast to android.app.Activity
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1739)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
    at android.app.ActivityThread.access$500(ActivityThread.java:122)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:132)
    at android.app.ActivityThread.main(ActivityThread.java:4123)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.ClassCastException: com.andaero.test.fragments.ListFragment cannot be cast to android.app.Activity

ListFragment类:

public class ListFragment extends android.app.ListFragment {

    boolean mDualPane;
    int mCurCheckPosition = 0;
    protected TextView activityTitle;

    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;

    String extStorageDirectory = Environment.getExternalStorageDirectory()
            .toString();
    File dbfile = new File(extStorageDirectory + "/Andaero/dB/Andaero.db");
    SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);

    private static final String QUERY_KEY = "QUERY_KEY";
    private static final String QUERY_ORDER = "QUERY_ORDER";

    private View layout;

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

    }

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

        Bundle extras = getActivity().getIntent().getExtras();
        Bundle arg = this.getArguments();//**ADDED TO GET THE ARGS

        /**
         * Get the query string from last activity and pass it to this
         * activity-----------------------------------------------------
         */
        String q = null;
        if (extras != null) {
            q = extras.getString(QUERY_KEY);
        }

        if (arg != null) {
        q = (String) (getArguments() != null ? getArguments().getString(
                "QUERY_KEY") : 1);
    }

        loadQuery(q);
    }

    public void loadQuery(String q) {

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {

            String qO = getActivity().getIntent().getStringExtra("QUERY_ORDER");
            Cursor c = db.rawQuery(q + " ORDER BY `_id` " + qO, null);
            setListAdapter(new QueryAdapter(getActivity(), c));
            db.close();

        } else {
            Alerts.sdCardMissing(getActivity());
        }
    }

    public class QueryAdapter extends CursorAdapter {

        public QueryAdapter(Context context, Cursor c) {
            super(context, c);
            LayoutInflater.from(context);
        }

        @Override
        public void bindView(View v, Context context, final Cursor c) {

            int tvLabel = c.getColumnIndexOrThrow("label");
            String label = c.getString(tvLabel);
            final TextView labelTxt = (TextView) v.findViewById(R.id.label);

            if (labelTxt != null) {
                labelTxt.setText("(" + label + ")");
            }

            int tvTitle = c.getColumnIndexOrThrow("title");
            final String title = c.getString(tvTitle);
            TextView titleTxt = (TextView) v.findViewById(R.id.listTitle);

            if (titleTxt != null) {
                titleTxt.setText(title);
            }

            int tvDescription = c.getColumnIndexOrThrow("description");
            String description = c.getString(tvDescription);
            TextView descriptionTxt = (TextView) v.findViewById(R.id.caption);

            if (descriptionTxt != null) {
                descriptionTxt.setText(description);
            }

            int tvDate = c.getColumnIndexOrThrow("date");
            String date = c.getString(tvDate);
            TextView dateTxt = (TextView) v.findViewById(R.id.dateAdded);

            if (dateTxt != null) {
                dateTxt.setText(date);
            }

            int tvGoto = c.getColumnIndexOrThrow("gotoURL");
            final String gotoURL = c.getString(tvGoto);
            TextView gotoTxt = (TextView) v.findViewById(R.id.dummy);

            if (gotoTxt != null) {
                gotoTxt.setText(gotoURL);
            }

            gotoTxt.setVisibility(View.GONE);
            v.setTag(gotoURL);

            final ListView lv = getListView();
            lv.setEnabled(true);
            lv.setClickable(true);

            lv.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View v, int arg2,
                        long arg3) {

                    // Create new fragment and transaction
                    Fragment newFragment = new ListFragment();
                    FragmentTransaction transaction = getFragmentManager()
                            .beginTransaction();

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

                    String url = "";
                    url = (String) v.getTag();

                    int nI = c.getColumnIndexOrThrow("intent");
                    String intent = c.getString(nI);
                    Class<?> myIntent = null;
                    try {
                        myIntent = Class.forName("com.andaero.test.fragments"
                                + intent);
                    } catch (ClassNotFoundException e) {
                        Log.e("ERROR", "Class Not Found for new intent!");
                        e.printStackTrace();
                    }

                    int tvTitle = c.getColumnIndexOrThrow("title");
                    String title = c.getString(tvTitle);

                    int tvLabel = c.getColumnIndexOrThrow("label");
                    String label = c.getString(tvLabel);

                    String queryKey = "SELECT * FROM " + label;
                    c.close();
                    db.close();

                    Bundle args = new Bundle();//**REPLACED THE INTENTS
                   args.putString("QUERY_KEY", queryKey);
                   args.putString("KEY_URL", url);
                   args.putString("KEY_SUBTITLE", title);
                   args.putString("KEY_LABEL", label);
                   args.putString("KEY_INTENT", intent);
                   args.putString("QUERY_ORDER", "ASC");

                   newFragment.setArguments(args);

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

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            final View v = LayoutInflater.from(context).inflate(
                    R.layout.list_item, parent, false);
            return v;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

为什么不创建一个在创建片段时传递值的构造函数?看来这就是你要做的事情

答案 1 :(得分:0)

您使用FragmentTransaction将一个Fragment替换为另一个Fragment,但Intent未使用Activity从一个startActivity()传递数据,您走在正确的轨道上实例到另一个像Intent那样。事实上,使用Fragment调用Fragment来指示ListFragment会导致您不想要的各种烟花(如您所见)。

将数据传递给构造函数中的新Fragment是完全可以的,因此您可以为Bundle创建一个构造函数,该构造函数接受您要转发的任何数据参数。另一个选择是将所有“额外内容”设置为新Fragment.setArguments()上的参数,方法是将它们放在Fragment并使用getArguments()。只要您想要访问附加到Bundle的参数,就可以致电Intent以取回相同的onItemClick()。所以基本上,在Bundle args = new Bundle(); args.putString("QUERY_KEY", queryKey); //...add all the extras to the bundle newFragment.setArguments(args); transaction.commit(); 方法中替换所有与Fragment有关的代码,而不是:

ListFragment

此外,偏离主题,但您可能希望将{{1}}重命名为其他内容,这样您就不必依赖完全限定的程序包名称来区分{{1}}和代码中的平台版本。

HTH