簡體   English   中英

將數據從一個片段發送到另一片段時出錯。 (兩個片段都由一個活動托管)

[英]Error sending data from one fragment to another fragment. ( Both fragments are hosted by one activity)

我在將數據從一個片段發送到另一個片段時遇到麻煩。 我遵循的是android 指南 ,該指南告訴我創建一個接口來與活動和片段進行通信。 我正在使用底部導航切換片段。 無論如何,這是來自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方法兩種方式對其進行初始化,該實例似乎總是為空。 我認為罪魁禍首可能是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,我要將數據從片段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>

讓我知道您是否需要更多信息。 提前致謝 :)

您可以通過如下方式在片段之間傳遞數據:

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上注冊該事件總線之前發布消息,然后在OnDettach中注銷它

 EventBus.getDefault().post(new MessageEvent("My Message));

在片段2中,在OnEvent方法中獲取消息(即使在此片段中,請不要忘記注冊和注銷事件總線)

@Subscribe
public void onEvent(MessageEvent event) {
        this.msg=event.getMsg();
        callTheMethodToDoYourOperation(msg);
}

這是一個基本示例,但是在使用此事件之前,請檢查事件總線,然后在兩個片段中都需要注冊,注銷和訂閱onevent,如果這是一種通信方式,則請使onEvent為空

希望這可以幫助

發生NullPointerException原因是您的Fragment尚未初始化,因此在與Fragment進行交互之前,請確保檢查它是否已初始化且是否可見。

if (f!= null && f.isVisible()) {
   f.displayReceivedData(message);
}

您也可以使用BundleFragment之間傳遞數據。

注意:在發布問題之前,請先了解錯誤,然后嘗試調試錯誤的根本原因。 您一定會自己解決的。

快樂的編碼:)

您將在接收數據的方法上獲得Null指針,該片段實例為null。 最喜歡的f為空。 如果該片段創建一個實例,然后調用.replace

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM