尝试调用虚方法会导致空指针异常

时间:2015-12-18 06:27:41

标签: android android-fragments nullpointerexception

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import umd.frenchpronunciationapp.dummy.DummyContent;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Large screen devices (such as tablets) are supported by replacing the ListView
 * with a GridView.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
 * interface.
 */
public class FragmentList1 extends Fragment implements AbsListView.OnItemClickListener{

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    TextView text1;
    private Button button1 = (Button) getView().findViewById(R.id.male);
    private Button button2 = (Button) getView().findViewById(R.id.female);
    ArrayList <String> phrases = new ArrayList<String> ();

    private OnFragmentInteractionListener mListener;

    /**
     * The fragment's ListView/GridView.
     */
    private AbsListView mListView;

    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private ListAdapter mAdapter;

    // TODO: Rename and change types of parameters
    public static FragmentList1 newInstance(String param1, String param2) {
        FragmentList1 fragment = new FragmentList1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public FragmentList1() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // TODO: Change Adapter to display your content
        mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
                android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);


        addListenerOnButtonMale();
        addListenerOnButtonFemale();

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item, container, false);

        // Set the adapter
        mListView = (AbsListView) view.findViewById(android.R.id.list);
        ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

        // Set OnItemClickListener so we can be notified on item clicks
        mListView.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public void readInPhrases () throws IOException
    {
        String str;

        InputStream myStream = getResources().openRawResource(R.raw.phrases);
        BufferedReader reader = new BufferedReader(new InputStreamReader(myStream));
        while ((str = reader.readLine()) != null)
        {
            phrases.add(str);
        }


    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
            mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
        }
        text1 = (TextView) getView ().findViewById (R.id.phrase);


        try {
            readInPhrases();

        }
        catch (IOException ex)
        {
            // catches overidden error ioexecption
        }


        MediaPlayer mp1 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g1));
        MediaPlayer mp2 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g2));
        MediaPlayer mp3 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g3));
        MediaPlayer mp4 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g4));
        MediaPlayer mp5 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g5));
        MediaPlayer mp6 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g6));
        MediaPlayer mp7 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g7));
        MediaPlayer mp8 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g8));
        MediaPlayer mp9 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g9));
        MediaPlayer mp10 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g10));
        MediaPlayer mp11 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g11));
        MediaPlayer mp12 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g12));



        switch (position){
            default:
            case 0:
                text1.setText (phrases.get(0));
                // to incorperate male voice, do this and have male and female buttons
                // and a variable that holds true or false if button was pressed
                //if (male == true)
                mp1.start();
                //else
                //mp... .start ();
                break;
            case 1:
                text1.setText (phrases.get (1));
                mp2.start ();
                break;
            case 2:
                text1.setText (phrases.get (2));
                mp3.start ();
                break;
            case 3:
                text1.setText (phrases.get (3));
                mp4.start ();
                break;
            case 4:
                text1.setText (phrases.get (4));
                mp5.start ();
                break;
            case 5:
                text1.setText (phrases.get (5));
                mp6.start ();
                break;
            case 6:
                text1.setText (phrases.get (6));
                mp7.start ();
                break;
            case 7:
                text1.setText (phrases.get (7));
                mp8.start ();
                break;
            case 8:
                text1.setText (phrases.get (8));
                mp9.start ();
                break;
            case 9:
                text1.setText (phrases.get (9));
                mp10.start ();
                break;
            case 10:
                text1.setText (phrases.get (10));
                mp11.start ();
                break;
            case 11:
                text1.setText (phrases.get (11));
                mp12.start ();
                break;
        }
    }

    public void addListenerOnButtonMale ()
    {

        //male.setBackgroundResource((R.drawable.malelogo));
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Perform action on click
            }
        });
    }

    public void addListenerOnButtonFemale ()
    {

        //female.setBackgroundResource((R.drawable.femalelogo));


        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                MediaPlayer mp1 = MediaPlayer.create(getActivity().getApplicationContext(), (R.raw.g1));
                mp1.start();

            }
        });
    }
    /**
     * The default content for this Fragment has a TextView that is shown when
     * the list is empty. If you would like to change the text, call this method
     * to supply the text it should use.
     */
    public void setEmptyText(CharSequence emptyText) {
        View emptyView = mListView.getEmptyView();

        if (emptyView instanceof TextView) {
            ((TextView) emptyView).setText(emptyText);
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(String id);
    }

}

addListenerOnButtonMale();方法中添加onCreate()会导致我的应用崩溃。我四处寻找可以帮助NullPointerException的答案,但他们都表示我需要在调用方法之前声明button,这对任何事情都没有帮助。

1 个答案:

答案 0 :(得分:1)

您的onCreate()

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

    // TODO: Change Adapter to display your content
    mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);


    addListenerOnButtonMale();
    addListenerOnButtonFemale();

}

您的addListenerOnButtonMale()

public void addListenerOnButtonMale ()
{

    //male.setBackgroundResource((R.drawable.malelogo));
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            // Perform action on click
        }
    });
}

检查您的onCreate() ...您尚未初始化button1 ..这就是您获得NullPoitnerException的原因。

addListenerOnButtonMale();

中删除addListenerOnButtonFemale();onCreate();

修改您的onCreateView(),如下所示:

首先通过查找引用来初始化,然后调用您的方法:

public void onCreateView(){
   View view = inflater.inflate(R.layout.fragment_item, container, false);

    // Set the adapter
    mListView = (AbsListView) view.findViewById(android.R.id.list);
    ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

    // Set OnItemClickListener so we can be notified on item clicks
    mListView.setOnItemClickListener(this);

    button1 = (Button) view.findViewById(R.id.*button1*);// place id of your button1.

    button2 = (Button) view.findViewById(R.id.*button2*);// place id of your button2.

    addListenerOnButtonMale();
    addListenerOnButtonFemale();

    return view;
}