0
Let’s go I need to make one fragment
where information will come from little to little, I am using the method of RecyclerView
to develop this. The whole idea is to get comments from a certain item.
First I created a fragment
, and stayed 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 that I created my own adapter
that has remained so:
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 mine 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 it like this:
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
, I mean, I want to go from one to the other, 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 in two metodos
this one of mine fragment
, the first this:
@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 on one he falls on the other, when I comment on the two, he does not appear mine 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 she’s making a mistake on the variable txtItensCarrinho
tried to make a if
to check if she is null
, but nothing helped. Already in the method onCreateOptionsMenu
error in the variable restaurante.isFavorito()
.
In Logcat the following error appears:
Process: com.projecto.teste, PID: 3304 java.lang.Nullpointerexception: Attempt to invoke virtual method 'Boolean com.projecto.teste.entity.Restaurante.isFavorito()' on a null Object Reference
To illustrate, this is happening by clicking on this button marked on the image:
It is worth noting that obotão side the heart is not sending to any view
nor Fragment, only performs a function on the page.
This is the full code of the page that is calling my Fragment:
@EFragment(R.layout.fragment_lista_cardapio)
public class FragmentCardapio extends Fragment {
public static String RESTAURANTE_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;
}
By error, your restaurant object has not yet been initialized when you tried to call the isFavorite method()
– Márcio Oliveira
What can I do to test and solve, can help me ?
– Renan Rodrigues
It was just a kick from me because you didn’t post the full code, so you can’t know where you try to initialize the object.
– Márcio Oliveira
which code you want I posted, tried to post as complete as possible
– Renan Rodrigues
Where you declare this object and where you initialize it for the first time?
– Márcio Oliveira
I put the full code
– Renan Rodrigues
@Márciooliveira saw something?
– Renan Rodrigues
I saw that you are using these view injection kits (to replace the traditional findViewById). I don’t particularly like it, since you can’t know exactly at what point in the life cycle of Activity/Fragment they will run. For example, you initialize the restaurant object within that @Afterviews, so my guess is that it’s only running after onCreateOptionsMenu, so the error. Try to initialize the init() method inside onCreateView to see what happens as it runs before onCreateOptionsMenu.
– Márcio Oliveira
How to do this ?
– Renan Rodrigues
Let’s go continue this discussion in chat.
– Renan Rodrigues
Man, now I’m stuck at work, later we can try.
– Márcio Oliveira
Okay then, but nothing has changed in the change
– Renan Rodrigues
some feedback @Márciooliveira
– Renan Rodrigues
Tense day today. Put as it was the code with the change I spoke.
– Márcio Oliveira
@Márciooliveira can’t remember kkkk anymore
– Renan Rodrigues