从Fragment获取数据值到主要活动?

时间:2016-04-07 15:26:37

标签: android android-fragments server badge

我正在尝试创建一个通知徽章,例如Whatsapp(Near tabs)但无法获取存储在片段中的数据值,但由于徽章将在主要活动中,我无法获取(通话来自片段的动态值。

以下是代码:

  

LoadJSON代码

private void loadJSONClaim() {
    sp = this.getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    String usr = sp.getString(UserID, "");
    Retrofit retrofitclaim = new Retrofit.Builder()
            .baseUrl("http://ec2-54-191-118-200.us-west-2.compute.amazonaws.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterfaceClaim requestclaim = retrofitclaim.create(RequestInterfaceClaim.class);
    Call<JSONResponseClaim> call = requestclaim.getJSONClaim(usr);
    call.enqueue(new Callback<JSONResponseClaim>() {
        @Override
        public void onResponse(Call<JSONResponseClaim> call, Response<JSONResponseClaim> responseclaim) {

            JSONResponseClaim jsonResponseClaim = responseclaim.body();
            dataclaim = new ArrayList<>(Arrays.asList(jsonResponseClaim.getAndroidClaim()));
            adapterclaim = new DataAdapterClaim(dataclaim);
            mRecyclerViewClaim.setAdapter(adapterclaim);
            eligitem.setText("    Eligible to earn   " + dataclaim.size() + " items");
          /* if(dataclaim.size()==0){
                filldata.setVisibility(View.GONE);
                emptyclaim.setVisibility(View.VISIBLE);
            }
            else{
                emptyclaim.setVisibility(View.GONE);
                filldata.setVisibility(View.VISIBLE);

            }*/
        }

因此,以下代码在Fragment中工作或者在Main活动中调用数据值应该解决问题,我想。

  

MainActivity.java

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    CleverTapAPI ct;

    BadgeView badgeView = new BadgeView(this,tabLayout);
    badgeView.setText("2");
    badgeView.show();

有人可以提供帮助吗?

编辑:精致的问题

1 个答案:

答案 0 :(得分:2)

首先创建一个界面,其中包含您希望发送的任何内容:

public Interface IEventListener{
   public void somMethod(data_type_toSend data)
}

然后在你的片段的类define和构造函数中启动这个接口:

IEventListener myListener;
public YourFragment (IEventListener listener){
     myListener=listener
}

最后让您的活动实现您的界面

public class myActivity extends ... implements **IEventListener**{

然后在你的活动覆盖事件回调中:

 @Override
  public void somMethod(data_type_toSend data){
//what you want to do with sent data to activity
}