【问题标题】:Fragment Error - ListFragment cannot be cast to android.app.Activity片段错误 - ListFragment 无法转换为 android.app.Activity
【发布时间】:2012-02-09 12:02:01
【问题描述】:

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

当 ListFragment 项目被选中时,DetailsFragment 将被另一个 ListFragment 替换,方法是将 Extras 传递给活动中的新(或第二个)ListFragment。我的问题是我收到“未找到处理 Intent {(has extras)} 的活动”。 ListFragment 在活动第一次启动时工作正常,但是当我用另一个 ListFragment 更新(替换)Details 活动时,我得到了错误。

这是我的第一个 Fragment 活动,我想我不知道如何在 Fragment 之间正确传递 Extras。我肯定没有正确使用片段管理器/事务类(?)。如果有人能纠正我的实现,我将不胜感激。

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

更新 2:我按照 Devunwired 的建议更正了 Arguments 的意图,它现在运行良好。 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;
        }
    }
}

【问题讨论】:

    标签: android android-fragments android-activity


    【解决方案1】:

    您使用FragmentTransaction 将一个Fragment 替换为另一个,但Fragment 不使用Intent 将数据从一个实例传递到另一个实例,就像Activity 一样.事实上,使用指向FragmentIntent 调用startActivity() 会导致各种你不想要的烟花(就像你已经看到的那样)。

    在其构造函数中将数据传递给新的Fragment 是完全可以的,因此您可以为您的ListFragment 创建一个构造函数,该构造函数接受您要转发的任何数据参数。另一种选择是将所有“附加”设置为新Fragment 的参数,方法是将它们放入Bundle 并使用Fragment.setArguments()。任何时候你想访问你附加到Fragment 的参数,你可以调用getArguments() 来取回相同的Bundle。所以基本上,在你的 onItemClick() 方法中替换所有与 Intent 相关的代码,而是:

    Bundle args = new Bundle();
    args.putString("QUERY_KEY", queryKey);
    //...add all the extras to the bundle
    
    newFragment.setArguments(args);
    
    transaction.commit();
    

    另外,题外话,但您可能希望将您的 Fragment 重命名为其他名称,这样您就不必依赖完全限定的包名称来区分您的 ListFragment 和平台版本在你的代码中。

    HTH

    【讨论】:

    • Thnx 对此有帮助。我现在没有收到错误并且活动加载,但它所做的只是重新加载当前存在的数据:它不会像在没有片段的情况下设置类时那样将新数据加载到列表中。任何更多的帮助/指针。谢谢
    • 再次感谢您的帮助。您能否看看我的更改,看看是否有更好的方法来实现我的 Args,您是否明白为什么我的后退堆栈不能与后退键一起使用??
    • 我没有看到任何关于为什么后退操作不起作用的明显信息。事务被添加到后退堆栈中,因此点击后退按钮应将最后一个事务弹出到其先前状态。您是否在 Activity 中覆盖了 onBackPressed() 而没有调用 super 或其他会影响标准返回行为的东西?
    【解决方案2】:

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

    【讨论】:

    • 因为在片段中使用构造函数不好。你总是需要默认的构造函数(空),否则它会在恢复时中断......
    猜你喜欢
    • 2020-08-11
    • 2014-01-01
    • 2019-01-09
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多