我在以下语句中得到一个空指针异常:
    MenuSAP = (ShareActionProvider) item.getActionProvider();方法中的onCreateOptionsMenu(Menu menu)

MainActivity.java

 public class MainActivity extends Activity {
      protected static final int REQUEST_OK = 1;
      ListView l1;
      ArrayList<Array_songs> songlist;
      EditText e1;
      Song_adapter adp;
      private ShareActionProvider MenuSAP;

      ImageButton ib;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getActionBar();
        //actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setIcon(R.drawable.iconw);

        l1=(ListView)findViewById(R.id.lv1);
        ib=(ImageButton)findViewById(R.id.ib1);
        songlist=new ArrayList<Array_songs>();
        e1= (EditText)findViewById(R.id.editText1);
        e1.addTextChangedListener(tw);

        ib.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
                try{
                    startActivityForResult(i,REQUEST_OK );
                }catch(ActivityNotFoundException r){
                    Toast.makeText(getApplicationContext(),"song cant be played", Toast.LENGTH_SHORT).show();

                }


            }
        });


        adp=new Song_adapter(MainActivity.this, songlist, this.getApplication());
        l1.setAdapter(adp);
        getSongList("");


        l1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {

                int sCB = getVar();
                if(sCB == 0) {
                    Array_songs slist = songlist.get(position);
                    String Song_Title = slist.get_title();
                    String Song_Artist = slist.get_artist();
                    long Song_ID = slist.get_id();


                    //Toast.makeText(getApplicationContext(), Song_Artist + Song_Title + String.valueOf(Song_ID), Toast.LENGTH_SHORT).show();

                    // TODO Auto-generated method stub

                    Uri song_path = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Song_ID);


                    Intent musicplayer = new Intent(Intent.ACTION_VIEW);
                    musicplayer.setDataAndType(song_path, "audio/*");

                    try {

                        startActivity(musicplayer);

                    } catch (ActivityNotFoundException e) {

                        Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_SHORT).show();

                    }

                }
                else
                {

                }

            }
        });



        l1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                changeVar();
                vibrate();
                int select = l1.getSelectedItemPosition();
                l1.setItemChecked(select, true);
                adp.notifyDataSetChanged();
                return false;
            }
        });
    }

    private void vibrate() {
        Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(120);
    }


    private void changeVar() {
        ((SyncClass) this.getApplication()).setShowCheckBox(1);
    }



    private int getVar()
    {
        Integer sCB = Integer.parseInt(((SyncClass) this.getApplication()).getShowCheckBox());
        return sCB;
    }



    TextWatcher tw=new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            songlist.clear();
            adp.notifyDataSetChanged();
            getSongList(s.toString());



        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    };



    protected void  onActivityResult(int requestcode,int resultcode,Intent data){

        super.onActivityResult(requestcode, resultcode, data);

        if(requestcode==REQUEST_OK && resultcode==RESULT_OK){
            ArrayList<String> ls=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

            e1.setText(ls.get(0));

        }


    }



    public void getSongList(String stitle){
        ContentResolver cr= getContentResolver();
        Uri music=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor mus=cr.query(music, null, null, null, null);

        if(mus != null && mus.moveToFirst()){

            int titleint=mus.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int artistint= mus.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
            int songid=mus.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            do{
                String songTitle=mus.getString(titleint);
                String songArtist=mus.getString(artistint);
                long  songId=mus.getLong(songid);

                if(songTitle.toUpperCase().contains(stitle.toUpperCase())){


                    songlist.add(new Array_songs(songId, songTitle, songArtist));

                }

            }while(mus.moveToNext());

        }

    }



    @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);
        MenuItem item = menu.findItem(R.id.menu_item_share);
        MenuSAP = new ShareActionProvider(this);
        MenuSAP.setShareIntent(createShareIntent());
        MenuSAP = (ShareActionProvider) item.getActionProvider();
        return super.onCreateOptionsMenu(menu);
    }

    private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("audio/*");
        shareIntent.putExtra(Intent.EXTRA_MIME_TYPES,"audio/*");
        return shareIntent;
    }


    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    @Override
    public void onBackPressed() {
        int check;
        check = getVar();
        if(check == 1)
        {
            ((SyncClass) this.getApplication()).setShowCheckBox(0);
            adp.notifyDataSetChanged();
        }
        else
        {
            super.onBackPressed();
        }

    }
}


SongAdapter.java

    public class Song_adapter extends BaseAdapter {
    private ArrayList<Array_songs> song_ob;
    private LayoutInflater inflator_ob;
    private Application xyz;
    //private int sCB = ((SyncClass) this.getApplication()).getSomeVariable();
    public Song_adapter(Context c,ArrayList<Array_songs> songlist, Application a)
    {
        song_ob=songlist;
        inflator_ob= LayoutInflater.from(c);
        xyz = a;
    }

    @Override
    public int getCount() {

        // TODO Auto-generated method stub
        return song_ob.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent) {
        // TODO Auto-generated method stub
        LinearLayout lin_ob =(LinearLayout)inflator_ob.inflate(R.layout.song_content, parent,false) ;
        Array_songs ars_ob= song_ob.get(position);
        TextView title= (TextView)lin_ob.findViewById(R.id.song_name);
        TextView artist= (TextView)lin_ob.findViewById(R.id.artist);
        //CheckBox check = (CheckBox) lin_ob.findViewById(R.id.cbselect);
        if(((SyncClass) xyz).getShowCheckBox() == "1")
        {
            lin_ob.findViewById(R.id.cbselect).setVisibility(View.VISIBLE);
        }
        else
        {
            lin_ob.findViewById(R.id.cbselect).setVisibility(View.GONE);
        }

        String stitle= ars_ob.get_title();
        String sartist= ars_ob.get_artist();

        title.setText(stitle);
        artist.setText(sartist);


        return lin_ob;

    }

}


SyncClass.java

 public class SyncClass extends Application {
    private String showCheckBox = "0";

    public String getShowCheckBox()
    {
        return showCheckBox;
    }

    public void setShowCheckBox(int showCheckBox)
    {
        this.showCheckBox = Integer.toString(showCheckBox);
    }
}


menu_main.xml

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
    <item
        android:id="@+id/menu_item_share"
        android:showAsAction="ifRoom"
        android:title="Share"
        android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>


请帮忙。是Android的新手,需要帮助.. !!

最佳答案

代替使用getActionProvider,尝试使用
MenuItemCompat.setActionProvider(item, menuSAP);

请查看此答案以获取更多信息:

why MenuItemCompat.getActionProvider returns null?

关于java - 共享操作提供程序对象中的NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32136228/

10-10 15:52