Viewpager + webservice

时间:2015-11-10 19:21:18

标签: android web-services android-fragments android-viewpager fragment

编辑:我找到了解决方案。

我以错误的方式构建界面。

应该是:

( (IOnResultObtainedListener) adapter.getItem(i)).onResultObtained(response.getCompetition());

而不是:

((IOnResultObtainedListener) CompetitionActivity.this).onResultObtained(response.getCompetition());
        }

我有一个ViewPager,其中包含三个带有列表的片段。我需要用我在网络服务响应时获得的数据填充它们,但我不知道如何通知每个片段。我试图在Activity和Fragments之间实现一个接口,但是我得到了这个错误:

java.lang.ClassCastException:
    com.cuatroochenta.mybets.home.mygames.newGame.CompetitionActivity
    cannot be cast to
    com.cuatroochenta.mybets.home.mygames.newGame.IOnResultObtainedListener

这是我的活动代码:

public class CompetitionActivity extends MyBetsActionBarActivity implements ICompetitionsResponseListener {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
Handler handler;

IOnResultObtainedListener onResultObtainedListener;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Competiciones");
    setSupportActionBar(toolbar);

    handler = new Handler();

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
}

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.search_menu, menu);

    MenuItem searchItem = menu.findItem(R.id.action_search);

    SearchManager searchManager = (SearchManager) this.getSystemService(Context.SEARCH_SERVICE);

    SearchView searchView = null;
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(this.getComponentName()));
    }
    return super.onCreateOptionsMenu(menu);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new PopularsFragment(), "Populares");
    adapter.addFragment(new CategoriesFragment(), "Categorías");
    adapter.addFragment(new NewsFragment(), "Nuevos");
    viewPager.setOffscreenPageLimit(3);
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

private void doRequestCompetitions(){
    if (NetworkUtils.isNetworkAvailable(this)) {
        CompetitionsService competitionsService = new CompetitionsService();
        competitionsService.setServiceUrl(url);
        competitionsService.getCompetitionsAsync(new CompetitionsRequest(user, password), this);
    } else {
        InfoAlertManager.showInfoDialog(this, "Conexión requerida", "Aceptar");
    }
}

@Override
public void onCompetitionsResponse(final CompetitionsResponse response) {
    if (response.getCompetition() != null) {
        Log.d("onCompetitionsResponse", response.getCompetition().toString());

        // HERE IS WHEN I RECEIVE THE RESPONSE AND I SHOULD NOTIFY IT TO THE FRAGMENTS
        handler.post(new Runnable() {
            @Override
            public void run() {
                ((IOnResultObtainedListener) CompetitionActivity.this).onResultObtained(response.getCompetition());
            }
        });
    }
}

@Override
public void onError(ServiceResponseError serviceResponseError) {
    Log.d("ServiceResponseError", serviceResponseError.getMessage());
}

public void setOnResultObtainedListener(IOnResultObtainedListener onResultObtainedListener){
    this.onResultObtainedListener = onResultObtainedListener;
}

}

这是我的一个片段代码:

public class PopularsFragment extends Fragment implements IOnResultObtainedListener {

RecyclerView rvPopular;
CompetitionAdapter mCompetitionAdapter;

public PopularsFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("PopularsFragment", "onCreate");
}

@Override
public void onStart() {
    super.onStart();
    Log.d("MyBets", "PopularsFragment Visible");
}

@Override
public void onResume() {
    super.onResume();
    ((CompetitionActivity)getActivity()).setOnResultObtainedListener(this);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_competitions, container, false);
    rvPopular =  (RecyclerView) rootView.findViewById(R.id.rvCompetitions);
    rvPopular.setLayoutManager(new LinearLayoutManager(getActivity()));
    rvPopular.setHasFixedSize(true);
    return rootView;
}

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

@Override
public void onResultObtained(Competition competition) {
    mCompetitionAdapter = new CompetitionAdapter(getActivity(), competition, 0);
    rvPopular.setAdapter(mCompetitionAdapter);
}

}

有什么想法吗?我搜索过类似的问题,但我找不到任何有用的东西...... 希望你帮帮我。非常感谢!

2 个答案:

答案 0 :(得分:1)

CompetitionActivity实施的界面不是IOnResultObtainedListener,而是ICompetitionsResponseListener。实现IOnResultObtainedListener的是ViewPager下的片段。

ViewPagerAdapter将片段的实例保存为mFragmentList。因此,将其修饰符更改为默认(或公共),您可以从类外部访问它。

final List<Fragment> mFragmentList = new ArrayList<>();

此外,您必须将ViewPagerAdapter实例保存到字段变量而不是本地变量,以便在setupViewPager方法的一侧访问它:

private ViewPagerAdapter pagerAdapter;

private void setupViewPager(ViewPager viewPager) {
    pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    ...
}

然后,而不是这一行:

((IOnResultObtainedListener) CompetitionActivity.this).onResultObtained(response.getCompetition());

放置此代码:

for (Fragment fragment : pagerAdapter.mFragmentList) {
    ((IOnResultObtainedListener) fragment).onResultObtained(response.getCompetition());
}

调用每个片段的侦听器。

答案 1 :(得分:0)

可能最简单的方法是使用开源事件总线,例如Otto