空指针异常调用片段

时间:2016-02-29 18:40:57

标签: android android-fragments fragment

我想通过点击当前片段中的按钮来调用当前片段中的另一个片段。基于我到达的答案calling a fragment from fragment。 我修改后的代码如下:

这是我的主要活动:

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();

    }
}

这是我的一个片段,我试图称之为另一个片段:

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");

        }
    }
}

我实现了界面&在mainactivity中重写,现在我得到一个nullpointer异常如下:

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

有人可以告诉我我做错了吗?

2 个答案:

答案 0 :(得分:1)

您正在从接口调用方法,该接口为null。您应该在另一个类中为回调实现该接口。您还应该在片段外部创建接口以获得更好的结构。

答案 1 :(得分:0)

问题可能是造成的,因为您不会在替补堆叠中放置替换/删除的Fragment,而是调用方法addToBackStack()

  

如果在执行删除片段的事务时未调用addToBackStack(),则在提交事务并且用户无法导航回到该片段时,该片段将被销毁。然而,如果您在删除片段时调用addToBackStack(),则片段将停止,并且如果用户导航回来,将会恢复该片段。

因此,当您尝试使用替换/删除Fragment的方法时,您拥有NullPointerException。这是link