“尚未创建内容视图"在 Android 片段上

quot;Content view not yet Createdquot; on Android Fragments(“尚未创建内容视图在 Android 片段上)
本文介绍了“尚未创建内容视图"在 Android 片段上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 viewpager 设置的 Android 片段.基本上有 5 个标签可以滑动浏览.

I am using Android Fragments with a viewpager setup. Basically there are 5 tabs you can swipe through.

5 个中的 4 个包含由 MySQL 表填充的 ListFragments;这是在 AsyncTask 内完成的.当我快速滑动时,有时会出现此错误:

4 of the 5 contain ListFragments that are populated by MySQL tables; this is done inside of an AsyncTask. When I swipe very fast I sometimes get this error:

09-01 07:54:01.243: E/AndroidRuntime(19706): FATAL EXCEPTION: main
09-01 07:54:01.243: E/AndroidRuntime(19706): java.lang.IllegalStateException: Content view not yet created
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at com.---.---.MasterCat$TopFrag$TopTask.onPostExecute(MasterCat.java:570)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at com.---.---.MasterCat$TopFrag$TopTask.onPostExecute(MasterCat.java:1)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.os.AsyncTask.finish(AsyncTask.java:631)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.os.Looper.loop(Looper.java:137)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at android.app.ActivityThread.main(ActivityThread.java:4928)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at java.lang.reflect.Method.invokeNative(Native Method)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at java.lang.reflect.Method.invoke(Method.java:511)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
09-01 07:54:01.243: E/AndroidRuntime(19706):    at dalvik.system.NativeStart.main(Native Method)

我故意不使用 ProgressDialog,因为它会使刷卡有点卡顿.

I have intentionly not used a ProgressDialog because it makes swiping stutter quite a bit.

所以我有两个选择,无论哪种方式我都需要帮助:

So I have two options and I need help either way:

  1. 如何防止出现此错误并在滑动时保持列表刷新.

  1. How to prevent this error and keep the list refreshing even while swiping.

或者一旦加载了 5 个片段,关闭刷卡时刷新".换句话说,除非您退出活动并返回,否则列表将保持不变.

OR once the 5 fragments are loaded, turn off 'refresh while swiping'. In other words, the lists will stay the same unless you back out of the Activity and come back.

我更喜欢选项 #1.请让我知道您需要查看哪些代码:

I'd prefer option #1. Please let me know what code you need to see:

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


        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);

                    }
                });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }




    }

    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {

    }

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

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

    }

    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment f = null;
            switch (position) {
            case 0: {
                f = new MasterFrag();
                Bundle args = new Bundle();

                f.setArguments(args);
                break;
            }
            case 1: {
                f = new FeaturedFrag();
                Bundle args = new Bundle();

                f.setArguments(args);
                break;
            }
            case 4: {
                f = new TopFrag();
                Bundle args = new Bundle();

                f.setArguments(args);
                break;
            }
            case 3: {
                f = new NewFrag();
                Bundle args = new Bundle();

                f.setArguments(args);
                break;
            }
            case 2: {
                f = new TrendFrag();
                Bundle args = new Bundle();

                f.setArguments(args);
                break;
            }
            default:
                throw new IllegalArgumentException("not this many fragments: "
                        + position);
            }

            return f;

        }

此外,LogCat 中引用的第 570 行与 AsyncTask 内部的 getListView() 相关,该 AsyncTask 位于上面未显示的 ListFragment 内部.

Also, line 570 referenced in the LogCat pertains to a getListView() inside of an AsyncTask which is inside of a ListFragment not shown above.

编辑:

添加 5 个片段之一 - LogCat 中引用的片段 - TopFrag"

Adding one of the 5 Fragments - the one referenced in LogCat - "TopFrag"

class TopTask extends AsyncTask<String, String, Void> {
        InputStream is = null;
        String result = "";

        @Override
        protected Void doInBackground(String... params) {
            String url_select = "http://www.---.com/---/---.php";

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_select);
            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("Top", "Top"));

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(param));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // read content
                is = httpEntity.getContent();

            } catch (Exception e) {

                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "
");
                }
                is.close();
                result = sb.toString();

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            return null;

        }

        protected void onPostExecute(Void v) {

            String item, cat;
            try {
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data = null;
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    item = json_data.getString("item");
                    cat = json_data.getString("category");


                    items.add(item);
                    cats.add(cat);



                }
            } catch (JSONException e1) {
                Toast.makeText(getActivity(), "No Top Items Found",
                        Toast.LENGTH_LONG).show();
            } catch (ParseException e1) {
                e1.printStackTrace();
            }

            ListView listView;
            listView = getListView();
            listView.setTextFilterEnabled(true);

            listView.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long id) {
           // edit

                }
            });

            MasterCatObject[] mco = new MasterCatObject[items.size()];
            int index = 0;

            for (@SuppressWarnings("unused")
            String i : items) {
                mco[index] = new MasterCatObject(items.get(index),
                        cats.get(index));
                index++;
            }

            adapter = new AllTimeAdapter(getActivity(), mco);
            setListAdapter(adapter);

        }
    }

}

推荐答案

at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
at com.---.---.MasterCat$TopFrag$TopTask.onPostExecute(MasterCat.java:570)

您的 TopTask.onPostExecute() 不得在片段尚未(在 onCreateView 之前)/不再(在 onDestroyView) 显示.根本没有你能得到的ListView.

your TopTask.onPostExecute() must not touch the UI while the fragment is not yet (before onCreateView) / no longer (after onDestroyView) shown. There is simply no ListView you can get.

您可以在这里做的是更新 ListView 使用的数据结构,以便下次绘制列表时包含新数据.

What you could do here is to update the datastructure that is used by the ListView so the next time the list is drawn the new data is included.

这篇关于“尚未创建内容视图"在 Android 片段上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)