Null Pointer Exception calling fragments [duplicate]

不问归期 提交于 2019-12-12 07:01:58

问题


I want to call another fragment from the current fragment on the click of the button in the current fragment.Based on answers I got here, calling a fragment from fragment. My revised code is as follows :

Here is my Mainactivity :

package com.kibitz4college.k4c;

import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.asd.fragments.RecommendationsFragment;
import com.asd.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.SearchResultsFragment;
import com.asd.fragments.TrendingFragment;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, SearchCoachingFragment.searchbtnclickedlistner {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();





    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();

        if (id == R.id.search_colleges) {
            // Handle the Search Colleges action
            fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();


        }

         else if (id == R.id.search_consultancies) {
            fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();

        }


        else if (id == R.id.search_coaching) {

            fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();


        }

        else if (id == R.id.my_recommendations) {
         fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();

        }

         else if (id == R.id.trending) {

            fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();


        } else if (id == R.id.profile) {

        } else if (id == R.id.logout) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void showresults() {
        FragmentManager fm = getFragmentManager();
         fm.beginTransaction().replace(R.id.content_frame,new SearchResultsFragment()).commit();

    }
}

Here is one of my fragment from which I'm trying to call another :

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.kibitz4college.k4c.R;


public class SearchCoachingFragment extends Fragment {
    Button search_coll_btn;
    searchbtnclickedlistner searchbtnclickedlistner_var;

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

        final View rootview = inflater.inflate(R.layout.fragment_search_coaching, container, false);
        search_coll_btn = (Button) rootview.findViewById(R.id.Search_coaching_btn );
        search_coll_btn.setOnClickListener(new View.OnClickListener() {
            TextView lite=(TextView) rootview.findViewById(R.id.textView3);


            @Override
            public void onClick(View v) {
                searchbtnclickedlistner_var.showresults();
            }
        });

        return rootview;
    }

    public interface searchbtnclickedlistner
    {

        public void showresults();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try{
            searchbtnclickedlistner_var=(searchbtnclickedlistner)context;
        }
        catch(Exception e){
            throw new RuntimeException(context.toString()+ " must implement OnMyFragmentInteractionListener");

        }
    }
}

I've implemented interface & Overridden in the mainactivity, now I get a nullpointer exception as follows:

java.lang.NullPointerException: Attempt to invoke interface method 
void com.asd.fragments.SearchCoachingFragment$searchbtnclickedlistner.showresults() on a null object reference.

can someone please tell me what I'm doing wrong?


回答1:


You are calling a method from the interface and that interface is null. You should implement that interface in another class for the callback. Also you should create the interface outside the fragment for a better structure.




回答2:


The problem could be caused from the fact, you don't put replaced/removed Fragment in the backstack, calling the method addToBackStack().

If you do not call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and will be resumed if the user navigates back.

So when you try to use a method of a replaced/removed Fragment you have NullPointerException. This is the link.



来源:https://stackoverflow.com/questions/35707076/null-pointer-exception-calling-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!