目前,我正在开发一个媒体播放器,我希望在音频结束时隐藏一个元素。但当它发生时,应用程序会崩溃,并出现以下错误:Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference。检查我的当前代码:
meplayer.java文件

package etes.xddda.music;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class meplayer extends Activity {

    public static MediaPlayer mediaPlayer;
    public LinearLayout menu_dialog;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        menu_dialog = findViewById(R.id.menu_dialog);
    }

    public void initAudio(final Context context, final String url) {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
        }
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public LinearLayout menu_dialog;
            @Override
            public void onCompletion(MediaPlayer mp) {
                //Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
                killMediaPlayer();
                menu_dialog.setVisibility(View.GONE);
            }
        });
        mediaPlayer.start();
    }

    private void killMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

循环水适配器
    package etes.xddda.music;
    import android.app.Dialog;
    import android.content.Context;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.media.MediaPlayer;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    import java.util.List;


    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{

        Context mContext;
        List<mList> mData;
        Dialog myDialog;

        private MediaPlayer mediaPlayer;
        private int playbackPosition=0;
        meplayer media;

        private LinearLayout menu_dialog;
        public RecyclerViewAdapter(Context mContext, List<mList> mData) {
            this.mContext = mContext;
            this.mData = mData;
        }

        public void onClick(View view) {
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v;
            v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
            final MyViewHolder vHolder = new MyViewHolder(v);

            // Dialog ini
            myDialog = new Dialog(mContext);
            myDialog.setContentView(R.layout.dialog);
            myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            vHolder.item_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {

                    TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
                    TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
                    ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
                    dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
                    dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
                    dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
                    //Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
                    myDialog.show();
                }
            });
            vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
                    menu_dialog.setVisibility(v.VISIBLE);
                    media = new meplayer();
                    media.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());

                    MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
                }
            });
            return vHolder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {

            holder.tv_name.setText(mData.get(position).getName());
            holder.tv_author.setText(mData.get(position).getPhone());
            holder.img.setImageResource(mData.get(position).getPhoto());
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        public static class MyViewHolder extends RecyclerView.ViewHolder {

            private ImageButton item_play;
            private LinearLayout menu_play;
            private TextView tv_name;
            private TextView tv_author;
            private TextView tv_url;
            private ImageView img;

            public MyViewHolder(View itemView) {
                super(itemView);
                item_play = itemView.findViewById(R.id.info_id);
                menu_play = itemView.findViewById(R.id.list_item_id);

                tv_name = (TextView) itemView.findViewById(R.id.name_list);
                tv_author = (TextView) itemView.findViewById(R.id.author_list);
                img = (ImageView) itemView.findViewById(R.id.img_contact);
            }
        }
    }

碎片列表
package etes.xddda.music;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class fragmentList extends Fragment {

    View v;
    private RecyclerView myrecyclerview;
    private List<mList> lstContact;

    private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
    private JsonArrayRequest ArrayRequest;
    private RequestQueue requestQueue ;

    public fragmentList() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.list_fragment,container,false);
        myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(getContext(), lstContact);
        myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        myrecyclerview.setAdapter(recyclerViewAdapter);
        return v;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstaceState) {
        super.onCreate(savedInstaceState);
        _JSONcall();
    }


    public void _JSONcall() {

        lstContact = new ArrayList<>();
        ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                JSONObject jsonObject = null;

                for (int i = 0 ; i<response.length();i++) {
                    try {

                        jsonObject = response.getJSONObject(i);

                        lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "Error 1!",
                                Toast.LENGTH_LONG).show();
                    }
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "Error 3!",
                        Toast.LENGTH_LONG).show();
            }
        });


        requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
        requestQueue.add(ArrayRequest);
    }
}

主要活动
package etes.xddda.music;

import android.annotation.SuppressLint;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;


public class MainActivity extends AppCompatActivity {

    private DrawerLayout nDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private viewPagerAdapter adapter;
    public LinearLayout menu_dialog;

    private String player_status = "playing";
    private ImageButton player_img;
    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nDrawerLayout = findViewById(R.id.drawer);

        menu_dialog = findViewById(R.id.menu_dialog);
        menu_dialog.setVisibility(View.GONE);

        player_img = findViewById(R.id.playorpause);
        player_img.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View view) {
                                              //setMargins(viewPager, 0,0,0,110);
                                              if (player_status == "playing") {
                                                  player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
                                                  meplayer.pauseAudio();
                                                  player_status = "paused";
                                              } else {
                                                  player_img.setImageResource(R.drawable.ic_pause_black_24dp);
                                                  meplayer.startAudio();
                                                  player_status = "playing";
                                              }
                                          }
                                      });



        //menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));

        mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
        nDrawerLayout.addDrawerListener(mToggle);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        tabLayout = findViewById(R.id.tablayout_id);
        viewPager = findViewById(R.id.viewpager_id);
        //viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
        //setMarginBottom(viewPager, 0);
        setMargins(viewPager, 0,0,0,0);

        adapter = new viewPagerAdapter(getSupportFragmentManager());

        //Add fragments here
        adapter.addFragment(new fragmentList(), ""); //Lista de música
        adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
        adapter.addFragment(new fragmentPlayList(), ""); //Playlist

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
        tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mToggle.syncState();
    }
    public static void setMargins (View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }
}

姆利斯特
package etes.xddda.music;

public class mList {
    private String Name;
    private String Author;
    private String URL;
    private int Photo;

    public mList() {
    }

    public mList(String name, String phone, String url, int photo) {
        Name = name;
        Author = phone;
        URL = url;
        Photo = photo;
    }

    //Get User
    public String getName() {
        return Name;
    }
    public String getPhone() {
        return Author;
    }
    public String getURL() {
        return URL;
    }
    public int getPhoto() {
        return Photo;
    }

    //Setter

    public void setName(String name) {
        Name = name;
    }

    public void setPhone(String phone) {
        Author = phone;
    }

    public void setURL(String url) {
        URL = url;
    }

    public void setPhoto(int photo) {
        Photo = photo;
    }
}

此脚本中没有错误,应用程序只是在音频完成时崩溃。这个问题与linemenu_dialog.setVisibility(View.GONE);有关,我已经在menu_dialog中定义了onCreate。那么,你能帮我吗?
备注:菜单对话框属于activity\u main.xml
谢谢您!

最佳答案

删除在OnCompletionListener中定义的本地变量菜单对话框:

package etes.xddda.music;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class meplayer extends Activity {

    public static MediaPlayer mediaPlayer;
    public LinearLayout menu_dialog;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        menu_dialog = findViewById(R.id.menu_dialog);
    }

    public void initAudio(final Context context, final String url) {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
        }
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            //public LinearLayout menu_dialog; REMOVE THIS
            @Override
            public void onCompletion(MediaPlayer mp) {
                //Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
                killMediaPlayer();
                menu_dialog.setVisibility(View.GONE);
            }
        });
        mediaPlayer.start();
    }

    private void killMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

09-11 18:51