Tabs fragment fetch data every time I change tab

China☆狼群 提交于 2019-12-02 10:08:24

问题


activity_profile.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?android:attr/actionBarSize"
android:background="@drawable/stalker_background" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" 
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

            <android.support.v4.view.ViewPager
                android:id="@+id/VPSlider"
                android:layout_width="match_parent"
                android:layout_height="175dp"
            />


            <android.support.v4.app.FragmentTabHost
                android:id="@android:id/tabhost"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >

                    <TabWidget
                    android:id="@android:id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" />

                    <FrameLayout
                    android:id="@android:id/tabcontent"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                </LinearLayout>

                </android.support.v4.app.FragmentTabHost>

            </LinearLayout>
            </ScrollView>


</LinearLayout>

ProfileActivity.java

package com.stalker.androidapp;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.Window;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.facebook.Session;
import com.google.gson.Gson;
import com.stalker.adapters.ViewPagerAdapter;
import com.stalker.objects.HomeSliderClassForAdapter;
import com.stalker.objects.LikeCategorySummaryResult;
import com.stalker.objects.StoryResult;
import com.stalker.objects.eStoryType;

public class ProfileActivity extends FragmentActivity {

AsyncTask<String, String, String> StoryResponse;
public String storyResponseString;

TextView tv;
public String UserId;
String UserName;
String AccessToken;
ViewPager VPSlider;
public LikeCategorySummaryResult interestResult;
FragmentTabHost mTabHost;
StoryResult Stories = new StoryResult();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    VPSlider = (ViewPager) findViewById(R.id.VPSlider);




    // /////////////////////////

    mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(),
            android.R.id.tabcontent);
    mTabHost.addTab(
            mTabHost.newTabSpec("tab1").setIndicator(
                    getResources().getString(R.string.interest)),
            InterestTabFragment.class, null);
    mTabHost.addTab(
            mTabHost.newTabSpec("tab2").setIndicator(
                    getResources().getString(R.string.interaction)),
            InteractionTabFragment.class, null);
    mTabHost.addTab(
            mTabHost.newTabSpec("tab3").setIndicator(
                    getResources().getString(R.string.hangout)),
            HangoutTabFragment.class, null);

    mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {
            // TODO Auto-generated method stub
            FragmentManager fragmentManager = getSupportFragmentManager();

            InterestTabFragment tabOneFrgment = (InterestTabFragment) fragmentManager
                    .findFragmentByTag("tab1");

            InteractionTabFragment tabTwoFrgment = (InteractionTabFragment) fragmentManager
                    .findFragmentByTag("tab2");

            HangoutTabFragment tabThreeFrgment = (HangoutTabFragment) fragmentManager
                    .findFragmentByTag("tab3");

            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();

            if (tabId.equalsIgnoreCase("tab1")) {
                if (tabOneFrgment != null) {
                    if (tabTwoFrgment != null) {
                        fragmentTransaction.hide(tabTwoFrgment);
                    }
                    if (tabThreeFrgment != null) {
                        fragmentTransaction.hide(tabThreeFrgment);
                    }                       
                    fragmentTransaction.show(tabOneFrgment);
                }
            } else if (tabId.equalsIgnoreCase("tab2")) {
                if (tabTwoFrgment != null) {
                    if (tabOneFrgment != null) {
                        fragmentTransaction.hide(tabOneFrgment);
                    }
                    if (tabThreeFrgment != null) {
                        fragmentTransaction.hide(tabThreeFrgment);
                    }
                    fragmentTransaction.show(tabTwoFrgment);
                }
            } else {
                if (tabThreeFrgment != null) {
                    if (tabOneFrgment != null) {
                        fragmentTransaction.hide(tabOneFrgment);
                    }
                    if (tabTwoFrgment != null) {
                        fragmentTransaction.hide(tabTwoFrgment);
                    }
                    fragmentTransaction.show(tabThreeFrgment);
                }
            }

            fragmentTransaction.commit();

        }
    });


    Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
        // Get the user's data
        AccessToken = session.getAccessToken();
        makeStoriesRequest(session);
    }



}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.stalker_profile_menu, menu);
    return true;
}

private void makeStoriesRequest(final Session session) {

    String URL = "http://..../";
    JSONObject UserStory;
    JSONObject ProfileStoryString = new JSONObject();
    StoryResponse = new RequestTask().execute(URL);
    try {
        storyResponseString = StoryResponse.get();
        UserStory = new JSONObject(storyResponseString);
        ProfileStoryString = UserStory.getJSONObject("StoryResult");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        Gson gson = new Gson();
        try {
            // j = new JSONObject(responseString);
            Stories = gson.fromJson(ProfileStoryString.toString(),
                    StoryResult.class);
        } catch (Exception e) {
            Log.i("my", e.getMessage());
            e.printStackTrace();
        }

    } catch (Throwable t) {
        Log.e("My App", "Could not parse malformed JSON: \""
                + storyResponseString + "\"" + t.getMessage());
    }

    ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSlider());

    VPSlider.setAdapter(adapter);

}


@Override
protected void onResumeFragments() {
    super.onResumeFragments();

}


}

I have this fragment activity on which I'm showing tabs. I have three tabs. For now I have only added code inside InterestTabFragment.java

package com.stalker.androidapp;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.devsmart.android.ui.HorizontalListView;
import com.facebook.Session;
import com.google.gson.Gson;
import com.stalker.adapters.CategoryLVAdapter;
import com.stalker.objects.LikeCategorySummaryResult;

public class InterestTabFragment extends Fragment{

View view;
String access_token;

AsyncTask<String, String, String> FirstResponse;
public String responseString;
JSONObject joiningYear;
HorizontalListView listview;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreateView(inflater, container, savedInstanceState);
    view = inflater.inflate(R.layout.interest_tab_fragment, container, false);

    listview = (HorizontalListView) view.findViewById(R.id.LVCategory);


        Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) {
            // Get the user's data
            access_token = session.getAccessToken();
            makeInterestRequest(session);
        }

    return view;
}


private void makeInterestRequest(final Session session) {
    access_token = session.getAccessToken();
    String URL =     "http://...";


    JSONObject HomeCardString = new JSONObject();
    FirstResponse = new RequestTask().execute(URL);
    try {
        responseString = FirstResponse.get();
        joiningYear = new JSONObject(responseString);
        HomeCardString = joiningYear.getJSONObject("LikeCategorySummaryResult");
//          HomeCardString = TestApiResult.getJSONObject("UserHomeResult");         
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {       
        Gson gson = new Gson();
        try
        {
//              j = new JSONObject(responseString);
            ((ProfileActivity)getActivity()).interestResult =     gson.fromJson(HomeCardString.toString(), LikeCategorySummaryResult.class);

        }
        catch(Exception e)
        {
            Log.i("myyyy", e.getMessage());
            e.printStackTrace();
        }

    } catch (Throwable t) {
        Log.e("My App", "Could not parse malformed JSON: \"" + responseString + "\"" +    t.getMessage());
    }

    CategoryLVAdapter adapter = new CategoryLVAdapter(getActivity(), R.layout.category_item_template,     ((ProfileActivity)getActivity()).interestResult.categories);

    listview.setAdapter(adapter);

//      listView.setAdapter(adapter);

}


}

This code works ok. But when I goto my second tab and then return to first tab. It load data again. but I want it to just show previous fragment don't load it again.

Link to a nice tutorial will also be helpful, but I am already following this tutorial but it is not working as I was expecting it to work.


回答1:


If you go to 3rd tab then go to the 2nd or 1st tab then 1st will be recreated and call onCreate, that is the default behavior of fragment. But going to just 2nd tab and then back to 1st tab will not recreate the 1st tab. I have made some changes in the InterestTabFragment.java below only in onCreate. See if it helps, if not then notify me, I may try again. Thanks.....

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreateView(inflater, container, savedInstanceState);
    view = inflater.inflate(R.layout.interest_tab_fragment, container, false);

    listview = (HorizontalListView) view.findViewById(R.id.LVCategory);

        if(((ProfileActivity)getActivity()).interestResult.categories == null){
            Session session = Session.getActiveSession();
            if (session != null && session.isOpened()) {
                // Get the user's data
                access_token = session.getAccessToken();
                makeInterestRequest(session);
        }
        } else {
            CategoryLVAdapter adapter = new CategoryLVAdapter(getActivity(), R.layout.category_item_template,     ((ProfileActivity)getActivity()).interestResult.categories);

            listview.setAdapter(adapter);
        }


    return view;
}


来源:https://stackoverflow.com/questions/25337570/tabs-fragment-fetch-data-every-time-i-change-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!