-1

URL から RSS フィードを読み取り、フラグメント アクティビティに表示するプロジェクトに取り組んでいます。また、タブをナビゲートするために ViewPager を使用し、プロジェクトで UI を反転するために FLipViewController を使用しました。

問題は、HomeFragment (最初のタブ画面) で AsyncTask を使用して RSS フィードを読み取り、HomeFragment UI に表示していたことです。すべての RSS フィードが読み取られましたが、これらは初めて My HomeFragment UI に表示されませんが、ViewPager を使用して最初のタブから最後に移動し、My HomeFragment が再び開始されると、UI はアクティビティのフィードを表示します。

ログを入れてlogcatをチェックしました。onCreate() メソッドで AsyncTask を記述したにもかかわらず、 My onCreateView() が実行され、次に My 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 に答える