将数据从一个片段发送到另一个片段时出错。 (两个片段都由一个活动托管)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数据从一个片段发送到另一个片段时出错。 (两个片段都由一个活动托管)相关的知识,希望对你有一定的参考价值。
我正在麻烦地将数据从一个片段发送到另一个片段。我正在关注android guideline,它告诉我创建一个与活动和片段进行通信的接口。我正在使用底部导航切换片段。无论如何,这是android studio的错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.makkhay.cameratranslate.Favorite.displayReceivedData(java.lang.String)' on a null object reference
at com.example.makkhay.cameratranslate.HomeActivity.sendData(HomeActivity.java:143)
at com.example.makkhay.cameratranslate.HomeFragment$2.onClick(HomeFragment.java:162)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
出于某种原因,即使在初始化之后,我的片段也总是为空。我尝试了两种方式初始化它,onCreate方法和sendData方法,实例似乎总是为null。我认为主要的罪魁祸首可能是DrawerLayout。因为它是父xml,还有另一个名为“app_bar_home.xml”的xml;使用底部导航托管两个片段,新创建的实例始终为null
这是我的主要活动,它包含两个片段HomeActivity.java
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,HomeFragment.SendMessage {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new HomeFragment();
break;
case R.id.navigation_favorite:
selectedFragment = new Favorite();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.app_bar,
selectedFragment).commit();
return true;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.app_bar,
new HomeFragment()).commit();
}
}
@Override
public void sendData(String message) {
Favorite f = (Favorite) getSupportFragmentManager().findFragmentById(R.id.favFragment);
f.displayReceivedData(message);
}
}
这是我的活动activity_home.xml的xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
android:id="@+id/app_bar"
layout="@layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_home"
app:menu="@menu/activity_home_drawer" />
</android.support.v4.widget.DrawerLayout>
这是app_bar_home.xml,它也是活动的一部分
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
app:layout_collapseMode="pin"
android:id="@+id/toolbar"
/>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
app:layout_constraintBottom_toBottomOf="parent"
android:background="#000"
app:itemIconTint="@color/color_selector"
app:itemTextColor="@color/color_selector"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/navigation" />
</android.support.constraint.ConstraintLayout>
这是片段1,我想从中将数据发送到另一个片段。 HomeFragment.java
public class HomeFragment extends Fragment implements View.OnClickListener{
SendMessage SM;
private Button clearButton, favButton, shareButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
favButton = view.findViewById(R.id.favButton);
favButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SM.sendData(" test");
}
});
}
interface SendMessage {
void sendData(String message);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
HomeFragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/homeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
app:layout_collapseMode="pin" />
</android.support.design.widget.AppBarLayout>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="6dp"
android:layout_marginEnd="6dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginStart="6dp"
android:layout_marginTop="56dp"
android:background="@drawable/card_shadow"
android:divider="?android:dividerHorizontal"
android:paddingTop="6dp"
android:paddingBottom="6dp"
android:showDividers="middle">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingBottom="16dp"
android:gravity="right"
android:orientation="vertical">
<Button
android:id="@+id/favButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="4dp"
android:background="@drawable/ic_favorite_black_12dp"
/>
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
最后这里是第二个片段,我想收到数据Favorite.java
public class Favorite extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_favorite, container, false);
favText = v.findViewById(R.id.tv_recycler_item_1);
return v;
}
protected void displayReceivedData(String message)
{
Toast.makeText(getContext(),"rec:" + message,Toast.LENGTH_SHORT).show();
}
}
fragment_favorite.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/favFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Favorite">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar_scrolling"
android:layout_width="match_parent"
android:layout_height="180dp"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:src="@drawable/bg_red" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/Widget.AppCompat.PopupMenu.Overflow" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<TextView
android:id="@+id/txtData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="548dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/recycler_view_recycler_view"
app:layout_constraintStart_toStartOf="parent" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="382dp"
android:layout_marginEnd="344dp"
android:layout_marginRight="344dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
</android.support.design.widget.CoordinatorLayout>
如果您需要更多信息,请告诉我。提前致谢 :)
你可以通过在bundle中作为参数来传递片段之间的数据,如下所示:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
对于检索,您可以执行以下操作
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key);
}
在我看来,最好的沟通方式是在Activity-fragment,fragment-fragment,Activity-Activty之间使用EventBus,非常简单,不那么复杂
这是一个示例创建一个你想要共享的模型,所以这里是发送字符串的模型声明字符串变量使用构造函数和getter来设置和获取消息
public MessageEvent(String Message)
{
this.msg=msg;
}
public String getMsg() {
return msg;}
现在在你的片段1中,在OnAttach上注册eventbus之前发布消息并在OnDettach中注销它
EventBus.getDefault().post(new MessageEvent("My Message));
在Fragment 2中获取OnEvent方法中的消息(即使在这个片段中也不要忘记注册和取消注册Event Bus)
@Subscribe
public void onEvent(MessageEvent event) {
this.msg=event.getMsg();
callTheMethodToDoYourOperation(msg);
}
这是一个基本的例子,但是在使用它之前检查事件总线,而且在你需要注册,注销和订阅onevent的两个片段中,如果这是通信的一种方式让onEvent为空
希望这可以帮助
发生NullPointerException
是因为你的Fragment
尚未初始化,因此在与之交互之前确保你检查它是否初始化和可见。
if (f!= null && f.isVisible()) {
f.displayReceivedData(message);
}
您也可以使用Bundle
在Fragment
之间传递数据。
注意:在发布问题之前了解错误并尝试调试错误的根本原因。你肯定会自己解决它。
快乐编码:)
您正在获取数据的方法上获得Null指针,该片段实例为null。最喜欢的f是null。如果该片段创建一个实例,然后调用.replace
以上是关于将数据从一个片段发送到另一个片段时出错。 (两个片段都由一个活动托管)的主要内容,如果未能解决你的问题,请参考以下文章