重用碎片对象会导致空指针异常

时间:2013-10-09 18:08:56

标签: java android android-fragments

在活动布局中,我使用的是android.support.v4.widget.DrawerLayout。当用户从抽屉列表视图或菜单中选择选项时,我将用片段替换主视图。

在某些时候,我不需要替换片段,而是需要更改现在布局中存在的片段中的数据。

ChannelFragment channelFragment = new ChannelFragment();
Fragment favsFragment = new FavorFragment();
Fragment homeFragment = new HomeFragment();`
@Override
public void onCreate(Bundle savedInstanceState) {

 setContentView(R.layout.activity_base);
showFragment(channelFragment);

}

@Override
public void onSelectItem(int position) {
if(channels!=null){  //channels -- List<Channel>
showFragment(channelFragment);
//This will change the TextView text in channelFragment.
channelFragment.changeChannelTitle(channels.get(position).getName());
}
public void showFragment(Fragment fragment){
     FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
     ft.replace(R.id.content_frame, fragment);
     ft.commit();
}
}

ChannelFragment.java

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

    View rootView = inflater.inflate(R.layout.fragment_channel, container,
            false);
    programList = (ListView)rootView.findViewById(R.id.lvPrograms);
    tvChannel = (TextView)rootView.findViewById(R.id.tvChannelName);
    return rootView;
}



public void changeChannelTitle(final String title){
//i tried to set tvChannel..setText(title); it leads to the same exception
    ((TextView)getView().findViewById(R.id.tvChannelName)).setText(title);

}

fragment_channel.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" >

<TextView
    android:id="@+id/tvChannelName"
    android:layout_width="wrap_content"``
    android:layout_height="wrap_content"
    android:text="Channels Page"
    android:layout_gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
     />

<ListView
    android:id="@+id/lvPrograms"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

activity_base.xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

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

<ListView
    android:id="@+id/listview_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#111"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp" />

</android.support.v4.widget.DrawerLayout>
  • 场景1: 我在onCreate中加载channelFrgment并尝试更改文本。它发生了变化,没有问题发生。

  • 场景2: 我正在onCreate中加载home片段。当用户从listview中选择一些选项时,我用通道片段替换了主片段,并尝试更改文本。在这种情况下抛出Null指针异常。我已经显示已经初始化的片段并尝试了内容。但是异常告诉ChannelsFragment中存在的TextView为空。

  • 场景3: channelFragment(onCreate) - &gt; Home Fragment - &gt; ChannelFragment;现在我试图更改textview的文本,发生了同样的异常。

我该如何处理这种情况?

Logcat输出

10-09 23:46:49.918: E/AndroidRuntime(21743): FATAL EXCEPTION: main
10-09 23:46:49.918: E/AndroidRuntime(21743): java.lang.NullPointerException
10-09 23:46:49.918: E/AndroidRuntime(21743):    at                             com.ps.tvprograms.fragments.ChannelFragment.changeChannelTitle(ChannelFragment.java:53)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at     com.ps.tvprograms.AppMainActivity.onSelectItem(AppMainActivity.java:72)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at com.ps.library.activities.menuimagesdynamic.DrawerActivity$DrawerItemClickListener.onItemClick(DrawerActivity.java:128)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.widget.AbsListView$1.run(AbsListView.java:3571)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.os.Handler.handleCallback(Handler.java:725)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.os.Looper.loop(Looper.java:153)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at android.app.ActivityThread.main(ActivityThread.java:5297)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at java.lang.reflect.Method.invokeNative(Native Method)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at java.lang.reflect.Method.invoke(Method.java:511)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
10-09 23:46:49.918: E/AndroidRuntime(21743):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

您的问题是您正在为FragmentTransaction使用“replace()”。当调用ft.replace()时,它实际上会分离当前片段并将其替换为下一个片段。当此片段被销毁时,与其关联的任何视图都将再次设置为null(在本例中为TextView)。放入下一个片段时,将调用“onCreateView()”方法。

如果您正在寻找替代方案,请考虑在您的FragmentTransaction中使用show()和hide(),以便您的片段保持连接状态,而只是隐藏。

修改

好的,我可能已经意识到实际发生了什么。提交事务后,请直接尝试添加“getSupportFragmentManager()。executePendingTransactions()”。所以它应该如下所示。

public void showFragment(Fragment fragment)
{
   FragmentTransaction ft = getSupportFragmentManager();
   ft.replace(R.id.content_frame, fragment);
   ft.commit();
   getSupportFragmentManager().executePendingTransactions();
}

原始代码不起作用的原因是,当您提交FragmentTransaction时,它不会立即进行更改,只是说它们最终会完成。您的问题出现是因为当您引用TextView时,事务实际上还没有替换您的片段。

希望这会有所帮助。祝你好运!