Android三个asynctasks一起运行

时间:2014-02-18 14:57:04

标签: android json android-asynctask android-viewpager

我工作Tabhost(viepager)我有三个片段和每个片段我解析json我可以在listview中显示每个片段的json项目(它工作完美)但我有一个问题。我使用AsyncTask来解析json并显示listview,但所有三个Asynctask一起运行 这是我的代码

public class MainActivity extends FragmentActivity implements
    TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {

private TabHost mTabHost;
private ViewPager mViewPager;
private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, MainActivity.TabInfo>();
private PagerAdapter mPagerAdapter;
private HorizontalScrollView horizontalScrollView;
private ImageButton menubutton;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    menubutton = (ImageButton) findViewById(R.id.menubutton);
    menubutton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Toast.makeText(getApplicationContext(), "Helo",
                    Toast.LENGTH_SHORT).show();

        }
    });

    this.initialiseTabHost(savedInstanceState);
    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }

    this.intialiseViewPager();
}

protected void onSaveInstanceState(Bundle outState) {
    outState.putString("tab", mTabHost.getCurrentTabTag());
    super.onSaveInstanceState(outState);
}

private void intialiseViewPager() {

    List<Fragment> fragments = new Vector<Fragment>();
    fragments.add(Fragment.instantiate(this, Pirveli.class.getName()));
    fragments.add(Fragment.instantiate(this, Meore.class.getName()));
    fragments.add(Fragment.instantiate(this, Mesame.class.getName()));


    this.mPagerAdapter = new PagerAdapter(
            super.getSupportFragmentManager(), fragments);

    this.mViewPager = (ViewPager) super.findViewById(R.id.viewpager);
    this.horizontalScrollView = (HorizontalScrollView) super
            .findViewById(R.id.horizontalScrollView);
    this.mViewPager.setAdapter(this.mPagerAdapter);
    this.mViewPager.setOnPageChangeListener(this);
}

public void centerTabItem(int position) {
    mTabHost.setCurrentTab(position);
    final TabWidget tabWidget = mTabHost.getTabWidget();
    @SuppressWarnings("deprecation")
    final int screenWidth = getWindowManager().getDefaultDisplay()
            .getWidth();
    final int leftX = tabWidget.getChildAt(position).getLeft();
    int newX = 0;

    newX = leftX + (tabWidget.getChildAt(position).getWidth() / 2)
            - (screenWidth / 2);
    if (newX < 0) {
        newX = 0;
    }
    horizontalScrollView.scrollTo(newX, 0);
}

private void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();
    TabInfo tabInfo = null;
    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("All Channels").setIndicator(
                    "All Channels"), (tabInfo = new TabInfo("All Channels",
                    Pirveli.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("Commersant").setIndicator(
                    "Commersant"), (tabInfo = new TabInfo("Commersant",
                    Meore.class, args)));

    this.mapTabInfo.put(tabInfo.tag, tabInfo);
    MainActivity.AddTab(this, this.mTabHost,
            this.mTabHost.newTabSpec("Tabula").setIndicator("Tabula"),
            (tabInfo = new TabInfo("Tabula", Mesame.class, args)));



    mTabHost.setOnTabChangedListener(this);
}

private static void AddTab(MainActivity activity, TabHost tabHost,
        TabHost.TabSpec tabSpec, TabInfo tabInfo) {

    tabSpec.setContent(activity.new TabFactory(activity));
    tabHost.addTab(tabSpec);
}

public void onTabChanged(String tag) {

    for (int tabIndex = 0; tabIndex < mTabHost.getTabWidget().getTabCount(); tabIndex++) {
        View tab = mTabHost.getTabWidget().getChildTabViewAt(tabIndex);
        TextView t = (TextView) tab.findViewById(android.R.id.title);
        t.setTextColor(getResources().getColor(R.color.text_color));
    }

    int pos = this.mTabHost.getCurrentTab();
    this.mViewPager.setCurrentItem(pos);
}

@Override
public void onPageScrolled(int position, float positionOffset,
        int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {

    centerTabItem(position);
}

@Override
public void onPageScrollStateChanged(int state) {

}

private class TabInfo {
    private String tag;
    @SuppressWarnings("unused")
    private Class<?> clss;
    @SuppressWarnings("unused")
    private Bundle args;
    @SuppressWarnings("unused")
    private Fragment fragment;

    TabInfo(String tag, Class<?> clazz, Bundle args) {
        this.tag = tag;
        this.clss = clazz;
        this.args = args;
    }

}

class TabFactory implements TabContentFactory {

    private final Context mContext;

    public TabFactory(Context context) {
        mContext = context;
    }

    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }

}
}

这是第一个fragmen的代码(所有Fragment的代码都是相同的,不同的只是json的URl)

public class Pirveli extends Fragment {
private String URL = "*******************************";

public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;
public TransparentProgressDialog pd;
public JSONParser jsonparser;
static DealBoxAdapter adapter;
ProgressDialog pDialog, pDialog1;
static String fontPath2 = "font.ttf";
public static Typeface tf2;
ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();
public ImageLoader imageLoader;
static final int DIALOG_ERROR_CONNECTION = 1;
private int screenSize;
private LoadDataAllChanelsToServer loader;
public static String dateTime;
private ArrayList<Content> contents = new ArrayList<Content>();
public static boolean oneTime = false;
public TextView journal, tittle, description, smalllink, DateTime,
        smallstatID;
HashMap<String, String> map;
private ConnectionDetector cd;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.send_items, container, false);
    list = (ListView) rootView.findViewById(R.id.pirvelilistview);
    cd = new ConnectionDetector(getActivity());
    pd = new TransparentProgressDialog(getActivity(), R.drawable.loader);
    screenSize = getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK;
    loader = new LoadDataAllChanelsToServer();

    list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(android.widget.AdapterView<?> parent,
                View view, int position, long id) {

            journal = (TextView) view.findViewById(R.id.smalljournal1);

            tittle = (TextView) view.findViewById(R.id.smalltitle1);
            description = (TextView) view
                    .findViewById(R.id.smallDescription1);
            smalllink = (TextView) view.findViewById(R.id.smalllink1);
            DateTime = (TextView) view.findViewById(R.id.smallDateTime1);
            smallstatID = (TextView) view.findViewById(R.id.smallstatID1);
            String Stringjournal = journal.getText().toString();
            String Stringtittle = tittle.getText().toString();
            String Stringdescription = description.getText().toString();
            String Stringlink = smalllink.getText().toString();
            String StringdateTime = DateTime.getText().toString();
            String StringstatID = smallstatID.getText().toString();

            Intent in = new Intent(getActivity(),
                    com.leavingstone.dealbox.Result.class);
            in.putExtra("KEY_journal", Stringjournal);
            in.putExtra("KEY_title", Stringtittle);
            in.putExtra("KEY_description", Stringdescription);
            in.putExtra("KEY_link", Stringlink);
            in.putExtra("KEY_pubDate", StringdateTime);
            in.putExtra("KEY_statID", StringstatID);

            String url = itemList.get(position).get(Pirveli.KEY_image);

            if (url.endsWith("-c.jpg"))
                url = url.replace("-c.jpg", ".jpg");
            in.putExtra("Bitmap", url);

            in.putExtra("Bitmap", url);

            startActivity(in);

        }
    });

    if (!cd.isConnectingToInternet()) {
        Toast.makeText(getActivity(), "No internet connection",
                Toast.LENGTH_SHORT).show();

    } else {
        loader.execute();

    }

    return rootView;
}

private class LoadDataAllChanelsToServer extends
        AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {

         pd.show();
    }

    @Override
    protected String doInBackground(String... urls) {

        jsonparser = new JSONParser();

        JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
        try {

            jsonarray = jsonobject.getJSONArray("data");

            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                map = new HashMap<String, String>();

                map.put("journal", jsonobject.getString(KEY_journal));
                map.put("image", jsonobject.getString(KEY_image));
                map.put("title", jsonobject.getString(KEY_title));
                map.put("description",
                        jsonobject.getString(KEY_description));
                map.put("JournalID", jsonobject.getString(KEY_JournalID));
                map.put("pubDate", jsonobject.getString(KEY_pubDate));
                map.put("statID", jsonobject.getString(KEY_statID));

                Content cont = new Content(jsonobject.getString("journal"),
                        jsonobject.getString("image"),
                        jsonobject.getString("title"),
                        jsonobject.getString("pubDate"),
                        jsonobject.getString("description"),
                        jsonobject.getString("JournalID"),
                        jsonobject.getString("statID"));
                contents.add(cont);

                itemList.add(map);
                dateTime = itemList.get(itemList.size() - 1).get(
                        KEY_pubDate);
            }

        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        return itemList.toString();

    }

    @Override
    protected void onPostExecute(String result) {
        try {
            if (pd != null) {
                pd.dismiss();

            }
        } catch (Exception e) {

        }

        try {
            adapter = new DealBoxAdapter(getActivity(), itemList,
                    screenSize);
            list.setAdapter(adapter);

        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

}

@Override
public void onDestroy() {
    super.onDestroy();
    try {
        if (loader != null) {
            loader.cancel(true);
            loader = null;
        }
    } catch (Exception e) {

    }

}
}

当我去每个片段时,可以运行每个AsyncTask吗? 例如,第一次应该运行第一个片段的Asynctas等等....

1 个答案:

答案 0 :(得分:0)

在Viewpager中,您可以使用setUserVisbileHint(boolean isVisibleToUser) http://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean)来检测您的片段是否已显示。如果您将loader.execute();放在那里,它将在显示片段时执行。

请注意,setUserVisbileHint()仅适用于Viewpager。

相关问题