简体   繁体   English

从 Activity 传递到 Fragment 的数据返回 null

[英]Data being passed from Activity to Fragment is returning null

I have reviewed multiple solutions to my question, but each attempt results in my android application crashing due to the data being sent returning null.我已经查看了我的问题的多个解决方案,但是由于发送的数据返回 null,每次尝试都会导致我的 android 应用程序崩溃。 I am attempting to send a ArrayList of Strings to a fragment, but when I launch my application I receive the following error.我正在尝试将字符串的 ArrayList 发送到片段,但是当我启动我的应用程序时,我收到以下错误。

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.assignment2, PID: 17719
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.assignment2/com.example.assignment2.MainActivity}: android.view.InflateException: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: android.view.InflateException: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Error inflating class fragment
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getStringArrayList(java.lang.String)' on a null object reference
        at com.example.assignment2.TickerListFragment.onCreateView(TickerListFragment.java:21)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
        at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:386)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:281)
        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:140)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at com.example.assignment2.MainActivity.onCreate(MainActivity.java:18)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
W/System: A resource failed to call close. 

The following is my MainActivity class以下是我的 MainActivity 类


import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> tickers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        tickers = new ArrayList<String>();
        tickers.add("BAC");
        tickers.add("BTC");
        tickers.add("APPL");

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("def", tickers);
        TickerListFragment list = new TickerListFragment();
        list.setArguments(bundle);
        fragmentTransaction.replace(R.id.list_fragment, list).commit();

    }
}

The following is the XML for the main activity class.以下是主要活动类的 XML。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/list_fragment"
        android:name="com.example.assignment2.TickerListFragment"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

The following is the fragment class以下是片段类


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.fragment.app.Fragment;


import java.util.ArrayList;


public class TickerListFragment extends Fragment {
    ArrayList<String> def_tickers;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
        View view = inflater.inflate(R.layout.fragment_tickerlist, container, false);
        def_tickers = this.getArguments().getStringArrayList("def");

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        LinearLayout layout = (LinearLayout) view.findViewById(R.id.list_layout);
    }
}

And the following is the XML for the fragment以下是片段的 XML

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/list_layout"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

    </LinearLayout>

</ScrollView>

If someone could point out my oversight as to why the sent data is being retrieved as null that would be much appreciated.如果有人能指出我对为什么将发送的数据检索为 null 的疏忽,那将不胜感激。

AFAIK when you use <fragment> in xml it is automatically inflated, when the view is inflated, ie setContentView(R.layout.activity_main); AFAIK 当您在 xml 中使用<fragment>时,它会自动膨胀,当视图膨胀时,即setContentView(R.layout.activity_main);

This means the fragment is created before you got the chance to pass in the bundled args.这意味着片段是在您有机会传递捆绑的参数之前创建的。

Back in the day it was standard practice to use a FrameLayout instead like you've stated in your comment.回到过去,就像您在评论中所说的那样,使用FrameLayout是标准做法。 But now it is best to use FragmentContainerView as it respects animations among other things.但现在最好使用FragmentContainerView ,因为它尊重动画等。

<FragmentContainerView
    android:id="@+id/list_fragment"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM