Android Студия NullPointerException, вызванная фрагментом транзакции - PullRequest
0 голосов
/ 23 января 2020

Мое приложение перестало работать после добавления фрагментов. В частности, эта функция в MainActivity. java:

 public void setFragment (Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.framelayout,fragment);
        fragmentTransaction.commit();
    }    

, которая затем вызывается внутри onCreate :

setFragment(newsFeedFragment);

newsFeedFragment определяется здесь в MainActivity класс:

NewsFeedFragment newsFeedFragment;

И вот определение NewsFeedFragment

public class NewsFeedFragment extends Fragment {
    Context context;
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context=context;
    }
    // Here we are going to return our layout view
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_newsfeed,container,false);

        return view;
    }
}

Приложение вылетает, и я получаю эту ошибку:
enter image description here

Хотя очевидно, что функция вызывает эту ошибку, я не знаю, какая ее часть в точности вызывает ошибку.
На всякий случай, вот и вся MainActivity. java ,

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.search)
    ImageView search;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.framelayout)
    FrameLayout framelayout;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    @BindView(R.id.bottom_navigation)
    BottomNavigationView bottomNavigation;

    NewsFeedFragment newsFeedFragment;
    NotificationFragment notificationFragment;
    FriendsFragment friendsFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        bottomNavigation.inflateMenu(R.menu.bottom_navigation_main);
        bottomNavigation.setItemBackgroundResource(R.color.colorPrimary);
        bottomNavigation.setItemTextColor(ContextCompat.getColorStateList(bottomNavigation.getContext(),R.color.nav_item_colors));
        bottomNavigation.setItemIconTintList(ContextCompat.getColorStateList(bottomNavigation.getContext(),R.color.nav_item_colors));

        setFragment(newsFeedFragment);
        bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.newsfeed_fragment:
                        setFragment(newsFeedFragment);
                        break;

                    case R.id.profile_fragment:

                        break;

                    case R.id.profile_friends:
                        setFragment(friendsFragment);
                        break;

                    case R.id.profile_notification:
                        setFragment(notificationFragment);
                        break;
                }
                return true;
            }
        });
    }

    public void setFragment (Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.framelayout,fragment);
        fragmentTransaction.commit();
    }
}

Ответы [ 3 ]

2 голосов
/ 23 января 2020
  newsFeedFragment = new NewsFeedFragment();
  setFragment(newsFeedFragment);
2 голосов
/ 23 января 2020

Поскольку newsFeedFragment равно null , инициализируйте фрагмент перед его использованием.

newsFeedFragment=NewsFeedFragment();
setFragment(newsFeedFragment);

Надеюсь, это поможет !!

0 голосов
/ 23 января 2020

newsFeedFragment объявлен, но не определен в вашем классе MainActivity. NullPointerException в основном вызывается, если мы объявляем какой-либо объект, но не определяем этот объект.

NewsFeedFragment newsFeedFragment;////// this is declaration
newsFeedFragment=NewsFeedFragment();////// this is definition of that declared object

теперь после определения вы можете использовать этот объект, где хотите. как

setFragment(newsFeedFragment);
...