Android three asynctasks running together - android

I working Tabhost(viepager) i have three fragments and each fragments i parsed json and i can show json's items in listview each fragments(it working perfect)but i have one problem. i use AsyncTask to parse json and show listview but all three Asynctask running together
this is a my code
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;
}
}
}
and this is a first fragmen's code (all Fragment 's code is same,different is only json's 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) {
}
}
}
it is a possible to run every AsyncTask when i go each fragments?
for example ,first time should run first fragment's Asynctas and etc....

Within a Viewpager you can use setUserVisbileHint(boolean isVisibleToUser) http://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean) to detect if your fragment ist shown. If you place the loader.execute(); in there, it will be executed on showing of the fragment.
Note that setUserVisbileHint() only works within a Viewpager.

Related

Viewpager adapter in android

Why does my pager adapter doesn't want to start from my first item. When I start ContainerIspiti activity, and show first fragment, the view pager dones't show the right element. Insted of first, view pager shows the second element, and I can't to swipe to first element of my array list. Does anybody have solution.
Here is my code for ConainterIspiti
public class ContainerIspiti extends FragmentActivity{
private Button next, previous, odgovori, informacije;
private TextView textPitanja, brojPitanja;
private ViewPager pager;
private PagerAdapter mPagerAdapter;
public static ArrayList<Pitanja> getAllPitanja;
public static ArrayList<Pitanje_has_Slika> getAllImages;
private Intent intent;
private DBTools db = new DBTools(this);
private ProgressDialog pDialog;
private int broj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_container_pitanja);
Bundle bundle = new Bundle();
intent = getIntent();
Dohvati d = new Dohvati();
d.execute();
textPitanja = (TextView) findViewById(R.id.kategorijaTextViewPitanjeActivity);
brojPitanja = (TextView) findViewById(R.id.brojPitanjaTextViewPitanjeActivity);
pager = (ViewPager) findViewById(R.id.pagerPitanja);
pager.setCurrentItem(0, true);
bundle.putString("NAZIV_KATEGORIJE", intent.getStringExtra("NAZIV_KATEGORIJE"));
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.i("Position je sljedeci ", String.valueOf(position));
return PitanjaFragment.create(position);
}
#Override
public int getCount() {
Log.i("Velicina polja je ", String.valueOf(getAllPitanja.size()));
Log.i("Prvi eleemnt liste je", getAllPitanja.get(0).getTextPitanja());
return getAllPitanja.size();
}
}
private class Dohvati extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContainerIspiti.this);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
getAllPitanja = db
.getAllPitanja(intent.getStringExtra("id_kategorije"));
Log.i("Ovoliki je get all pitanja", String.valueOf(getAllPitanja.size()));
getAllImages = db.getAllPitanjaImages();
Log.i("ovoliko je slika", String.valueOf(getAllImages.size()));
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
brojPitanja.setText(String.valueOf(position) + "/" + String.valueOf(getAllPitanja.size()));
broj = position;
}
});
textPitanja.setText(intent.getStringExtra("NAZIV_KATEGORIJE"));
brojPitanja.setText(String.valueOf(broj) + "/" + getAllPitanja.size());
}
}
}
and here is my fragment activity
public class PitanjaFragment extends Fragment implements API{
public static final String ARG_PAGE = "page";
private int broj;
private ImageView image;
private TextView textPitanja;
private String uri;
private View view;
private ListView listView;
private Typeface custom_font;
private boolean odgovoreno, tocno;
private ArrayList<Odgovor> odgovorList;
private PitanjaAdapter adapter;
private DBTools db;
private List<Integer> kliknuti;
private HashMap<Integer, List<Integer>> odgBrojPitanja;
public static PitanjaFragment create(int pageNumber) {
PitanjaFragment fragment = new PitanjaFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public PitanjaFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
broj = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_pitanja, container, false);
image = (ImageView) view.findViewById(R.id.imageSlikaImageView);
image.setOnClickListener(this);
textPitanja = (TextView) view.findViewById(R.id.textPitanjaTextViewPitanjaActivity);
db = new DBTools(getActivity());
listView = (ListView) view.findViewById(R.id.listView);
updateDisplay((broj+1));
return view;
}
public void updateDisplay(int z) {
odgovoreno = false;
tocno = true;
textPitanja.setText(stripHtml(String.valueOf(ContainerIspiti.getAllPitanja.get(z).getTextPitanja())));
image.setImageBitmap(null);
//info = ContainerIspiti.getAllPitanja.get(z).getInfo();
Log.d("Postoji", ContainerIspiti.getAllImages.get(z).getNazivSlike() + ", ");
for (int j = 0; j < ContainerIspiti.getAllImages.size(); j++) {
if (ContainerIspiti.getAllImages.get(j).getIdPitanja() == ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
&& ContainerIspiti.getAllImages.get(j).getNazivSlike() != null) {
Log.i("Id pitanja slike + idpitanja pitanja + idSlike",
ContainerIspiti.getAllImages.get(j).getIdPitanja()
+ ", "
+ String.valueOf(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
+ ", "
+ ContainerIspiti.getAllImages.get(j).getIdSlika()));
image.setVisibility(View.VISIBLE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi);
//povecalo.setEnabled(true);
uri = PregledZnakova.PHOTOS_BASE_URL
+ ContainerIspiti.getAllImages.get(j).getNazivSlike();
int rounded_value = 40;
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.placeholder).showStubImage(R.drawable.placeholder).cacheInMemory().cacheOnDisc().displayer(new RoundedBitmapDisplayer(rounded_value)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
ImageLoader.getInstance().displayImage(uri, image,options);
break;
// }
} else {
image.setVisibility(View.GONE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi_neaktivno);
//povecalo.setEnabled(false);
}
}
odgovorList = db.getAllOdgovore(Integer.toString(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()));
adapter = new PitanjaAdapter(getActivity(),
R.layout.pitanja_entry, odgovorList);
listView.setAdapter(adapter);
for (int i=0;i<ContainerIspiti.getAllPitanja.size();i++){
if (ContainerIspiti.getAllPitanja.get(i).isTocno()){
Log.i("Ovo pitanje je tocno", ContainerIspiti.getAllPitanja.get(i).getTextPitanja());
}
}
}
#Override
public int getItemBroj() {
return broj;
}
#Override
public int getPosition() {
return broj;
}
#Override
public void setPosition(int position) {
this.broj = position;
}
#Override
public Fragment getFragment() {
return this;
}
}
Thanks for your time and your help.
In the onCreateView() method of your PitanjaFragment class, replace:
updateDisplay((broj+1));
with
updateDisplay(broj);
Try this. It should work.

Android Fragment Content Lost

i have a problem on android eclipse with fragments in a viewpager. When an home activity starts i show an actionbar tabs and first fragment on the screen. When i swipe to next fragment and then back to first fragment, first fragment contents are still on the screen. But on the other hand if a swipe 2 times to right and go back first fragment, its contents are lost and blank screen is shown. My codes are below. How to retain each fragment content either it is shown or is visible ? any help is appreciated. Thanx in advance.
HomeActivity.java
public class HomeActivity extends FragmentActivity implements TabListener {
private String[] menuItems = null;
private ActionBar bar = null;
private ViewPager viewPager = null;
private TabsAdapter tabsAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setPageMargin(10);
menuItems = getResources().getStringArray(R.array.menuTitles);
bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabsAdapter = new TabsAdapter(this, viewPager);
for (int i = 0; i < menuItems.length; i++) {
switch (i) {
case 0:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NewsFeedActivity.class, null);
break;
case 1:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NotificationActivity.class, null);
break;
case 2:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NewsFeedActivity.class, null);
break;
case 3:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NotificationActivity.class, null);
break;
case 4:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NewsFeedActivity.class, null);
break;
default:
break;
}
}
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
// Restore selected tab
int saved = savedInstanceState.getInt("tab", 0);
if (saved != getActionBar().getSelectedNavigationIndex())
getActionBar().setSelectedNavigationItem(saved);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public static class TabsAdapter extends FragmentPagerAdapter implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mContext, "Reselected!", Toast.LENGTH_SHORT).show();
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mContext, "gokay!", Toast.LENGTH_SHORT).show();
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(),
info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
}
NewsFeedActivity.java
public class NewsFeedActivity extends Fragment {
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
private ArrayList<String> xmlList = null;
private XMLParser parser = null;
private String xml = "";
private Document doc = null;
private NodeList nl = null;
private View view = null;
private Element e = null;
private ListView listNewsFeed = null;
private static Bundle args = null;
private static NewsFeedActivity newsFeed = null;
private ArrayAdapter<String> adapter = null;
public static NewsFeedActivity newInstance(int page, String title) {
newsFeed = new NewsFeedActivity();
args = new Bundle();
args.putInt("Page", page);
args.putString("newsFeed", title);
newsFeed.setArguments(args);
return newsFeed;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_news_feed, container, false);
if (getActivity().getActionBar().getSelectedTab().getPosition() == 0) {
new NewsFeeder().execute("");
}
return view;
}
private class NewsFeeder extends AsyncTask<String, String, String> {
private ProgressDialog mProgressDialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Haber kaynağı yenileniyor..");
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
xmlList = new ArrayList<String>();
try {
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL); // getting XML
Log.i("gokay", xml);
doc = parser.getDomElement(xml); // getting DOM element
nl = doc.getElementsByTagName(KEY_ITEM);
return null;
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
Log.e("gokay", e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mProgressDialog.dismiss();
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
xmlList.add(parser.getValue(e, KEY_ID));
xmlList.add(parser.getValue(e, KEY_NAME));
xmlList.add("Rs." + parser.getValue(e, KEY_COST));
xmlList.add(parser.getValue(e, KEY_DESC));
}
listNewsFeed = (ListView) view.findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, xmlList);
listNewsFeed.setAdapter(adapter);
// onFoodMenuItemsDBAddFinished();
}
}
}
try using
setRetainInstance(true);
in oncreate() fragment

Android some Asynctask running same time in Fragment

i'm working json.i created viepager(tabhost) i have three fragment and each fragment i parsed json (i use Asynctask each fragment) and i can show json data in listview(image and text).it working perfect but when program is starting there three asynctask starting same time and program is slowly and also i have another problem when i go next fragment and then if i go to back fragment Asynctask also running twice.for example if my json server link contains two data when i go to back fragment then i got 4 items
what is a problem if anyone knows solution please help me
thanks
this is a my code:
MainActivity.java code
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;
}
}
}
and first fragment java code
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) {
}
}
}
another two classes(fragments)code is similar this but differenc is only URl

Android json viewpager action bar fragmentpageadapter

I have created action bar and viewpager, I have three fragment. Each of the fragment I parsed json and can show each listview . My problem is : If I click second fragment and then I go back(click firs fragmet) when I go to the next fragment and then if I go to a front fragment at this situation Loading information from the server occurs twice, I use AsyncTask class to load info from server.
Below is a my code :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SendItemsFragment();
case 1:
return new RecivedItemsFragment();
case 2:
return new FavoriteItemsFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
public class MainActivity extends FragmentActivity implements TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "test1", "test2", "test3" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setIcon(R.color.white);
actionBar.setDisplayShowTitleEnabled(true);
Drawable d = getResources().getDrawable(R.drawable.acttitle);
getActionBar().setBackgroundDrawable(d);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
viewPager = (ViewPager) findViewById(R.id.vp_main);
viewPager.setAdapter(mAdapter);
getActionBar().setCustomView(R.layout.menu_example);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// actionBar.setStackedBackgroundDrawable(getResources().getDrawable(
// R.drawable.background)); background viewpager
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
This is - one of the fragment's code. Similar to all three of them. The only difference is that the load of data from the server, And also use the AsyncTask class, each of which had a different.
public class SendItemsFragment 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;
#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.listView1);
pd = new TransparentProgressDialog(getActivity(), R.drawable.loader);
screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
loader=new LoadDataAllChanelsToServer();
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);
HashMap<String, String> 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));
itemList.add(map);
}
} 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();
}
}
}
}
that's all :)
if anyone knows solution please help me
thank you
You should cancel async task when your Fragment is destroyed.
private LoadDataAllChanelsToServer mLoader;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
mLoader = new LoadDataAllChanelsToServer();
mLoader.execute();
...
}
#Overide
public onDestroy() {
super.onDestroy();
if(mLoader != null) {
mLoader.cancel(true);
mLoader = null;
}
this way when fragment is destroyed AsyncTask will be canceled.
You can also set ViewPager.setOffscreenPageLimit(2). This way, since you have only 3 Fragments, no Fragments will be destroy and therefore your onViewCreated will only be called once.

Save the fragment state in tabs switch

it is one week I try to solve this problem whitout success. Please help me.
I use the tabs navigation with viewpager. This is the class where I put the tabs and the FragmentPagerAdapter class:
public class Detail extends SherlockFragmentActivity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
mViewPager = (ViewPager)findViewById(R.id.pager);
// Add the tabs
mTabsAdapter = new TabsAdapter(this, bar, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.filmtab),
FragmentFilm.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.cinematab),
FragmentCinema.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.dintornitab),
FragmentPdi.class, null);
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
}
public static class TabsAdapter extends FragmentPagerAdapter
implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ActionBar mBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(Detail activity, ActionBar bar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mBar = bar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<? extends Fragment> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
The 3 fragment classes are all the same I copy here just one;
In the fragment class I use async task for download the data I need to put in the view, I do this in the onActivityCreated method:
public class FragmentFilm extends SherlockFragment
{
private Detail act;
private DetailedRec detail_film;
private View view;
private String a;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
setRetainInstance(true);
view = inflater.inflate(R.layout.tab_film_info, container, false);
return view;
}
/*
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
act = (Detail) getActivity();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new DownloadFilmDetailAsyncTask().execute();
}
private class DownloadFilmDetailAsyncTask extends AsyncTask<Void, DetailedRec, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ProgressBar prBar = (ProgressBar)getView().findViewById(R.id.progressbar_film);
prBar.setVisibility(View.GONE);
ScrollView lay = (ScrollView)getView().findViewById(R.id.tab_filmsummary);
lay.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params)
{
try
{
String locale = getResources().getConfiguration().locale.getDisplayName();
JSONObject objSend = new JSONObject();
objSend.put("idFilm", act.getIdFilm());
objSend.put("cinemaId",act.getIdCinema());
int ind = locale.indexOf("(");
String locale_send = locale.substring(0, ind-1);
objSend.put("locale", locale_send);
ArrayList<String> otherCin = new ArrayList<String>(Arrays.asList(act.getOtherCinemas()));
JSONArray othCin = new JSONArray(otherCin);
objSend.put("otherCinemas", othCin );
JSONObject jsonObject = sendAndGetJSONObject(JSON_SERVER+"JsonServer?op=getFilmbyId",objSend);
DetailedRec detail_rec = new DetailedRec();
//FILM
detail_rec.setFilmId(jsonObject.getString("filmId"));
detail_rec.setName(jsonObject.getString("name"));
detail_rec.setImageUrl(jsonObject.getString("imageUrl").replace("640", "80"));
detail_rec.setActors(jsonObject.getString("actors"));
detail_rec.setGenre(jsonObject.getString("genre"));
detail_rec.setDirector(jsonObject.getString("director"));
detail_rec.setPlot(jsonObject.getString("plot"));
detail_rec.setYear(jsonObject.getString("year"));
detail_rec.setDuration(jsonObject.getString("duration"));
detail_rec.setTrailer(jsonObject.getString("trailer"));
detail_rec.setRating(jsonObject.getString("rating"));
detail_film = detail_rec;
publishProgress(detail_rec);
}
catch (IOException ignored)
{
}
catch (JSONException ignored)
{
}
return null;
}
#Override
protected void onProgressUpdate(DetailedRec... values)
{
for (final DetailedRec detail_rec : values)
{
updateViews(detail_rec);
}
}
private JSONObject getJSONObject(String url) throws IOException, MalformedURLException, JSONException
{
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
InputStream in = conn.getInputStream();
try
{
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(in),"WINDOWS_1252"));
for (String line = r.readLine(); line != null; line = r.readLine())
{
sb.append(line);
}
return new JSONObject(sb.toString());
}
finally
{
in.close();
}
}
private JSONObject sendAndGetJSONObject(String url,JSONObject request) throws IOException, MalformedURLException, JSONException
{
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
InputStream in=null;
try{
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(request.toString());
se.setContentType((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
in = entity.getContent();
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(in),"WINDOWS_1252"));
for (String line = r.readLine(); line != null; line = r.readLine())
{
sb.append(line);
}
return new JSONObject(sb.toString());
}catch(Exception e){
}
finally
{
in.close();
}
return null;
}
}
private void updateViews(final DetailedRec detail_rec){
//FILM
TextView filmName = (TextView) getView().findViewById(R.id.movieTitle);
filmName.setText(detail_rec.getName().trim());
TextView actors = (TextView) getView().findViewById(R.id.movieActor);
actors.setText(detail_rec.getActors().trim());
TextView genre = (TextView) getView().findViewById(R.id.movieGenre);
genre.setText(detail_rec.getGenre().trim());
TextView director = (TextView) getView().findViewById(R.id.movieDirector);
director.setText(detail_rec.getDirector().trim());
TextView plot = (TextView) getView().findViewById(R.id.moviePlot);
plot.setText(detail_rec.getPlot().trim());
TextView year = (TextView) getView().findViewById(R.id.movieYear);
year.setText(detail_rec.getYear().trim());
TextView duration = (TextView) getView().findViewById(R.id.movieDuration);
duration.setText(detail_rec.getDuration().trim());
ImageView image = (ImageView) getView().findViewById(R.id.moviePoster);
new DownloadImagesTask(detail_rec.getImageUrl().trim().replace("80", "100")).execute(image);
//image.setImageBitmap(downloadBitmap(detail_rec.getImageUrl().trim().replace("80", "100")));
//Rating
if(detail_rec.getRating().compareTo("N/A")!=0){
RatingBar rateBar = (RatingBar)getView().findViewById(R.id.MovieRatingBar);
rateBar.setRating(Float.parseFloat(detail_rec.getRating()));
}
//Trailer
Button trailer = (Button)getView().findViewById(R.id.trailer);
if(detail_rec.getTrailer().compareTo("")!=0){
trailer.setVisibility(View.VISIBLE);
trailer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index = detail_rec.getTrailer().indexOf("v=");
String videoId="";
if(index!=-1){
videoId = detail_rec.getTrailer().substring(index+2); //"Fee5vbFLYM4";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId));
intent.putExtra("VIDEO_ID", videoId);
startActivity(intent);
}
}
});
}
}
}
Ok, in my application I want the fragment is load one time. I explain so good:
When I start the Detail class the fragment classes are istantiate and the AsyncTask in all the 3 fragment start, now when the user switch from one tab to other I want the fragment in tab unselected don't lost the data and the view because now when I switch from one tab to another and then return the first tab this is recreate and the onActivityCreated method is called again!
Please help me, I search in all place but I dont find solution!!
P.S. I use the SherlockActionBar, I don't know id it is relevant. Sorry for my bad English
Thank you
Just after instantiating the ViewPager, add this
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(3);
That should do it!

Categories

Resources