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!
Related
It's working fine in single GridView Json Object,when i am calling to tabView my tabs will displaying but my Gridview not set into my Tabs.
Please any one help me
Main Activity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
MyAdapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Kids();
case 2:
// Movies fragment activity
return new Kids();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
this activity not displaying in my Tabview,it will working fine in my single gridview activity,when i am calling in tabview it will not diisplaed my gridview
kids.java
public class Kids extends Fragment {
ListAdapter adapter;
private ArrayList<Pojo> gridData;
GridView grd;
private ProgressBar mProgressBar;
private String Sam_URL = "http://example.in/rest/jsoMain/document?name=Rekapalli";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
System.out.println("Servce Called");
gridData=new ArrayList<Pojo>();
grd =(GridView)rootView.findViewById(R.id.gridview);
Async as=new Async(getActivity(),grd);
as.execute(Sam_URL);
mProgressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
// grd.setBackgroundColor(Color.CYAN);
grd.setVerticalSpacing(7);
grd.setHorizontalSpacing(7);
return super.onCreateView(inflater, container, savedInstanceState);
}
class Async extends AsyncTask<String, Void, Integer>{
Context context;
GridView gridView;
public Async(Context context,GridView gridView) {
// TODO Auto-generated constructor stub
this.context=context;
this.gridView=gridView;
}
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
Integer result = 0;
try {
// Create Apache HttpClient
//HttpClient httpclient = new DefaultHttpClient();
URL url = new URL(Sam_URL);
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
// int statusCode =
// httpResponse.getStatusLine().getStatusCode();
// 200 represents HTTP OK
if (true) {
String response = streamToString(in);
parseResult(response);
result = 1; // Successful
} else {
result = 0; // "Failed
}
} catch (Exception e) {
}
return result;
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == 1) {
gridView.setAdapter(new MyAdapter(context,gridData));
gridView.setVisibility(View.VISIBLE);
}mProgressBar.setVisibility(View.GONE);
}
private void parseResult(String result) {
try {
Log.d("MainActivity", "JSON Result : " + result);
JSONArray response = new JSONArray(result);
for (int i = 0; i < response.length(); i++)
{
JSONObject obj = response.getJSONObject(i);
String Doc_name = obj.getString("documentName");
Log.d("documentName",Doc_name);
String Doc_file = obj.getString("documentFile");
String Doc_content = obj.getString("documentContent");
String Doc_offer=obj.getString("offer");
String Doc_address=obj.getString("address");
//Log.d("documentName","JSON Result : " + result);
Pojo gd = new Pojo();
gd.setDocumentName(Doc_name);
gd.setDocumentFile(Doc_file);
gd.setOffer(Doc_offer);
gd.setDocumentContent(Doc_content);
gd.setAddress(Doc_address);
gridData.add(gd);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Change from:
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Kids();
case 2:
// Movies fragment activity
return new Kids();
}
return null;
}
To:
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Games();
case 2:
// Movies fragment activity
return new Movies();
}
return null;
}
Hope that Helps!!!
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
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
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.
I have create an app the layout have three tab in Android 2.3. Each tab has one fragment, and in each fragment, there has a list view. All the data show in list view is from internet, the data always change, so I want to reload the data every time when I watch that fragment. For example, I am watching the "tab1" now, when I click "tab2" the data in "tab2" will reload, and when I click back to "tab1" the data in "tab1" will also reload again. I tried
ft.detach(frg);
ft.attach(frg);
ft.commit();
but always have errors.
Here is my codes.
MainActivity
public class MainActivity extends ActionBarActivity {
private ViewPager pager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = new ViewPager(this);
pager.setId(R.id.pager);
setContentView(pager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), pager);
mTabsAdapter.addTab(bar.newTab().setText("tab1"), Tab1.class, null);
mTabsAdapter.addTab(bar.newTab().setText("tab2"), Tab2.class, null);
mTabsAdapter.addTab(bar.newTab().setText("tab3"), Tab3.class, null);
}
}
Tab1
public class Tab1 extends ListFragment{
private String result;
protected ArrayAdapter listAdapter;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/sample.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
items.clear();
Thread t = new Thread(new sendPostRunnable());
t.start();
listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter);
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "Name: "+jobject.getString("name")+"\n";
temp += "Email: "+jobject.getString("email");
items.add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
listAdapter.notifyDataSetChanged();
}
});
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
TabsAdapter
public class TabsAdapter extends FragmentPagerAdapter implements TabListener, OnPageChangeListener{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final String TAG = "";
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, ActionBar bar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = bar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(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 onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i = 0; i<mTabs.size(); i++){
if (mTabs.get(i) == tag){
mViewPager.setCurrentItem(i);
}
}
}
#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();
}
}
Impelement some interface like OnMyRefreshListener in your fragment and then:
public void onPageSelected(int position) {
((OnMyRefreshListener)pagerViewAdapter.getItem()).onMyRefresh();
}
I am facing same problem in my previous app.
No more changes just add one line in your MainActivity.java
viewPager.setOffscreenPageLimit();
if you have a three tab then put viewPager.setOffscreenPageLimit(3);.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list_tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(4);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
Document