Android:无法使用服务器中的更新内容重新加载片段

时间:2016-09-14 05:51:06

标签: android-viewpager android-tablayout

我有一个Fragment作为具有tablayout的容器,viewpager有2个制表符片段。在主容器片段中,我有一个带有自定义按钮的工具栏,通过点击web服务点击更新选项卡片段中的内容。

这是容器片段的代码。

public class NotificationsFragment extends Fragment {

TabLayout tabLayout = null;
ViewPager viewPagerNotifications = null;

public NotificationsFragment()
 {
     // Required empty public constructor
}

public static NotificationsFragment newInstance() {

    Bundle args = new Bundle();

    NotificationsFragment fragment = new NotificationsFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_notifications, null);

    final Button mButton_right = (Button) getActivity().findViewById(R.id.Button_right);
    mButton_right.setVisibility(View.VISIBLE);

    final Button mButton_alerts = (Button) getActivity().findViewById(R.id.Button_alerts);
    mButton_alerts.setVisibility(View.GONE);

    tabLayout = (TabLayout) rootView.findViewById(R.id.TabLayout_notifications);
    tabLayout.addTab(tabLayout.newTab().setText("Symptoms"));
    tabLayout.addTab(tabLayout.newTab().setText("Diagnosis"));

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.textColorPrimary));
    tabLayout.setSelectedTabIndicatorHeight(8);
    tabLayout.setTabTextColors(ContextCompat.getColor(getActivity(),R.color.textColorPrimary),
            getResources().getColor(R.color.textColorPrimary));

    ViewCompat.setElevation(tabLayout, 5f);

    viewPagerNotifications = (ViewPager) rootView.findViewById(R.id.viewPagernotifications);


    final NotificationPagerAdapter pagerAdapter = new NotificationPagerAdapter(getFragmentManager(),tabLayout.getTabCount());
    viewPagerNotifications.setAdapter(pagerAdapter);

    viewPagerNotifications.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    viewPagerNotifications.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            Log.e("notif","onpageselected"+position);


        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPagerNotifications.setCurrentItem(tab.getPosition());

            switch (tab.getPosition())
            {
                case 0:
                    mButton_right.setVisibility(View.VISIBLE);
                    mButton_alerts.setVisibility(View.GONE);

                   /* LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getActivity());
                    Intent i = new Intent("TAG_REFRESH");
                    lbm.sendBroadcast(i);*/

                    break;

                case 1:
                    mButton_right.setVisibility(View.GONE);
                    mButton_alerts.setVisibility(View.VISIBLE);

                    break;

                default:
                    break;
            }



        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });




    // Inflate the layout for this fragment
    return rootView;
}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}


@Override
public void onDetach() {
    super.onDetach();
}

}

这是Pager Adapter类的代码

public class NotificationPagerAdapter extends FragmentStatePagerAdapter {

final int Illness = 1;
final int Symptoms = 0;

int numOfTabs;

SymptomsTabFragment symptomsTabFragment;
IllnessTabFragment illnessTabFragment;


public NotificationPagerAdapter(FragmentManager fm,int numOfTabs) {
    super(fm);
    this.numOfTabs=numOfTabs;
}

@Override
public Fragment getItem(int position) {
    switch (position)
    {
        case Symptoms:
           symptomsTabFragment = new SymptomsTabFragment();
            return symptomsTabFragment;

        case Illness:
             illnessTabFragment= new IllnessTabFragment();
            return illnessTabFragment;


    }
    return null;
}


  @Override
  public int getCount() {
    return numOfTabs;
  }
}

这是第一个标签片段的代码

 public class SymptomsTabFragment extends Fragment {

@Bind(R.id.recycler_view_notificationsSymptoms)
RecyclerView mRecyclerView_notificationSymptoms;


NetworkStatus mNetworkStatus = null;

static AlertDialog mShowDialog = null;

Button mButton_right;

ArrayList<NotificationSymptomdata> notificationSymptoms = null;
ArrayList<NotificationSymptomdata> notificationSymptomid = null;
ArrayList<String> notificationSettingID = null;
ArrayList<NotificationSymptomdata> isNotification = null;


public SymptomsTabFragment() {
    // Required empty public constructor
}


public static SymptomsTabFragment newInstance() {
    SymptomsTabFragment fragment = new SymptomsTabFragment();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.e("stb", "oncreate");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_symptoms_tab, container, false);
    ButterKnife.bind(this, rootView);

    mButton_right = (Button) getActivity().findViewById(R.id.Button_right);


    Log.e("stb", "oncreateview");


    Toolbar.LayoutParams params = new Toolbar.LayoutParams(marginInDp(80), marginInDp(50));
    params.gravity = Gravity.RIGHT;
    params.setMargins(0, 0, marginInDp(20), 0);
    mButton_right.setLayoutParams(params);
    mButton_right.setBackgroundResource(0);
    mButton_right.setTag(1);
    mButton_right.setVisibility(View.VISIBLE);
    mButton_right.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final int status = (Integer) v.getTag();
            if (status == 1) {
                mButton_right.setText("Select All");
                v.setTag(0);

            } else {

                mButton_right.setText("DeSelect All");
                v.setTag(1);
            }

            if (mButton_right.getText().toString().equalsIgnoreCase("Select All")) {


                ArrayList<UpdateNotificationRequestData> Updatenoti;

                Log.e("stb", "onclick");

                UpdateNotificationsRequestModel requestModel = new UpdateNotificationsRequestModel();
                requestModel.setUserID(AppPreferences.readString(getActivity(), AppPreferenceNames.sUserid, ""));
                requestModel.setAppVersion(CommonUtils.APP_VERSION);
                requestModel.setDeviceInfo(CommonUtils.DeviceInfo);
                requestModel.setDeviceTypeID(CommonUtils.DEVICE_TYPE_ID);

                Updatenoti = new ArrayList<UpdateNotificationRequestData>();
                UpdateNotificationRequestData requestData;
                for (int i = 0; i < notificationSymptoms.size(); i++) {
                    requestData = new UpdateNotificationRequestData();
                    requestData.setIsNotification("1");
                    requestData.setNotificationSettingID(notificationSymptoms.get(i).getNotificationSettingID());
                    Updatenoti.add(requestData);
                }

                requestModel.setUpdateNotification(Updatenoti);

                if (mNetworkStatus.isNetWorkAvailable(getActivity()) == true) {
                    update_notifications(requestModel);

                } else {
                    CommonUtils.showAlertDialog(getActivity(), "No Network Available. Please connect to network");
                }

            } else if (mButton_right.getText().toString().equalsIgnoreCase("DeSelect All")) {

                ArrayList<UpdateNotificationRequestData> Updatenoti;

                Log.e("stb", "onclick");

                UpdateNotificationsRequestModel requestModel = new UpdateNotificationsRequestModel();
                requestModel.setUserID(AppPreferences.readString(getActivity(), AppPreferenceNames.sUserid, ""));
                requestModel.setAppVersion(CommonUtils.APP_VERSION);
                requestModel.setDeviceInfo(CommonUtils.DeviceInfo);
                requestModel.setDeviceTypeID(CommonUtils.DEVICE_TYPE_ID);

                Updatenoti = new ArrayList<UpdateNotificationRequestData>();
                UpdateNotificationRequestData requestData;
                for (int i = 0; i < notificationSymptoms.size(); i++) {
                    requestData = new UpdateNotificationRequestData();
                    requestData.setIsNotification("0");
                    requestData.setNotificationSettingID(notificationSymptoms.get(i).getNotificationSettingID());
                    Updatenoti.add(requestData);
                }

                requestModel.setUpdateNotification(Updatenoti);

                if (mNetworkStatus.isNetWorkAvailable(getActivity()) == true) {
                    update_notifications(requestModel);
                } else {
                    CommonUtils.showAlertDialog(getActivity(), "No Network Available. Please connect to network");
                }


            }


        }
    });


    notificationSymptoms = new ArrayList<>();
    notificationSymptomid = new ArrayList<>();
    notificationSettingID = new ArrayList<>();
    isNotification = new ArrayList<>();

    mNetworkStatus = new NetworkStatus(getActivity());


    // Inflate the layout for this fragment
    return rootView;
}


/**
 * Used to set margin value programmatically
 *
 * @param sizeInDP
 * @return
 */
private int marginInDp(int sizeInDP) {
    int marginInDp = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, sizeInDP, getResources()
                    .getDisplayMetrics());
    return marginInDp;
}


/**
 * Update the notification settings
 */
public void update_notifications(UpdateNotificationsRequestModel object) {
    /**
     * Start the progress Bar.
     */
    CommonUtils.show_progressbar(getActivity());

    /**
     * call api
     */

    Call<UpdateNotificationsResponseModel> responsecall = VirusApplication.getRestClient().getAPIService().updateNotifications(object);
    responsecall.enqueue(new Callback<UpdateNotificationsResponseModel>() {
        @Override
        public void onResponse(Response<UpdateNotificationsResponseModel> response, Retrofit retrofit) {

            /**
             * Stop the progress Bar
             */
            CommonUtils.stop_progressbar();

            if (response.isSuccess()) {
                //Server Success
                UpdateNotificationsResponseModel responseModel = response.body();
                if (responseModel.getErrorCode().equalsIgnoreCase("0")) {
                    //Data Success
                    Log.e("nf", "data success");

                    CommonUtils.showAlertDialog(getActivity(), responseModel.getMessage());

                   // getNotificationSettings();


                } else {
                    CommonUtils.showAlertDialog(getActivity(), responseModel.getMessage());

                   // getNotificationSettings();


                }
            } else {

                CommonUtils.showAlertDialog(getActivity(), "Server Error");

               // getNotificationSettings();

            }

        }

        @Override
        public void onFailure(Throwable t) {

            /**
             * Stop the progress Bar
             */
            CommonUtils.stop_progressbar();


        }
    });


}

@Override
public void onResume() {
    super.onResume();

    Log.e("stb", "onresume");

  /*  r = new MyReceiver();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(r,
            new IntentFilter("TAG_REFRESH"));
        */
       /**
      * Downloads mychildren details.
     */
       if (mNetworkStatus.isNetWorkAvailable(getActivity()) == true) {
          getNotificationSettings();
       } else {
         CommonUtils.showAlertDialog(getActivity(),                      getString(R.string.network_unavailable));
    }




}


/**
 * Get Notification Settings
 */
public void getNotificationSettings() {

    //hit the getnotifications API to fetch the notification details

    CommonUtils.show_progressbar(getActivity());

    /**
     * Calls WebAPI
     */

    Call<NotificationsModel> notificationsModelCall = VirusApplication.getRestClient().getAPIService().notifications(getNotificationsrequest());
    notificationsModelCall.enqueue(new Callback<NotificationsModel>() {
        @Override
        public void onResponse(Response<NotificationsModel> response, Retrofit retrofit) {

            /**
             * Stops the Progresss bar
             */
            CommonUtils.stop_progressbar();

            if (response.isSuccess()) {//Server Success

                NotificationsModel notificationsModel = response.body();
                if (notificationsModel.getErrorCode().equalsIgnoreCase("0")) {// Data Success

                    int i = 1;
                    for (NotificationSymptomdata nsymptomsData : notificationsModel.getNotificationSymptomdata()) {
                        notificationSymptoms.add(nsymptomsData);
                        //  aSymptomsID.add(symptomsData.getSymptomID());

                       /* if (edit_child_symptoms_id == symptomsData.getSymptomID()) {
                            illness_selection_position = i;
                        }*/

                        i++;
                    }


                    Log.e("noti", "Symptoms ArraySize-->" + notificationSymptoms.size());

                    if (notificationSymptoms.size() != 0) {
                        NotificationsAdapter notificationsAdapter = new NotificationsAdapter(getActivity(), notificationSymptoms);
                        mRecyclerView_notificationSymptoms.setAdapter(notificationsAdapter);
                        notificationsAdapter.notifyDataSetChanged();
                        LinearLayoutManager SymptomsLayoutManager = new LinearLayoutManager(getActivity());
                        mRecyclerView_notificationSymptoms.setLayoutManager(SymptomsLayoutManager);
                    }

                    for(int j=0;j<notificationSymptoms.size();j++)
                    {
                        if (notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("true"))
                        {
                            mButton_right.setText("DeSelect All");
                        }
                        else
                        if(notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("false"))
                        {
                            mButton_right.setText("Select All");
                        }
                        else
                        if (notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("true") || (notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("false")))
                        {
                            Log.e("ins","coming  here");

                            mButton_right.setText("Select All");
                        }
                    }


                } else { // Data Failure
    //                        CommonUtils.makeToast(AddLogActivity.this,      illnessCategory.getMessage());
                    /**
                     * Stops the Progresss bar
                     */
                    CommonUtils.stop_progressbar();
                    Log.e("noti", "data failure");
                }
            } else {// Server Failure
 //                    CommonUtils.makeToast(AddLogActivity.this, "Server Error");
                /**
                 * Stops the Progresss bar
                 */
                CommonUtils.stop_progressbar();
                Log.e("noti", "server failure");
            }
        }


        @Override
        public void onFailure(Throwable t) {

            /**
             * Stops the Progresss bar
             */
            CommonUtils.stop_progressbar();
            Log.e("noti", "retrofit failure");

        }
    });


}

/**
 * Request values to Get notifications.
 *
 * @return map object
 */
public Map<String, Object> getNotificationsrequest() {

    Map<String, Object> getChildrenValues = new HashMap<>();
    getChildrenValues.put("appVersion", CommonUtils.APP_VERSION);
    getChildrenValues.put("deviceTypeID", CommonUtils.DEVICE_TYPE_ID);
    getChildrenValues.put("deviceInfo", CommonUtils.DeviceInfo);
    getChildrenValues.put("userID", AppPreferences.readString(getActivity(), AppPreferenceNames.sUserid, ""));

    return getChildrenValues;

   }
 }

我面临的问题是根据按钮的文本点击mButton_right,即&#34;选择全部&#34;或者&#34;取消选择所有&#34;我应该更新我片段中的内容。选择相应按钮的Web服务调用正在选项卡内正确进行。

但是每当更新后收到新数据时,我都无法使用新的传入数据刷新选项卡片段。 如何以及在何处调用服务以获取更新的数据并在单击按钮时刷新选项卡片段?请帮忙!

1 个答案:

答案 0 :(得分:0)

为了刷新Fragment TabLayout内的Fragment数据,您应该创建一个函数,只要您更改 // In activity final Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.frame_container); if (currentFragment instanceof MainTabFragment) { ((MainTabFragment) currentFragment).doRefresh(); } 就可以调用该函数,并且可以刷新其中的数据。有关详情,请参阅:

    package agent;

    import java.util.regex.Pattern;
    import java.awt.List;
    import java.util.concurrent.TimeUnit;
    import org.junit.*;
    import static org.junit.Assert.*;
    import static org.hamcrest.CoreMatchers.*;
    import org.openqa.selenium.*;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.FluentWait;
    import org.openqa.selenium.support.ui.Select;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class TaxRegistration {
      private static final TaxRegistration Driver = null;
    private WebDriver driver;
    WebDriverWait wait;
      private String baseUrl;
      private boolean acceptNextAlert = true;
      private StringBuffer verificationErrors = new StringBuffer();
      private By tagText = By.id("AddressDetails_City");


      @Before
      public void setUp() throws Exception {
        System.setProperty("webdriver.chrome.driver","E:/Vignesh/Automation/New folder (2)/chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 5);
        baseUrl = "http://govreports.com.au/dev/taxagentt1.html";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
      }

      @Test
      public void testBASFormWebdriver() throws Exception {
          driver.get("http://govreports.com.au/dev/taxagentt1.html");
            driver.findElement(By.id("BAS")).click();
            Thread.sleep(1000);
            driver.findElement(By.id("TFND")).click();
            Thread.sleep(1000);
            driver.findElement(By.id("PAYG")).click();
            Thread.sleep(1000);
            driver.findElement(By.id("TPAR")).click();
            Thread.sleep(1000);
            //((JavascriptExecutor)driver).executeScript("scroll(0,2000)");
            Thread.sleep(1000);
            driver.findElement(By.id("OUT")).click();
            Thread.sleep(1000);
            //((JavascriptExecutor)driver).executeScript("scroll(0,1000)");
            Thread.sleep(1000);
            driver.findElement(By.id("BUL")).click();
            Thread.sleep(1000);
            driver.findElement(By.id("NUL")).click();
            Thread.sleep(1000);
            driver.findElement(By.id("IUL")).click();
            Thread.sleep(1000);
            //((JavascriptExecutor)driver).executeScript("scroll(0,6000)");
            Thread.sleep(1000);
            driver.findElement(By.cssSelector("a.btn.btn-default > b")).click();
            Thread.sleep(2000);
            driver.findElement(By.id("AgentNo")).clear();
            driver.findElement(By.id("AgentNo")).sendKeys("78301003");
            driver.findElement(By.id("AgentName")).clear();
            driver.findElement(By.id("AgentName")).sendKeys("Vignesh Check");
            driver.findElement(By.id("SendQuote")).click();
            Thread.sleep(2000);
            driver.findElement(By.xpath("(//input[@name='plancodeTPAR'])[2]")).click();
            driver.findElement(By.xpath("(//input[@value='1'])[9]")).clear();
            driver.findElement(By.xpath("(//input[@value='1'])[9]")).sendKeys("2");
            driver.findElement(By.id("Proceed")).click();
            Thread.sleep(5000);
            driver.findElement(By.id("ABN")).click();
            driver.findElement(By.id("ABN")).clear();
            driver.findElement(By.id("ABN")).sendKeys("19087046080");
            driver.findElement(By.id("BusinessName")).click();
            Thread.sleep(2000);
            driver.findElement(By.id("Username")).clear();
            driver.findElement(By.id("Username")).sendKeys("vikireg02@govreports.com.au");
            driver.findElement(By.id("Password")).clear();
            driver.findElement(By.id("Password")).sendKeys("Viki2607");
            driver.findElement(By.id("ConfirmPassword")).clear();
            driver.findElement(By.id("ConfirmPassword")).sendKeys("Viki2607");
            String capColorDropDown = "//span[@role='listbox']";
            driver.findElement(By.xpath(capColorDropDown)).click();
            String itemName = "Orange";
            String listId = "color_listbox";
            Thread.sleep(2000);
            String xpathForItem = "//ul[@id='Salutation_listbox']/li[@class='k-item' and text()='Mr']";
            driver.findElement(By.xpath(xpathForItem)).click();
            driver.findElement(By.id("FirstName")).click();
            driver.findElement(By.id("FirstName")).clear();
            driver.findElement(By.id("FirstName")).sendKeys("Vignesh");
            driver.findElement(By.id("LastName")).click();
            driver.findElement(By.id("LastName")).clear();
            driver.findElement(By.id("LastName")).sendKeys("Ks");
            driver.findElement(By.id("TelephoneAreaCode")).click();
            driver.findElement(By.id("TelephoneAreaCode")).clear();
            driver.findElement(By.id("TelephoneAreaCode")).sendKeys("02");
            driver.findElement(By.id("TelephoneNumber")).click();
            driver.findElement(By.id("TelephoneNumber")).clear();
            driver.findElement(By.id("TelephoneNumber")).sendKeys("2356895623");
            driver.findElement(By.id("AddressDetails_Line1")).clear();
            driver.findElement(By.id("AddressDetails_Line1")).sendKeys("Walker Street");