Android中的一些Asynctask在Fragment中同时运行

时间:2014-03-17 10:07:01

标签: android json android-asynctask android-viewpager

我正在工作json.i创建了viepager(tabhost)我有三个片段和每个片段我解析了json(我使用Asynctask每个片段)我可以在listview中显示json数据(图像和文本)。完美但是当程序启动的时候有三个asynctask开始同一时间和程序是缓慢的,当我去下一个片段时我还有另一个问题然后如果我回到片段Asynctask也运行两次。例如,如果我的json服务器链接包含两个数据当我回到片段然后我有4件物品 如果有人知道解决方案有什么问题请帮助我 谢谢 这是我的代码: MainActivity.java代码

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;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    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();
    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("Send").setIndicator("Send"),
            (tabInfo = new TabInfo("Send", Pirveli.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

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

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

    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 i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
        TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i)
                .findViewById(android.R.id.title);
        // tv.setTextColor(getResources().getColor(R.color.sa_green));
    }
    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;
    private Class<?> clss;
    private Bundle args;
    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;
    }

}

} 和第一个片段java代码

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


private JSONArray jsonarray;
private ListView list;
private TransparentProgressDialog pd;
private JSONParser jsonparser;
private static DealBoxAdapter adapter;

private ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();

private int screenSize;
private LoadDataAllChanelsToServer loader;
private static String dateTime;
private ArrayList<Content> contents = new ArrayList<Content>();
private static boolean oneTime = false;
private TextView journal, tittle, description, smalllink, DateTime,
        smallstatID;

private boolean scrollDetected = false;

@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);

    pd = new TransparentProgressDialog(getActivity(), R.drawable.loader);
    screenSize = getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK;
    loader = new LoadDataAllChanelsToServer();


    // loader.execute();

    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(DealBoxComponents.KEY_image);

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

            in.putExtra("Bitmap", url);

            startActivity(in);
            // overridePendingTransition(R.anim.trans_left_in,
            // R.anim.trans_left_out);

        }
    });


    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);

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

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

                itemList.add(map);
                dateTime = itemList.get(itemList.size() - 1).get(
                        DealBoxComponents.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();
        }

    }

}



public void Notify() {

    adapter.notifyDataSetChanged();
    oneTime = false;
}

// @Override
// public void onDestroy() {
// super.onDestroy();
// try {
// if (loader != null) {
// loader.cancel(true);
// loader = null;
// }
// } catch (Exception e) {
// // TODO: handle exception
// }
//
// }
@Override
public void onPause() {
    super.onPause();
    try {
        if (loader != null) {
            loader.cancel(true);
            loader = null;
        }
    } catch (Exception e) {

    }
}

} 另外两个类(片段)代码与此类似,但differenc仅为URl

0 个答案:

没有答案