2014-02-18 3 views
1

Я работаю Tabhost (viepager) У меня есть три фрагмента и каждый фрагмент, который я разбирал json, и я могу показать элементы json в списке каждого фрагмента (он работает идеально), но у меня есть одна проблема. Я использую AsyncTask для разбора JSON и шоу ListView, но все три AsyncTask работает вместе это мой кодAndroid три asynctasks работает вместе

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

} 
} 

и это код с первым Фрагмена лет (весь код Fragment «s таким же, отличается URL-адреса только JSON в)

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

С СОТОВОГО андроид версии, вы можете выполнить 5 AsyncTask одновременно, но до Honeycomb пула потоков была ограничена 1. –

+0

мое приложение версии 4.1 и выше ... (андроида: minSdkVersion = «11» андроид : targetSdkVersion = "14") – user3293990

+0

Возможный дубликат [Как определить, когда фрагмент становится видимым в ViewPager] (http://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in -viewpager) –

ответ

0

В течение ViewPager вы можете использовать setUserVisbileHint(boolean isVisibleToUser)http://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean), чтобы обнаружить, если ваш фрагмент IST показано на рисунке. Если вы разместите там loader.execute();, он будет выполнен при показе фрагмента.

Отметьте, что setUserVisbileHint() работает только на Viewpager.

Смежные вопросы