-1

我正在开发一个从 url 读取 RSS 提要并将其显示在片段活动中的项目。我还使用 ViewPager 来浏览选项卡,并使用 FLipViewController 来翻转项目中的 UI。

问题是我在 HomeFragment(第一个选项卡屏幕)中使用了 AsyncTask 来读取 RSS 源并将它们显示在我的 HomeFragment UI 上。所有的 RSS 提要都已被读取,但这些提要第一次没有显示在 My HomeFragment UI 上,但是当我使用 ViewPager 从第一个选项卡导航到最后一个选项卡时,当我的 HomeFragement 再次启动时,UI 会显示活动上的提要。

我已经检查了 logcat 并在其中输入了一些日志。我开始知道我的 onCreateView() 被执行,然后我的 AsyncTask 被执行,即使我已经在我的 onCreate() 方法中编写了 AsyncTask,我也尝试在我的 onCreateView() 和 onActivityCreated() 方法中使用 AsyncTask 但是总是发生同样的事情。

谁能帮助我为什么当活动第一次启动时我的 AsyncTask 没有执行,为什么当活动重新启动时 UI 被夸大而不是首先。如果可能的话,我也可以通过其他方式实现我所需要的。

我在下面附上了我的代码,任何帮助将不胜感激。

我的基本活动如下:-

public class Base extends FragmentActivity implements ActionBar.TabListener {

    private ViewPager viewPager;
    private TabPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Post", "Category", "Gallery" };

    String TabFragmentHome;

    public void setTabFragmentHome(String t){
        TabFragmentHome = t;
    }

    public String getTabFragmentHome(){
        return TabFragmentHome;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_activity);

        // Initializing...
        viewPager=(ViewPager)findViewById(R.id.pager);
        actionBar=getActionBar();
        mAdapter=new TabPagerAdapter(getFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        for(String tab_name:tabs){
            actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
        }

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(arg0);

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.base, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
         // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }   
   }

我的家庭片段课程如下:-

public class HomeFragment extends Fragment {

    private static String sAllPostFeedURL = "SOME_FEED_URL";
    List<AllStoriesModel> lASM;
    List<AllStoriesModel>list = new ArrayList<AllStoriesModel>();
    FlipViewController flipview;
    NoteViewBaseAdapter NVBAdapter;

        RelativeLayout rLay;

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.d("HomeFragment","onCreateView");
        View rootView=inflater.inflate(R.layout.home_fragment, container,false);
        rLay=(RelativeLayout)rootView.findViewById(R.id.MainLayout);

        return flipview;
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.d("HomeFragment","OnResume");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Log.d("HomeFragment","OnCreate");
        new LoadStoriesOnline().execute();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        Log.d("HomeFragment","OnActivityCreated");
    }

    public class NoteViewBaseAdapter extends BaseAdapter{

        private final Context mContext = null;
        LayoutInflater inflate;
        List<AllStoriesModel> lstory;

        public NoteViewBaseAdapter(Context homeFragment,
                List<AllStoriesModel> objASM) {
            // TODO Auto-generated constructor stub
            Log.d("HomeFragment","NoteViewBaseAdapter Started");
            inflate=LayoutInflater.from(homeFragment);
            lstory=objASM;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return lstory.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            Log.d("HomeFragment","NoteViewAdapter.getView() Method");
            View layout=convertView;

            if(layout==null){
                layout=inflate.inflate(R.layout.home_fragment, null);
            }
            //Get's value from our ArrayList by the position
            final AllStoriesModel objASM = lstory.get(position);
            TextView tHeadline = (TextView)layout.findViewById(R.id.tHeadline);
            ImageView iStoryImage = (ImageView)layout.findViewById(R.id.iStoryImage);
            TextView tAuthor = (TextView)layout.findViewById(R.id.tAuthor);
            TextView tDate = (TextView)layout.findViewById(R.id.tDate);
            TextView tStoryDesc = (TextView)layout.findViewById(R.id.tStoryDetails);
            RelativeLayout lMore=(RelativeLayout)layout.findViewById(R.id.MainLayout);
            try{
                tHeadline.setText(objASM.getStitle());
                String sStoryDesc="<html><head>" + 
                        "<style type=\"text/css\">" +
                        "</style></head>" +
                "<body>" +
                    "<section id=\"content\">" +
                        objASM.getSdesc() + 
                    "</section>" + "<br><br>"+
                "</body></html>";
                tStoryDesc.setText(Html.fromHtml(sStoryDesc));
                tAuthor.setText(objASM.getSauthor());
                tDate.setText(objASM.getSdate());

                Picasso.with(getActivity())
                .load(objASM.getSthumburl().replace("-150x150.", "."))
                .placeholder(R.drawable.image) // optional
                .error(R.drawable.ic_launcher)         // optional
                .into(iStoryImage);

            }catch(Exception e){
                Log.d("Home Fragment : ", "Error in Feed");
                e.printStackTrace();
            }

            lMore.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    someOperations();
                }
            });

            return layout;
        }

    }

    public class LoadStoriesOnline extends AsyncTask<String, String, String>
    {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            Log.d("HomeFragment","doInBackground Method");
            if(StoryService.checkInternetConnection(getActivity()))
            {
                Log.d("Home Fragment", "Loading stories started");
                HttpGet request = new HttpGet(sAllPostFeedURL);
                request.addHeader("accepts", "application/rss+xml");
                HttpClient client = new DefaultHttpClient();

                HttpResponse response = null;
                try {
                    response = client.execute(request);
                } catch (IOException e) {

                    e.printStackTrace();
                }

                RootElement root = new RootElement("rss");

                lASM = new ArrayList<AllStoriesModel>();
                AllStoriesParser objASP = new AllStoriesParser();

                lASM = AllStoriesParser.appendArrayListener(root.getChild("channel"), 0);

                try {
                    Xml.parse(response.getEntity().getContent(), Xml.Encoding.UTF_8, root.getContentHandler());
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Log.d("HomeFragment","OnPostExecute");
            if(lASM!=null){
                NVBAdapter=new NoteViewBaseAdapter(getActivity(), lASM);
                NVBAdapter.notifyDataSetChanged();
            flipview = new FlipViewController(getActivity(), FlipViewController.VERTICAL);
            flipview.setAdapter(NVBAdapter);

            }
            else{
                Log.d("HomeFragment : ","lASM is null");
            }

        }

    }
}

我的 TabPager 适配器如下:-

public class TabPagerAdapter extends FragmentPagerAdapter{

    public TabPagerAdapter(FragmentManager fm) {
        super(fm);
        // TODO Auto-generated constructor stub
    }

    public Fragment getItem(int index) {
        // TODO Auto-generated method stub
        switch (index) {
        case 0:
            // Top Rated fragment activity
            return new HomeFragment();
        case 1:
            // Games fragment activity
            return new CategoriesFragment();
        case 2:
            // Movies fragment activity
            return new GalleryFragment();
        }

        return null;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 3;
    }

}

我的解析器类如下:-

public class AllStoriesParser {
    private static AllStoriesModel objASM;
    private String text;

    public AllStoriesParser() {
        // TODO Auto-generated constructor stub
        //lstory = new ArrayList<AllStoriesModel>();
    }

    public static List<AllStoriesModel> appendArrayListener(final Element parent, int depth) {
        final List<AllStoriesModel> lstory = new ArrayList<AllStoriesModel>();
        objASM = new AllStoriesModel();

        Element storyElement = parent.getChild("item");

        storyElement.setEndElementListener(new EndElementListener() {
            @Override
            public void end() {
                lstory.add(objASM.copy());

                Log.d("AllStoriesParser StoryNo:", lstory.size()+"");
                Log.d("AllStoriesParser list:",lstory.get(lstory.size()-1).getStitle()+"");

                }
        });

        appendCommonListeners(storyElement, objASM, depth);

        return lstory;
    }

    private static void appendCommonListeners(Element storyElement,
            final AllStoriesModel objASM, int depth) {
        // TODO Auto-generated method stub
        Log.d("AllstoriesParser","AppendCommonListener");
        storyElement.getChild("guid").setEndTextElementListener(new EndTextElementListener() {
            @Override
            public void end(String body) {
                if (body != null && body != "") {
                    objASM.setSguid(body);
                }
            }
        });

        storyElement.getChild("title").setEndTextElementListener(new EndTextElementListener() {
            @Override
            public void end(String body) {
                if (body != null && body != "") {
                    objASM.setStitle(body);

                }
            }
        });

        storyElement.getChild("pubDate").setEndTextElementListener(new EndTextElementListener() {
            @Override
            public void end(String body) {
                if (body != null && body != "") {
                    objASM.setSdate(body);
                    }
            }
        });

        storyElement.getChild("SOME_VALUE", "creator").setEndTextElementListener(new EndTextElementListener() {
            @Override
            public void end(String body) {
                if (body != null && body != "") {
                    objASM.setSauthor("By: "+body);
                    Log.d("Author Name: ", body);
                }
            }
        });

        storyElement.getChild("description").setEndTextElementListener(new EndTextElementListener() {
            @Override
            public void end(String body) {
                if (body != null && body != "") {

                    objASM.setSdesc(body);
                }
            }
        });

        storyElement.getChild("SOME_VALUE", "encoded").setEndTextElementListener(new EndTextElementListener() {
            @Override
            public void end(String body) {
                if (body != null && body != "") {
                    objASM.setScontent(body);
                }
            }
        });

        storyElement.getChild("SOME_VALUE", "thumbnail").setEndTextElementListener(new EndTextElementListener() {
            @Override
            public void end(String body) {
                if (body != null && body != "") {
                    objASM.setSthumburl(body);
                }
            }
        });

    }

}

我的 base_activity.xml 如下:-

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.advance.Base" />

我的 home_fragment.xml 文件如下:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/MainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:clickable="true"
    android:focusable="false" 
    android:background="#ffffff">
    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="130dp"
        tools:context="in.advance.Base" />
    <TextView 
        android:id="@+id/tHeadline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold"
        android:layout_marginLeft="5sp"
        android:layout_marginRight="5sp"
        android:gravity="left"
        android:typeface="serif"
        android:text="ajdvjka ajk dvajdv ajkl vdjkl "/>

        <LinearLayout 
            android:id="@+id/lLayDateAuthor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_below="@+id/tHeadline"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp">

            <TextView
                android:id="@+id/tAuthor"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:textColor="#0000ff"
                android:textStyle="italic"
                android:layout_weight="1"
                android:textSize="12sp"
                android:typeface="serif"
                android:text="By: FirstName LastName" />

            <TextView
                android:id="@+id/tDate"
                android:textColor="#0000ff"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:layout_weight="1"
                android:textStyle="italic"
                android:textSize="10sp"
                android:typeface="serif"
                android:text="30/Feb/2020 25:61 Xx" />
        </LinearLayout>

        <ImageView
            android:id="@+id/iStoryImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/tStoryDetails"
            android:layout_below="@+id/lLayDateAuthor"
            android:layout_gravity="center_horizontal"
            android:scaleType="fitCenter"
            android:src="@drawable/indiacom" />

        <TextView
            android:id="@+id/tStoryDetails"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="5"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="5dp"
            android:gravity="left"
            android:layout_marginLeft="5sp"
            android:layout_marginRight="5sp"
            android:textStyle="normal"
            android:textSize="15sp"
            android:typeface="serif"
            android:text="TextView" /> 

</RelativeLayout>

我的 Logcat 输出如下:-

01-13 16:12:29.155: D/HomeFragment(20997): OnCreate
01-13 16:12:29.155: D/HomeFragment(20997): onCreateView
01-13 16:12:29.160: D/HomeFragment(20997): doInBackground Method
01-13 16:12:29.220: D/Home Fragment(20997): Loading stories started
01-13 16:12:29.325: D/HomeFragment(20997): OnActivityCreated
01-13 16:12:29.325: D/HomeFragment(20997): OnResume
01-13 16:12:31.225: D/AllstoriesParser(20997): AppendCommonListener
01-13 16:12:31.250: D/Author Name:(20997): AFP
01-13 16:12:31.310: D/AllStoriesParser StoryNo:(20997): 1
01-13 16:12:31.310: D/AllStoriesParser list:(20997): Maria Sharapova to spearhead Russia against Poland in Fed Cup
01-13 16:12:31.315: D/Author Name:(20997): Indo-Asian News Service
01-13 16:12:31.400: D/AllStoriesParser Title:(20997): 2
01-13 16:12:31.400: D/AllStoriesParser list:(20997): Goa Minister takes a U-turn after facing flak for controversial remarks over LGBT community

                           || to ||

01-13 16:12:38.910: D/Author Name:(20997): Krishnan Iyer
01-13 16:12:38.915: D/AllStoriesParser Title:(20997): 50
01-13 16:12:38.915: D/AllStoriesParser list:(20997): Cristiano Ronaldo wins FIFA Ballon d’Or 2014: The Award Ceremony – In Pics
01-13 16:12:38.920: D/HomeFragment(20997): OnPostExecute
01-13 16:12:38.950: D/HomeFragment(20997): NoteViewBaseAdapter Started
01-13 16:12:38.965: D/HomeFragment(20997): NoteViewAdapter.getView() Method
01-13 16:12:39.035: W/Settings(20997): Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
01-13 16:12:39.040: D/HomeFragment(20997): NoteViewAdapter.getView() Method
4

1 回答 1

0

尝试将代码移动到 onStart(),这样代码总是在视图可见时运行。

于 2015-01-13T10:56:14.857 回答