搜索可聚焦空指针异常

时间:2016-08-01 20:29:12

标签: java android

嗨我做了关于搜索查询的所有事情,并且在错误方面没有问题,但我一直得到nullpointerexception的运行时错误

下面的java src代码

package com.developer.bunamay.mplayer;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends Activity {
String LOG_CLASS = "MainActivity";
public static final PlayUtils PlayerController = PlayUtils.getInstance();
CustomAdapter customAdapter = null;
private MediaFileAdapter mediaFileAdapter = null;
public static final int PICK_FOLDER_REQUEST = 8;
static TextView playingSong;
Button btnPlayer;
static Button btnPause, btnPlay, btnNext, btnPrevious;
Button btnStop;
LinearLayout mediaLayout;
static LinearLayout linearLayoutPlayingSong;
ListView mediaListView;
SeekBar seekBar;
TextView textBufferDuration, textDuration;
static ImageView imageViewAlbumArt;
static Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = MainActivity.this;
    init();

}

private void init() {
    getViews();
    setListeners();
    playingSong.setSelected(true);
    seekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
    if (PlayerConstants.SONGS_LIST.size() <= 0) {
        PlayerConstants.SONGS_LIST = PlayUtils.listOfSongs(getApplicationContext());
    }
    setListItems();
}

private void setListItems() {
    customAdapter = new CustomAdapter(this, R.layout.custom_list, PlayerConstants.SONGS_LIST);
    mediaListView.setAdapter(customAdapter);
    mediaListView.setFastScrollEnabled(true);
}

private void getViews() {
    playingSong = (TextView) findViewById(R.id.textNowPlaying);
    btnPlayer = (Button) findViewById(R.id.btnMusicPlayer);
    mediaListView = (ListView) findViewById(R.id.listViewMusic);
    mediaLayout = (LinearLayout) findViewById(R.id.linearLayoutMusicList);
    btnPause = (Button) findViewById(R.id.btnPause);
    btnPlay = (Button) findViewById(R.id.btnPlay);
    linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    btnStop = (Button) findViewById(R.id.btnStop);
    textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
    textDuration = (TextView) findViewById(R.id.textDuration);
    imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
    btnNext = (Button) findViewById(R.id.btnNext);
    btnPrevious = (Button) findViewById(R.id.btnPrevious);
}

private void setListeners() {
    mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
            Log.d("TAG", "TAG Tapped INOUT(IN)");
            PlayerConstants.SONG_PAUSED = false;
            PlayerConstants.SONG_NUMBER = position;
            boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
            if (!isServiceRunning) {
                Intent i = new Intent(getApplicationContext(), MusicService.class);
                startService(i);
            } else {
                PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
            }
            updateUI();
            changeButton();
            Log.d("TAG", "TAG Tapped INOUT(OUT)");
        }
    });

    btnPlayer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
            startActivity(i);
        }
    });
    btnPlay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Controls.playControl(getApplicationContext());
        }
    });
    btnPause.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Controls.pauseControl(getApplicationContext());
        }
    });
    btnNext.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Controls.nextControl(getApplicationContext());
        }
    });
    btnPrevious.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Controls.previousControl(getApplicationContext());
        }
    });
    btnStop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), MusicService.class);
            stopService(i);
            linearLayoutPlayingSong.setVisibility(View.GONE);
        }
    });
    imageViewAlbumArt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
            startActivity(i);
        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    try {
        boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
        if (isServiceRunning) {
            updateUI();
        } else {
            linearLayoutPlayingSong.setVisibility(View.GONE);
        }
        changeButton();
        PlayerConstants.SEEKBAR_HANDLER = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Integer i[] = (Integer[]) msg.obj;
                textBufferDuration.setText(PlayUtils.getDuration(i[0]));
                textDuration.setText(PlayUtils.getDuration(i[1]));
                seekBar.setProgress(i[2]);
            }
        };
    } catch (Exception e) {
    }
}

@SuppressWarnings("deprecation")
public static void updateUI() {
    try {
        MediaItem data = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER);
        playingSong.setText(data.getTitle() + " " + data.getArtist() + "-" + data.getAlbum());
        Bitmap albumArt = PlayUtils.getAlbumart(context, data.getAlbumId());
        if (albumArt != null) {
            imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(albumArt));
        } else {
            imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(PlayUtils.getDefaultAlbumArt(context)));
        }
        linearLayoutPlayingSong.setVisibility(View.VISIBLE);
    } catch (Exception e) {
    }
}

public static void changeButton() {
    if (PlayerConstants.SONG_PAUSED) {
        btnPause.setVisibility(View.GONE);
        btnPlay.setVisibility(View.VISIBLE);
    } else {
        btnPause.setVisibility(View.VISIBLE);
        btnPlay.setVisibility(View.GONE);
    }
}

public static void changeUI() {
    updateUI();
    changeButton();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.action_about:
            Intent about = new Intent(MainActivity.this, About.class);
            startActivity(about);
            break;
        case R.id.action_exit:
            finish();
            break;
    }
    int id = item.getItemId();
    // get music from specific folder
    if (id == R.id.folder_music) {
        Intent intent = new Intent(this, FolderPickerActivity.class);
        startActivityForResult(intent, PICK_FOLDER_REQUEST);
        return true;
    }

    // search songs by title
    if (id == R.id.action_search_title) {
        PlayerController.SEARCH_TYPE = "TITLE";

        return true;
    }
    // search songs by artist
    if (id == R.id.action_search_artist) {
        PlayerController.SEARCH_TYPE = "ARTIST";

        return true;
    }
    // search songs by album
    if (id == R.id.action_search_album) {
        PlayerController.SEARCH_TYPE = "ALBUM";

        return true;
    }

    if (id == R.id.action_sort_title) {
        MediaFileComparator.sortByTitle(PlayerController.SONGS_LIST);
        MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
        mediaAdapter.notifyDataSetChanged();

        return true;
    }
    if (id == R.id.action_sort_album) {
        MediaFileComparator.sortByAlbum(PlayerController.SONGS_LIST);
        MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
        mediaAdapter.notifyDataSetChanged();

        return true;
    }
    if (id == R.id.action_sort_artist) {
        MediaFileComparator.sortByArtist(PlayerController.SONGS_LIST);
        MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
        mediaAdapter.notifyDataSetChanged();

        return true;
    }
    if (id == R.id.action_sort_duration) {
        MediaFileComparator.sortByDuration(PlayerController.SONGS_LIST);
        MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
        mediaAdapter.notifyDataSetChanged();

        return true;
    }
    return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

    // init menu items for search
    MenuItem itemSearchTitle = menu.findItem(R.id.action_search_title);
    MenuItem itemSearchAlbum = menu.findItem(R.id.action_search_album);
    MenuItem itemSearchArtist = menu.findItem(R.id.action_search_artist);

    SearchView searchViewTitle = (SearchView) itemSearchTitle.getActionView();
    SearchView searchViewAlbum = (SearchView) itemSearchAlbum.getActionView();
    SearchView searchViewArtist = (SearchView) itemSearchArtist.getActionView();

    searchViewTitle.setFocusable(true);
    searchViewAlbum.setFocusable(true);
    searchViewArtist.setFocusable(true);

    // init searchable info for each menu item
    searchViewTitle.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchViewTitle.setQueryHint("title...");
    searchViewTitle.setIconified(true);

    searchViewAlbum.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchViewAlbum.setQueryHint("album...");
    searchViewAlbum.setIconified(true);

    searchViewArtist.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchViewArtist.setQueryHint("artist...");
    searchViewArtist.setIconified(true);

    // set textChangeListeners for each type of search
    final SearchView.OnQueryTextListener textChangeListenerTitle = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            if (!TextUtils.isEmpty(newText)) {
                mediaFileAdapter.getFilter().filter(newText);
            }
            return true;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            return true;
        }
    };

    SearchView.OnQueryTextListener textChangeListenerAlbum = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            if (!TextUtils.isEmpty(newText)) {
                mediaFileAdapter.getFilter().filter(newText);
            }
            return true;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            return true;
        }
    };

    SearchView.OnQueryTextListener textChangeListenerArtist = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            if (!TextUtils.isEmpty(newText)) {
                mediaFileAdapter.getFilter().filter(newText);
            }
            return true;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            return true;
        }
    };

    // apply listeners to searchViews
    searchViewTitle.setOnQueryTextListener(textChangeListenerTitle);
    searchViewAlbum.setOnQueryTextListener(textChangeListenerAlbum);
    searchViewArtist.setOnQueryTextListener(textChangeListenerArtist);

       return super.onCreateOptionsMenu(menu);
  }

 }

我一直在

上收到错误
        searchViewTitle.setFocusable(true);

这里是显示错误的logcat

07-31 18:12:18.047 2066-2066/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.developer.bunamay.mplayer, PID: 2066
                                             java.lang.NullPointerException
                                                 at com.developer.bunamay.mplayer.MainActivity.onCreateOptionsMenu(MainActivity.java:300)
                                                 at android.app.Activity.onCreatePanelMenu(Activity.java:2538)
                                                 at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
                                                 at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:800)
                                                 at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
                                                 at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                                                 at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                                                 at android.view.Choreographer.doFrame(Choreographer.java:543)
                                                 at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
                                                 at android.os.Handler.handleCallback(Handler.java:733)
                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                 at android.os.Looper.loop(Looper.java:136)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:515)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                 at dalvik.system.NativeStart.main(Native Method)
   07-31 18:12:18.051 587-599/? W/ActivityManager:   Force finishing activity com.developer.bunamay.mplayer/.MainActivity

谢谢!

1 个答案:

答案 0 :(得分:0)

itemSearchTitle的ActionView此时为空。