Null Object Reference JAVA

Asked

Viewed 301 times

0

The whole problem is happening in a search, when I click and start typing the field it goes filtering the results, when I click on one of these results to open another screen, this error:

Attempt to invoke virtual method 'void android.widget.Textview.setText(java.lang.Charsequence)' on a null Object Reference

The search code looks like this:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_restaurante, menu);

    MenuItem searchItem = menu.findItem(R.id.action_search);

    SearchManager searchManager = (SearchManager) getActivity()
            .getSystemService(Context.SEARCH_SERVICE);

    searchView = null;
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();

        if(restaurantes == null || restaurantes.size() == 0){
            searchView.setEnabled(false);
        }
    }

    if (searchView != null) {
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getActivity().getComponentName()));

        searchView.setOnQueryTextListener(new OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String arg0) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String arg0) {
                filtrarRestaurante(arg0);
                return false;
            }
        });
    }
    //searchView.setVisibility(View.INVISIBLE);
    super.onCreateOptionsMenu(menu, inflater);
}

The function filtarRestaurante(agr0) is this:

public void filtrarRestaurante(String filtro){
 ArrayList<Restaurante> restaurantesEncontrados = new ArrayList<Restaurante>();

    if(filtro.length() == 0 && restaurantes != null){
        restaurantes.clear();
        restaurantes.addAll(restaurantesBkp);
        configurarAdapter();
        return;
    }

    // Procura pelo restaurante
    restaurantes.clear();
    restaurantes.addAll(restaurantesBkp);
    for(Restaurante restaurante : restaurantes){
        if(restaurante.getNomeRestaurante().toLowerCase().contains(filtro.toLowerCase())){
            restaurantesEncontrados.add(restaurante);
        }
    }
    restaurantes = restaurantesEncontrados;
    configurarAdapter();
}

Here is the init of my Fragment:

    @AfterViews
public void init() {
    Globales.setPedido(new Pedido());

    restaurante = (Restaurante) getArguments().getSerializable(RESTAURANTE_CARDAPIO);
    Globales.setRestauranteAtual(restaurante);
    carregarCardapio(restaurante);
}

So I charge the restaurant:

Restaurante restaurante;

This error is happening when I click on the restaurant and the error happens here:

@Override
public void onResume() {
    super.onResume();
    try{
        updateCarrinho();
        Globales.setListaOpcionais(null);

        TextView toolbarTitle = (TextView) getActivity().findViewById(
                R.id.toolbar_title);
        toolbarTitle.setText(restaurante.getNomeRestaurante());
    }catch (Exception e){
        MessageUtil.showError(getActivity(), e.getMessage());
    }

}

Right on this line

toolbarTitle.setText(restaurant.getNomeRestaurant());

when I’m going to name the restaurant the exception, why would I give it ?

  • I’ve noticed that restaurants sometimes double in search results.
  • The cool thing is that this only happens when I search the name of the restaurant, otherwise it comes in normally, so if I search it and I go back to the problem.

    ATTACHMENTS:

Photo of the debug in the restaurant part = (Restaurant) getArguments(). getSerializable(RESTAURANTE_CARDAPIO);

foto do debug

  • Make sure that you are enabling the correct XML and that in this XML you have the object with the toolbar_title ID

  • You are using Activity or Fragment?

  • There are some hypotheses, but to actually confirm the verdict, you would have to add more of your code to the question.

  • @Leonardodias I am using Fragment

  • @acklay can tell me that add, whatever you need

  • For example, restaurante, does not have at any time where it is being declared (in question) or receiving its constructor. This may even be a cause to the problem.

  • Renan, I added an answer, give a look! Hugs

  • @Leonardodias and in the case of restaurant duplication in the search list

  • You have to debug to see if you’re really assigning value to restaurante through the (Restaurante) getArguments().getSerializable(RESTAURANTE_CARDAPIO);

  • @acklay debugged and this coming normally, ta problem at set time.

  • Put it this way: toolbarTitle.setText(" "+restaurante.getNomeRestaurante())... and says what happens.

  • @acklay in the same way

  • @acklay was here thinking, if I redirect to the restaurant listing fragment, what do you think

  • @Renanrodrigues I wish I could help you, but there is no way to reproduce your error here because the code is not complete, both xml, and your class. I did not understand very well what would be "redirect to the fragment of listing of restaurants".... The answers you have been given are valid, but for some cases. Basically they are answers that suppose an error, they are "kicking". I could kick something, but there are numerous possibilities of error. = D

  • I managed to reach something, I verified that what is happening is when I research it is not finding null, however what you think of geviewbyid is another value, I’m still investigating here

Show 11 more comments

2 answers

1


Renan,

The problem is here:

TextView toolbarTitle = (TextView) getActivity().findViewById(R.id.toolbar_title);

When you call the getActivity(), You’re telling him to go look in the Activity layout that called his Fragment.

When you declare the Fragment layout, you call there on onCreateView so, for example:

View view = inflater.inflate(R.layout.fragment, container, false);

That one view that you should call to reference a layout item, in your case it would look like this:

TextView toolbarTitle = (TextView) view.findViewById(R.id.toolbar_title);
  • a problem appeared in the view talking cannot resolve symbol view

  • your change did not work, actually gave more problems yet, all restaurants are giving the same issue error now. I did so: TextView toolbarTitle = (TextView) getView().findViewById(R.id.toolbar_title); had to use getView for not giving to use view

0

The error is because the findViewById() of this line:

TextView toolbarTitle = (TextView) getActivity().findViewById(R.id.toolbar_title);

is returning null, IE, did not find a view with that id and with that the app crashea because you are trying to set the text in something that does not exist.

Since you didn’t post the code I will give some kicks, since it appears to be running inside a Fragment (by getActivity you are calling):

  • If your Textview with the "toolbar_title" attribute is in the Activity layout, make sure that in the Activity layout the name is matching.

  • If your Textview with the "toolbar_title" attribute is in the Fragment layout, make sure that in the Fragment layout the name is matching, create a global variable in Fragment and use findViewById() in Fragment’s Oncreateview() method.

Example:

private TextView mToolBarTitle;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_article_detail, container, false);
    mToolbarTitle = (TextView) rootView.findViewById(R.id.toolbar_title);

    ...

    return rootView;
}

Finally, seven text using this global variable in your method:

try{
    updateCarrinho();
    Globales.setListaOpcionais(null);

    mToolbarTitle.setText(restaurante.getNomeRestaurante());
}catch (Exception e){
    MessageUtil.showError(getActivity(), e.getMessage());
}
  • Or trying to set something that does not exist in a place where you have to insert a text.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.