java.lang.Nullpointerexception: Attempt to invoke virtual method 'java.util.List .adapter.Conversasadapter.getConversas()' on a null Object Reference

Asked

Viewed 169 times

1

I’m having this mistake opening ChatActivity.class. Does anyone have a solution to this error? Thanks in advance.

Mistakes

EDIT: --LINE WRONG LINE LINE 89->> Conversation Taught = listConversionsAtualized.get( position ); After standardizing adpter

java.lang.Indexoutofboundsexception: Index: 0, Size: 0 at java.util.Arraylist.get(Arraylist.java:437) at xxx.xxx.Fragment.Searchfragment$1.onItemClick(Searchfragment.java:89)

at xxx.xxx.helper.RecyclerItemClickListener.onInterceptTouchEvent(Recycleritemclicklistener.java:21)

java.lang.Nullpointerexception: Attempt to invoke virtual method 'java.util.List .adapter.Conversasadapter.getConversas()' on a null Object Reference

at xxx.xxx.Fragment.Searchfragment$1.onItemClick(Searchfragment.java:86) at

xxx.xxx.helper.RecyclerItemClickListener.onInterceptTouchEvent(Recycleritemclicklistener.java:21)

Pesquisafragment.class

public class PesquisaFragment extends Fragment {

    //Widget
    private SearchView searchViewPesquisa;
    private RecyclerView recyclerPesquisa;
    private ConversasAdapter adapter;
    private List<Usuario> listaUsuarios;
    private DatabaseReference usuariosRef;
    private AdapterPesquisa adapterPesquisa;
    private String idUsuarioLogado;

    public PesquisaFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_pesquisa, container, false);

        searchViewPesquisa = view.findViewById(R.id.searchViewPesquisa);
        recyclerPesquisa   = view.findViewById(R.id.recyclerPesquisa);

        //Configurações iniciais
        listaUsuarios = new ArrayList<>();
        usuariosRef = ConfiguracaoFirebase.getFirebaseDatabase()
                .child("grupos");
        idUsuarioLogado = UsuarioFirebase.getIdentificadorUsuario();

        //Configura RecyclerView
        recyclerPesquisa.setHasFixedSize(true);
        recyclerPesquisa.setLayoutManager(new LinearLayoutManager(getActivity()));

        adapterPesquisa = new AdapterPesquisa(listaUsuarios, getActivity());
        recyclerPesquisa.setAdapter( adapterPesquisa );

        //Configurar evento de clique
        recyclerPesquisa.addOnItemTouchListener(new RecyclerItemClickListener(
                getActivity(),
                recyclerPesquisa,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        List<Conversa> listaConversasAtualizada = adapter.getConversas();
Conversa conversaSelecionada = listaConversasAtualizada.get( position );

                        if( conversaSelecionada.getIsGroup().equals("true") ){

                            Intent i = new Intent(getActivity(), ChatActivity.class);
                            i.putExtra("chatGrupo", conversaSelecionada.getGrupo() );
                            startActivity( i );

                        }else {
                            Intent i = new Intent(getActivity(), ChatActivity.class);
                            i.putExtra("chatContato", conversaSelecionada.getUsuarioExibicao() );
                            startActivity( i );
                        }

                    }

                    @Override
                    public void onLongItemClick(View view, int position) {

                    }

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    }
                }
        ));

        //Configura searchview
        searchViewPesquisa.setQueryHint("Buscar usuários");
        searchViewPesquisa.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                String textoDigitado = newText.toUpperCase();
                pesquisarUsuarios( textoDigitado );
                return true;
            }
        });



        return view;
    }

    private void pesquisarUsuarios(String texto){

        //limpar lista
        listaUsuarios.clear();

        //Pesquisa usuários caso tenha texto na pesquisa
        if( texto.length() >= 2 ){

            Query query = usuariosRef.orderByChild("nome")
                    .startAt(texto)
                    .endAt(texto + "\uf8ff" );

            query.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    //limpar lista
                    listaUsuarios.clear();

                    for( DataSnapshot ds : dataSnapshot.getChildren() ){

                        //verifica se é usuário logado e remove da lista
                        Usuario usuario = ds.getValue(Usuario.class);
                        if ( idUsuarioLogado.equals( usuario.getId() ) )
                            continue;

                        //adiciona usuário na lista
                        listaUsuarios.add( usuario );

                    }

                    adapterPesquisa.notifyDataSetChanged();

                    /*
                    int total = listaUsuarios.size();
                    Log.i("totalUsuarios", "total: " + total );
                    */
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }

    }

}

Conversasadapter.class

import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import igab.chat.R;
import igab.chat.model.Conversa;
import igab.chat.model.Grupo;
import igab.chat.model.Usuario;

import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;



public class ConversasAdapter extends RecyclerView.Adapter<ConversasAdapter.MyViewHolder> {

    private List<Conversa> conversas;
    private Context context;

    public ConversasAdapter(List<Conversa> lista, Context c) {
        this.conversas = lista;
        this.context = c;
    }

    public List<Conversa> getConversas(){
        return this.conversas;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_contatos, parent, false );
        return new MyViewHolder(itemLista);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        Conversa conversa = conversas.get( position );
        holder.ultimaMensagem.setText( conversa.getUltimaMensagem() );

        if ( conversa.getIsGroup().equals("true") ){

            Grupo grupo = conversa.getGrupo();
            holder.nome.setText( grupo.getNome() );

            if ( grupo.getFoto() != null ){
                Uri uri = Uri.parse( grupo.getFoto() );
                Glide.with( context ).load( uri ).into( holder.foto );
            }else {
                holder.foto.setImageResource(R.drawable.padrao);
            }

        }else {
            Usuario usuario = conversa.getUsuarioExibicao();
            if ( usuario != null ){
                holder.nome.setText( usuario.getNome() );

                if ( usuario.getFoto() != null ){
                    Uri uri = Uri.parse( usuario.getFoto() );
                    Glide.with( context ).load( uri ).into( holder.foto );
                }else {
                    holder.foto.setImageResource(R.drawable.padrao);
                }
            }
        }




    }

    @Override
    public int getItemCount() {
        return conversas.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        CircleImageView foto;
        TextView nome, ultimaMensagem;

        public MyViewHolder(View itemView) {
            super(itemView);

            foto = itemView.findViewById(R.id.imageViewFotoContato);
            nome = itemView.findViewById(R.id.textNomeContato);
            ultimaMensagem = itemView.findViewById(R.id.textEmailContato);

        }
    }

}

Recycleritemclicklistener.class

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    private OnItemClickListener mListener;
    GestureDetector mGestureDetector;

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        View childView = rv.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
            return true;
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

    public interface OnItemClickListener extends AdapterView.OnItemClickListener {
        public void onItemClick(View view, int position);

        public void onLongItemClick(View view, int position);
    }

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && mListener != null) {
                    mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
                }
            }
        });

    }
}

1 answer

0

You forgot to initialize this instance adapter yellow dial.

adapter nulo

  • estanciei mas agora recebo esse erro, .fragment.PesquisaFragment$1.onItemClick(PesquisaFragment.java:89) .helper.RecyclerItemClickListener.onInterceptTouchEvent(RecyclerItemClickListener.java:21)

Browser other questions tagged

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