尝试调用虚拟方法[空对象参考]

时间:2018-09-23 01:09:22

标签: java android android-studio android-mediaplayer

我花了最后5天的时间来尝试解决此问题。我真的不知道如何解决它。我得到objectKeys = Object.keys; public user={"id": "2", "name": "Marios Manolakeris", "skills": [ { "skill_1": "Machine Learning", "skill_2": "AI", "skill_3": "C++" } ] } skills:any; constructor(){ this.skills = this.user.skills; } 。检查我的代码:

RecyclerView.java

Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

请注意,我在这部分中调用 MainActivity.java

package etes.xdda.music;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
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;

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

                MainActivity a = new MainActivity();
                a.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);
        }
    }
}

这是我的 MainActivity.java

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

            MainActivity a = new MainActivity();
            a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
            MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
        }
    });

导致崩溃的部分代码是:

package etes.xdda.music;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
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;



    private static MediaPlayer mediaPlayer;

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

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

            }
        });
        mediaPlayer.start();
    }

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

    private void updateLayout() {
    try {
        menu_dialog = findViewById(R.id.menu_dialog);
        menu_dialog.setVisibility(View.GONE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@edit:我已经添加了这段代码,我不知道是否可以帮忙

fragmentList.java

private void updateLayout() {
    try {
        menu_dialog = findViewById(R.id.menu_dialog);
        menu_dialog.setVisibility(View.GONE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

请帮帮我,我对应该做什么没有更多的想法。谢谢

1 个答案:

答案 0 :(得分:1)

只是看一下代码,看来您做错了很多事情。如这行

        MainActivity a = new MainActivity();

您无法以这种方式实例化生命周期组件,例如服务,活动,片段等。当您调用启动方法等时,Android为您提供了这些组件。上一行所创建的活动不会通过使用startActivity启动的活动进行生命周期调用。结果,该活动的setContentView永远不会被调用,并且您会收到此错误。您必须删除这一行并正确实施,错误才会消失。

也要添加一下,当您需要在已启动的旧实例上调用方法时,实际上已经在创建一个活动的新实例。

编辑:尝试这样。

MainActivity activity;
List<mList> mData;
Dialog myDialog;

private MediaPlayer mediaPlayer;
private int playbackPosition=0;

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

然后

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

            activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
            activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
        }
    });

还将主要活动功能中的静电消除