Fragment with recyclerview closing application

0

We'll need to do a fragment where information will come in little by little, I'm using the RecyclerView method to develop this. The whole idea is to get comments on a certain item.

Firstly I created a fragment , and it looks like this:

public class ComentariosFragment extends Fragment {

private RecyclerView mRecyclerView;
private List<Comentarios> mList;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.activity_comentarios, container,false);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.lstComentarios);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            ComentarioAdapter adapter = (ComentarioAdapter) mRecyclerView.getAdapter();

            if(mList.size() == llm.findLastCompletelyVisibleItemPosition() + 1){
                List<Comentarios> listAux = ((MainActivity) getActivity()).getSetComentariosList(10);

                for (int i = 0; i < listAux.size(); i++){
                    adapter.addItemList(listAux.get(i), mList.size());
                }
            }
        }
    });

    LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(llm);


    mList = ((MainActivity) getActivity()).getSetComentariosList(10);
    ComentarioAdapter adapter = new ComentarioAdapter(getActivity(), mList);

    mRecyclerView.setAdapter(adapter);

    return view;
 }
}

After this I created my adapter which looks like this:

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

private List<Comentarios> mList;
private LayoutInflater mLayoutInflater;


public ComentarioAdapter(Context c, List<Comentarios> l){
    mList = l;
    mLayoutInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public void addItemList(Comentarios c,int positon) {
    mList.add(c);
    notifyItemInserted(positon);
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = mLayoutInflater.inflate(R.layout.item_comentario, parent, false);
    MyViewHolder mVH = new MyViewHolder(v);
    return mVH;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.nmCliente.setText( mList.get(position).getNmCliente() );
    holder.observacaoAvaliacao.setText( mList.get(position).getObservacaoAvaliacao() );
    holder.ratingBar.setRating( mList.get(position).getAvaliacao() );
}

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

public class MyViewHolder extends RecyclerView.ViewHolder{
    public TextView nmCliente,observacaoAvaliacao;
    public RatingBar ratingBar;
    public MyViewHolder(View itemView) {
        super(itemView);

        nmCliente = (TextView) itemView.findViewById(R.id.nmCliente);
        observacaoAvaliacao = (TextView) itemView.findViewById(R.id.observacaoAvaliacao);
        ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);

    }
 }
}

Then I created my layout with activity like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white" >

<include
    android:id="@+id/toolbar_actionbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    layout="@layout/toolbar_default" />


<android.support.v7.widget.RecyclerView
    android:id="@+id/lstComentarios"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

And my item comentario :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="20dp"
    android:paddingLeft="16dp">

<TextView
    android:textColor="@color/primary_text"
    android:id="@+id/nmCliente"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:paddingRight="16dp"
    android:textSize="16sp" />

<RatingBar
    android:id="@+id/ratingBar"
    style="?android:attr/ratingBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="25dp"
    android:layout_alignLeft="@+id/nmCliente"
    android:layout_below="@+id/observacaoAvaliacao"
    android:max="5"
    android:numStars="5"
    android:progressBackgroundTint="#A79896"
    android:progressTint="@color/accent_color" />


<TextView
    android:textColor="@color/ampm_text_color"
    android:id="@+id/observacaoAvaliacao"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:paddingRight="16dp"
    android:textSize="16sp" />

<View
android:id="@+id/vw_divider"
android:layout_marginTop="20dp"
android:layout_below="@+id/observacaoAvaliacao"
android:background="@color/pink"
android:layout_width="match_parent"
android:layout_height="0.8dp" />

</RelativeLayout>

In my MainActivity I'm creating a list just to test, I do so:

public List<Comentarios> getSetComentariosList(int qtd){
    String[] nome = new String[]{"Gallardo", "Vyron", "Corvette", "Pagani Zonda", "Porsche 911 Carrera", "BMW 720i", "DB77", "Mustang", "Camaro", "CT6"};
    String[] comentarios = new String[]{"asdasdfsdfasdfasdfasdfasdf", "asdfsdfgfghdfghdfghfd", "Corfsdsdsd s  asdfasf asdvette", "fasdf asdf efaefawefasdf Zonda", "dfsdfsdfsad sdfa df 911 Carrera", "BMWasd weqweqweqwe  720i", "DB7 wqefwefqw e  qwefq we7", "Musta qwerqwer q wqerq ng", "Camar qerqw erq o", "CTqwer qwe wqe6"};
    Integer[] rating = new Integer[]{1,2,3,4,3,2,5,2,5,3};
    List<Comentarios> listAux = new ArrayList<>();

    for(int i = 0; i < qtd; i++){
        Comentarios c = new Comentarios(rating[i % rating.length], nome[i % nome.length], comentarios[ i % comentarios.length ] );
        listAux.add(c);
    }
    return(listAux);
}

I'm calling this whole process another fragment , or I want to get out of one to go to another, where I'm doing this:

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

    if(id == R.id.favoritar){
        if (!restaurante.isFavorito()) {
            // Adiciona aos favoritos
            adicionarAosFavoritos();
        } else {
            // Remove
            removerDosFavoritos();
        }
    }else if(id == R.id.comentar) {
        FragmentCardapio fgtComentarios = new FragmentCardapio();
        getFragmentManager().beginTransaction().replace(R.id.fragment_drawer, fgtComentarios).commit();
    }
    return super.onOptionsItemSelected(item);
}

When I do the button click event it drops to two metodos of this my fragment , the first one is:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_favoritar_restaurante, menu);
    menuItemCoracao = menu.getItem(1);

    if (restaurante.isFavorito()) {
        // Altera o icone para favoritado
        menuItemCoracao.setIcon(R.drawable.ic_favoritado);
    }

    super.onCreateOptionsMenu(menu, inflater);
}

and soon after this:

@Override
public void onResume() {
    super.onResume();
    updateCarrinho();

    TextView toolbarTitle = (TextView) getActivity().findViewById(
            R.id.toolbar_title);
    toolbarTitle.setText(restaurante.getNomeRestaurante());
}

When I comment one it falls in another, when I comment the two, it does not appear my fragment with the comments.

The function updatecarrinho() is this:

    private void updateCarrinho() {

    if(txtItensCarrinho != null){
        if (Globales.getPedido() != null && Globales.getPedido().getItens() != null) {
            if (Globales.getPedido().getItens().size() == 1) {
                txtItensCarrinho.setText(Globales.getPedido().getItens().size()
                        + " item no carrinho.");
            } else if (Globales.getPedido().getItens().size() == 0) {
                txtItensCarrinho.setText("Nenhum item no carrinho.");
            } else {
                txtItensCarrinho.setText(Globales.getPedido().getItens().size()
                        + " itens no carrinho.");
            }
        }
        imgCart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (Globales.getPedido() == null
                        || Globales.getPedido().getItens() == null
                        || Globales.getPedido().getItens().isEmpty()) {
                    MessageUtil.showError(getActivity(),
                            R.string.carrinho_vazio);
                    return;
                }
                Intent intentCarrinho = new Intent(getActivity(),
                        com.fomedemais.FomeDemais.CarrinhoActivity_.class);
                startActivity(intentCarrinho);
            }
        });
    }
}

and it is giving error in the variable txtItensCarrinho I tried to make a if to check if it is null , but it did nothing. In the% method of% it of the error in the variable onCreateOptionsMenu .

Logcat is displaying the following error:

  

Process: com.project.test, PID: 3304 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.project.teste.entity.Restaurante.isFavorito ()' on a null object reference

To illustrate, this is happening by clicking on this button marked in the image:

It'sworthnotingthatonthesidetheheartisnotsendingtoanyrestaurante.isFavorito()norfragment,itonlyperformsafunctiononthepage.

Thisisthefullcodeofthepagethatiscallingmyfragment:

@EFragment(R.layout.fragment_lista_cardapio)publicclassFragmentCardapioextendsFragment{publicstaticStringRESTAURANTE_CARDAPIO="restaurante_carregado";

@ViewById
StickyListHeadersListView lstCardapio;

@ViewById
TextView txtItensCarrinho;

@ViewById
ImageButton imgCart;

Restaurante restaurante;

CardapioAdapter adapter;
List<Restaurante> cardapio;

MenuItem menuItemCoracao;

@Click(R.id.lytCarrinho)
public void carrinho() {
    if (Globales.getPedido() == null
            || Globales.getPedido().getItens() == null
            || Globales.getPedido().getItens().isEmpty()) {
        MessageUtil.showError(getActivity(), R.string.carrinho_vazio);
        return;
    }

    Intent intentCarrinho = new Intent(getActivity(),
            com.fomedemais.FomeDemais.CarrinhoActivity_.class);
    startActivity(intentCarrinho);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        setHasOptionsMenu(true);
    return super.onCreateView(inflater, container, savedInstanceState);
}

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

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

@Override
public void onResume() {
    super.onResume();
    updateCarrinho();

    TextView toolbarTitle = (TextView) getActivity().findViewById(
            R.id.toolbar_title);
    toolbarTitle.setText(restaurante.getNomeRestaurante());
}

public void carregarCardapio(Restaurante restaurante) {
    try {
        final AsyncHttpClient request = new AsyncHttpClient();
        request.setTimeout(60);
        // Parametros
        RequestParams params = new RequestParams();
        params.put("cdRestaurante",
                String.valueOf(restaurante.getCodigoRestaurante()));
        params.put("cdCliente", PreferencesUtils.getString(getActivity(),
                PreferencesUtils.PREFERENCIA_CODIGO_CLIENTE));

        // Exibe a mensagem de progresso
        final ProgressDialog progress = MessageUtil.showProgress(
                getActivity(), R.string.aguarde, ResourceUtil.getString(
                        R.string.carregando_cardapio,
                        restaurante.getNomeRestaurante()), true);
        final Context mContext = getActivity();
        progress.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                request.cancelRequests(mContext, true);
            }
        });
        progress.show();

        request.post(Constantes.URL_CARDAPIO, params,
                new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(String resposta) {
                        progress.dismiss();
                        sucessoResposta(resposta);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        progress.dismiss();
                        MessageUtil.showError(getActivity(), R.string.erro_desconhecido);
                    }
                });
    } catch (Exception e) {
        MessageUtil.showError(getActivity(), R.string.erro_desconhecido);
        NegocioLog.inserir(Log.AVISO, e);
    }
}

private void sucessoResposta(String json) {
    try {
        Cardapio cardapio = JSONParser.parseCardapio(json);
        Globales.setCardapio(cardapio);
        Globales.getRestauranteAtual().setPagamentos(
                cardapio.getFormasPagamento());
        adapter = new CardapioAdapter(getActivity(), cardapio);
        lstCardapio.setAdapter(adapter);
        final Context context = getActivity();

        lstCardapio.getWrappedList().setOnItemClickListener(
                new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent,
                            View view, int position, long id) {
                        if (Globales.getRestauranteAtual().getStatus() == Constantes.STATUS_FECHADO) {
                            MessageUtil.showError(context,
                                    R.string.restaurante_fechado_cardapio);
                            return;
                        }

                        Comida comida = (Comida) adapter.getItem(position);

                        if(comida.isIndisponivel()){
                            MessageUtil.showError(context, "O item selecionado nao está disponível no momento.");
                            return;
                        }

                        Globales.getPedido().setCodRestaurante(restaurante.getCodigoRestaurante());
                        Intent itensActivity = new Intent(getActivity(), com.fomedemais.FomeDemais.AdicionarItemActivity_.class);
                        itensActivity.putExtra(AdicionarItemActivity.COMIDA, comida);
                        itensActivity.putExtra(AdicionarItemActivity.RESTAURANTE,restaurante);
                        startActivityForResult(itensActivity, 0);
                    }
                });
    } catch (Exception e) {
        NegocioLog.inserir(Log.AVISO, e);
        try {
            MessageUtil
                    .showError(getActivity(), R.string.erro_desconhecido);
        } catch (Exception e2) {
            NegocioLog.inserir(Log.AVISO, e);
        }
    }
}

private void updateCarrinho() {

    if(txtItensCarrinho != null){
        if (Globales.getPedido() != null && Globales.getPedido().getItens() != null) {
            if (Globales.getPedido().getItens().size() == 1) {
                txtItensCarrinho.setText(Globales.getPedido().getItens().size()
                        + " item no carrinho.");
            } else if (Globales.getPedido().getItens().size() == 0) {
                txtItensCarrinho.setText("Nenhum item no carrinho.");
            } else {
                txtItensCarrinho.setText(Globales.getPedido().getItens().size()
                        + " itens no carrinho.");
            }
        }
        imgCart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (Globales.getPedido() == null
                        || Globales.getPedido().getItens() == null
                        || Globales.getPedido().getItens().isEmpty()) {
                    MessageUtil.showError(getActivity(),
                            R.string.carrinho_vazio);
                    return;
                }
                Intent intentCarrinho = new Intent(getActivity(),
                        com.fomedemais.FomeDemais.CarrinhoActivity_.class);
                startActivity(intentCarrinho);
            }
        });
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_favoritar_restaurante, menu);
    menuItemCoracao = menu.getItem(1);

    if (restaurante.isFavorito()) {
        // Altera o icone para favoritado
        menuItemCoracao.setIcon(R.drawable.ic_favoritado);
    }

    super.onCreateOptionsMenu(menu, inflater);
}

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

    if(id == R.id.favoritar){
        if (!restaurante.isFavorito()) {
            // Adiciona aos favoritos
            adicionarAosFavoritos();
        } else {
            // Remove
            removerDosFavoritos();
        }
    }else if(id == R.id.comentar) {
        FragmentCardapio fgtComentarios = new FragmentCardapio();
        getFragmentManager().beginTransaction().replace(R.id.fragment_drawer, fgtComentarios).commit();
    }
    return super.onOptionsItemSelected(item);
}

private void removerDosFavoritos() {
    try {
        final AsyncHttpClient request = new AsyncHttpClient();

        // Parametros
        RequestParams params = new RequestParams();
        params.put("cdRestaurante",
                String.valueOf(restaurante.getCodigoRestaurante()));
        params.put("cdCliente", PreferencesUtils.getString(getActivity(),
                PreferencesUtils.PREFERENCIA_CODIGO_CLIENTE));

        request.post(Constantes.URL_EXCLUIR_RESTAURANTE_FAVORITO, params,
                new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(String resposta) {
                        restauranteRemovido(resposta);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                    }
                });
    } catch (Exception e) {
        NegocioLog.inserir(Log.AVISO, e);
    }
}

private void adicionarAosFavoritos() {
    try {
        final AsyncHttpClient request = new AsyncHttpClient();

        // Parametros
        RequestParams params = new RequestParams();
        params.put("cdRestaurante",
                String.valueOf(restaurante.getCodigoRestaurante()));
        params.put("cdCliente", PreferencesUtils.getString(getActivity(),
                PreferencesUtils.PREFERENCIA_CODIGO_CLIENTE));

        request.post(Constantes.URL_INSERIR_RESTAURANTE_FAVORITOS, params,
                new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(String resposta) {
                        restauranteFavoritado(resposta);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                    }
                });
    } catch (Exception e) {
        NegocioLog.inserir(Log.AVISO, e);
    }
}

public void restauranteRemovido(String resposta) {
    try {
        RetornoGenerico retorno = JSONParser.parseGenerico(resposta);
        if (retorno.isSucesso()) {
            Toast.makeText(getActivity(),
                    R.string.restaurante_removido_favorito,
                    Toast.LENGTH_SHORT).show();
        }
        // Altera o icone para favoritado
        menuItemCoracao.setIcon(R.drawable.ic_favoritar);
    } catch (Exception e) {
        NegocioLog.inserir(Log.AVISO, e);
    }
}

public void restauranteFavoritado(String resposta) {
    try {
        RetornoGenerico retorno = JSONParser.parseGenerico(resposta);
        if (retorno.isSucesso()) {
            Toast.makeText(getActivity(),
                    R.string.restaurante_adicionado_como_favorito,
                    Toast.LENGTH_SHORT).show();
        }
        // Altera o icone para favoritado
        menuItemCoracao.setIcon(R.drawable.ic_favoritado);
    } catch (Exception e) {
        NegocioLog.inserir(Log.AVISO, e);
    }
 }

}

class CardapioHolder {
    TextView txtNomeRestaurante;
    ImageView imgLogoRestaurante;
    TextView txtFuncionamento;
}
    
asked by anonymous 19.05.2017 / 15:29

1 answer

1

Renan, I was a bit confused by the code but I think I understood. First thing to remove from onResume

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

And I put OnCreate's Fragment:

public class AboutFragment extends Fragment {
    TextView toolbarTitle;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        toolbarTitle = (TextView) getActivity().findViewById(
                R.id.toolbar);
    }

}

I advise you to read the link to capture your objects and link to better control the events between fragments and activities.

Abs!

    
27.05.2017 / 17:39