在不使用活动的情况下在两个片段之间传递字符串 [英] Pass String between two fragments without using an activity

查看:96
本文介绍了在不使用活动的情况下在两个片段之间传递字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在NewDateFragment和NewEventFrament之间传递字符串curDate,我看到很多人都在使用Bundle,但是使用它们我仍然有NullPointerException。

I need to pass the string curDate between NewDateFragment and NewEventFrament, i see many peoples using Bundle, but using these i still having NullPointerException.

我将CalendarView转换为

I transform the CalendarView to one string named curDate.

public class NewDateFragment extends Fragment {

public String curDate;

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

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

    View view = inflater.inflate(R.layout.fragment_newdate,
            container, false);


    CalendarView calendar = (CalendarView) view.findViewById(R.id.calendarView);

    //sets the listener to be notified upon selected date change.
    calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
            curDate = day + "/" + month + "/" + year;

            NewDateFragment fragment = new NewDateFragment();
            Bundle bundle = new Bundle();
            bundle.putString("date", curDate);
            fragment.setArguments(bundle);

            Log.d("Current Date:", curDate);
        }
    });

}

public class NewEventFragment extends Fragment {

     // relative code inside onCreateView
     Bundle b = getActivity().getIntent().getExtras();
        final String dDate = b.getString("date");
}

我的Logcat:

10-08 18:34:49.036 10293-10293 / com.org.feedme.cisvmeeting.activities W / dalvikvm:threadid = 1:线程以未捕获的异常退出(group = 0x41640d88)
10-08 18:34:49.056 10293-10293 / com.org.feedme.cisvmeeting.activities E / AndroidRuntime致命异常:主
流程:com.org.feedme.cisvmeeting.activities,PID:10293
java.lang.NullPointerException
在com.org.feedme.fragments.NewEventFragment.attemptCreate(NewEventFragment.java:116)
在com.org.feedme.fragments.NewEventFragment $ 1.onClick( NewEventFragment.java:61)
在android.view.View.performClick(View.java:4569)
在android.view.View $ PerformClick.run(View.java:18570)
在android.os.Handler.handleCallback(Handler.java:743)
在android.os.Handler.dispatchMessage(Handler.java:99)
在android.os。 Looper.loop(Looper.java:136)
在android.app.ActivityThread.main(ActivityThread.java:5212)
在java.lang.reflect.Method.invokeNative(本机方法)
在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)
在java.lang.reflect.Method.invoke(Method.java:515)
android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)

10-08 18:34:49.036 10293-10293/com.org.feedme.cisvmeeting.activities W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41640d88) 10-08 18:34:49.056 10293-10293/com.org.feedme.cisvmeeting.activities E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.org.feedme.cisvmeeting.activities, PID: 10293 java.lang.NullPointerException at com.org.feedme.fragments.NewEventFragment.attemptCreate(NewEventFragment.java:116) at com.org.feedme.fragments.NewEventFragment$1.onClick(NewEventFragment.java:61) at android.view.View.performClick(View.java:4569) at android.view.View$PerformClick.run(View.java:18570) at android.os.Handler.handleCallback(Handler.java:743) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5212) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602) at dalvik.system.NativeStart.main(Native Method)

感谢所有帮助!

推荐答案

给定答案的替代方案是使用事件。如果您真的想避免耦合代码,这意味着摆脱类之间不必要的依赖,那么在Activity中使用变量不是一个好主意。这是我的建议:

An alternative to the given answer would be to use Events. If you really want to avoid coupling your code - meaning getting rid of unnecessary dependence between classes, having a variable inside your Activity is not a good idea. Here is my suggestion:


  • 将EventBus库添加到Gradle文件中:

  • Add EventBus library to your Gradle file:

 compile 'de.greenrobot:eventbus:2.4.0'


  • 创建一个简单的普通旧Java类来表示您的事件:

  • Create a simple plain old java class to represent your event:

    public class CalendarDateSelectedEvent{
       private String currentDate;
    
       public CalendarDateSelectedEvent(String date){
    
          this.currentDate = date;
       }
    
       public String getCurrentDate(){
    
          return currentDate;
       }
    }
    


  • 在第一个片段中,日期是选择后,您可以在选择日期后立即将事件发布到第二个片段,例如:

  • Inside your first fragment where a date is picked, you can post an event to your second fragment as soon as the date is selected like this:

    //somewhere when  a date is selected
    onSelectedDayChanged(String dateSelected){
       EventBus.getDefault().post(new CalendarDateSelectedEvent(dateSelected));
    }
    


  • 最后,在第二个片段中,执行以下操作:

  • Finally, inside your second fragment, do the following:

    //could be inside onCreate(Bundle savedInstanceState) method
    @Override
    public void onCreate(Bundle saveInstanceState){
       //......
       EventBus.getDefault().register(this);
    }
    
    @Override
    public void onDestroy(){
       super.onDestroy();
       EventBus.getDefault().unregister(this);
    }
    
    //very important piece here to complete the job
    public void onEvent(CalenderDateSelectedEvent event){
    
        String currentDate = event.getCurrentDate();
        //you can now set this date to view.
    }
    


  • 您可能会问,为什么所有的人都忙于拥有所有这些代码;但是答案很简单:活动不必真的知道两个片段中正在发生什么。您已经消除了代码中不必要的耦合。

    At this point, you might be asking, why all the hussle to have all these code; but the answer is simple: the activity doesn't have to really know what is happening in either fragments. You have eliminated unnecessary coupling in your code.

    如果您将活动更改为其他操作,则无需更改片段代码。

    If you ever change the activity to do something else, you won't have to change the fragment code.

    我希望这可以帮助您了解片段之间通信的两种方法之间的区别!

    I hope this helps you see the difference between the two approaches to communicating between fragments!

    第一种方法(您接受的答案涉及3个参与方,而第二种方法仅涉及2个参与方)。

    The first approach (the answer you accepted, involves 3 parties while the second approach involves only 2 parties). It is up to you to choose.

    享受!

    这篇关于在不使用活动的情况下在两个片段之间传递字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆