Android 异步任务不';t首先在片段中膨胀UI,但当活动恢复或重新启动时,UI膨胀
我正在从事一个项目,该项目从url读取RSS提要,并将其显示在片段活动中。我还使用ViewPager在选项卡中导航,并使用FLipViewController在项目中翻转UI 问题是我在HomeFragment(第一个选项卡屏幕)中使用了一个AsyncTask来读取RSS提要并在HomeFragment UI上显示它们。所有RSS源都已读取,但第一次未在我的HomeFragment UI上显示,但当我使用ViewPager从第一个选项卡导航到最后一个选项卡时,当我的HomeFragment再次启动时,UI会显示活动的源 我在日志里放了一些日志,检查了日志。我开始知道我的onCreateView()被执行,然后我的AsyncTask被执行,尽管我在onCreate()方法中编写了AsyncTask,我也尝试在onCreateView()和onActivityCreated()方法中使用AsyncTask,但每次都会发生同样的事情 有人能帮我解释为什么当活动第一次启动时,我的异步任务没有执行,为什么当活动重新启动时,UI膨胀而不是第一次。如果可能的话,我还可以通过其他方式实现我所需要的 随信附上我的代码,如有任何帮助,将不胜感激 我的基本活动如下:-Android 异步任务不';t首先在片段中膨胀UI,但当活动恢复或重新启动时,UI膨胀,android,android-fragments,android-asynctask,android-viewpager,flipview,Android,Android Fragments,Android Asynctask,Android Viewpager,Flipview,我正在从事一个项目,该项目从url读取RSS提要,并将其显示在片段活动中。我还使用ViewPager在选项卡中导航,并使用FLipViewController在项目中翻转UI 问题是我在HomeFragment(第一个选项卡屏幕)中使用了一个AsyncTask来读取RSS提要并在HomeFragment UI上显示它们。所有RSS源都已读取,但第一次未在我的HomeFragment UI上显示,但当我使用ViewPager从第一个选项卡导航到最后一个选项卡时,当我的HomeFragment再次启
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
}
}
<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" />
<?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>
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
我的主片段类如下所示:-
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");
}
}
}
}
我的解析器类如下所示:-
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);
}
}
});
}
}
尝试将代码移动到onStart(),这样,当视图可见时,代码将始终运行 在HomeFragment Fragment类的onCreate()方法中,仍然可以得到相同的结果。当我们第一次通过选项卡导航并返回活动时,UI仍然没有被填充,直到UI被填充。
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