Исключение NullPointer в AndroidX SearchView - PullRequest
0 голосов
/ 15 января 2020

У меня есть приложение, настроенное в настоящее время с архитектурой MVP. У меня настроен докладчик так:

package com.example.test;

// Declaration of packages
import androidx.appcompat.widget.SearchView;

public class LocationActivity extends AppCompatActivity implements LocationContract.View {
    private LocationPresenter presenter;
    private ProgressDialog progressDialog;

    @BindView(R.id.location_toolbar)
    Toolbar toolbar;

    @BindView(R.id.location_recycler)
    RecyclerView locationRecycler;

    private LocationAdapter locationAdapter;
    private SearchManager searchManager;
    private SearchView searchView;

    @Override
    protected int layoutRes() {
        return R.layout.location_activity;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.location_title);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        invalidateOptionsMenu();

        // Associate searchable configuration with the search view
        searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        // Setting up presenter with the data
        presenter = new LocationPresenter();
        presenter.attachView(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.subscribe();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the search toolbar menu instead of the default menu in the Base Activity
        getMenuInflater().inflate(R.menu.search_toolbar_menu, menu);

        searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(Integer.MAX_VALUE);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_search) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        // If the search view is opened, close it when the back button is pressed.
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
            return;
        }

        super.onBackPressed();
    }

    @Override
    public void onLocations(List<SensorLocation> locations, String closestSensorId) {
        locationAdapter = new LocationAdapter(locations, getResources(), this, closestSensorId);

        locationRecycler.setAdapter(locationAdapter);
        locationRecycler.setLayoutManager(new LinearLayoutManager(this));
        locationRecycler.invalidate();

        // Set the onQuery listener
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                locationAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                locationAdapter.getFilter().filter(query);
                return false;
            }
        });
    }
} 

Идея этого заключается в том, что при создании действия я настраиваю докладчик, который будет получать данные из API и вызывать onLocations. * 1005. *

При загрузке приложения все работает нормально, до тех пор, пока не нажата кнопка «Назад» и это действие не воссоздано, затем я получаю сообщение об ошибке:

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.widget.SearchView.setOnQueryTextListener(androidx.appcompat.widget.SearchView$OnQueryTextListener)' on a null object reference

При отладке я заметил, что onCreateOptionsMenu() не был вызван во второй раз, когда действие было возобновлено.

Может ли кто-нибудь любезно помочь, почему это происходит?

...