I am retrieving Cloud Firestore data in Modelo.class and I'm trying to pass these variables from the to fragment DescDenuncia using a adapter Adapter.class but to do that I need to get the context tfor it using the I've already tried use AppCompatActivity activity = (AppCompatActivity) view.getContext();, but my app crashes every time I run this line, I think its necessary to use a Context in the getSupportFragmentManager() to it works. If i'm doing this in a wrong way please tell me I truly don't know what I should do, please someone answer me. I belive the problem in the action bar that I'm using in the TelaPrincial.class becuse the code works when there is no BottomNavigationView, or when I load the layout use it to load teh layout separately.
I'm using this video https://www.youtube.com/watch?v=QgfNl541oso&t=2449s
Home.java
package com.example.safe;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class Home extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
RecyclerView recview;
Adapter adapter;
public static Home newInstance(String param1, String param2) {
Home fragment = new Home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recview = view.findViewById(R.id.rvDenuncias);
recview.setLayoutManager(new LinearLayoutManager(getContext()));
Query query = FirebaseFirestore.getInstance()
.collection("Ocorrencias")
.limit(50);
FirestoreRecyclerOptions<Modelo> options = new FirestoreRecyclerOptions.Builder<Modelo>()
.setQuery(query, Modelo.class)
.build();
adapter = new Adapter(options);
recview.setAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
Modelo
package com.example.safe;
public class Modelo {
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
public Modelo() {
}
public Modelo(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSetor() {
return setor;
}
public void setSetor(String setor) {
this.setor = setor;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getRisco() {
return risco;
}
public void setRisco(String risco) {
this.risco = risco;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getPrazo() {
return prazo;
}
public void setPrazo(String prazo) {
this.prazo = prazo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getResolucao() {
return resolucao;
}
public void setResolucao(String resolucao) {
this.resolucao = resolucao;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
Adapter.class
package com.example.safe;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
//Vinculando o reclycler view ao firestore
public class Adapter extends FirestoreRecyclerAdapter<Modelo, Adapter.myviewholder> {
public Adapter(#NonNull FirestoreRecyclerOptions<Modelo> options) {
super(options);
}
//Sobrescrevendo o método
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Modelo model) {
//Associando os itens do atalho ocorrências
holder.IDText.setText(model.getID());
holder.tipoText.setText(model.getTipo());
Glide.with(holder.img1.getContext()).load(model.getImg()).into(holder.img1);
//Ação de entrar abrir a ocorrência
holder.RLAYOUT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
//importando as variáveis do Modelo e enviado para o DescDenun
model.getEmpresa(),
model.getArea(),
model.getSetor(),
model.getTipo(),
model.getRisco(),
model.getImg(),
model.getData(),
model.getPrazo(),
model.getDesc(),
model.getResolucao(),
model.getID()
)).addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view);
}
//Coneção do reclycler view com essa classe
public class myviewholder extends RecyclerView.ViewHolder {
//Variáveis do modelo atalho
TextView tipoText, IDText;
RelativeLayout RLAYOUT;
ImageView img1;
//Associando os objetos ao modelo atalho
public myviewholder(#NonNull View itemView) {
super(itemView);
tipoText = itemView.findViewById(R.id.txtTipo);
img1 = itemView.findViewById(R.id.imageView);
IDText = itemView.findViewById(R.id.txtModeloID);
RLAYOUT = itemView.findViewById(R.id.RLlayout);
}
}
}
TelaPrincial.class
package com.example.safe;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import com.example.safe.databinding.ActivityTelaPrincipalBinding;
public class TelaPrincipal extends AppCompatActivity {
private ActivityTelaPrincipalBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityTelaPrincipalBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.bottomNavigationView.setOnItemSelectedListener(item -> {
switch (item.getItemId()){
case R.id.Home:
reaplaceFragment(new Home());
break;
case R.id.Estatísticas:
reaplaceFragment(new Graph());
break;
case R.id.Denúncia:
reaplaceFragment(new Denuncia());
break;
case R.id.Perfil:
reaplaceFragment(new Perfil());
break;
case R.id.Config:
reaplaceFragment(new Config());
break;
}
return true;
});
}
private void reaplaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit();
}
}
Related
I am retrieving Cloud Firestore data in Modelo.class and I'm trying to pass these variables from the to fragment DescDenuncia using a adapter Adapter.class but to do that I need to get the context tfor it using the I've already tried use AppCompatActivity activity = (AppCompatActivity) view.getContext();, but my app crashes every time I run this line, and is necessary to use a Context in the getSupportFragmentManager() to it works. If i'm doing this in a wrong way please tell me I truly don't know what I should do, please someone answer me
I'm using this video https://www.youtube.com/watch?v=QgfNl541oso&t=2449s
Modelo.java
package com.example.safe;
public class Modelo {
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
public Modelo() {
}
public Modelo(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSetor() {
return setor;
}
public void setSetor(String setor) {
this.setor = setor;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getRisco() {
return risco;
}
public void setRisco(String risco) {
this.risco = risco;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getPrazo() {
return prazo;
}
public void setPrazo(String prazo) {
this.prazo = prazo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getResolucao() {
return resolucao;
}
public void setResolucao(String resolucao) {
this.resolucao = resolucao;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
Home.java
package com.example.safe;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class Home extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
RecyclerView recview;
Adapter adapter;
public static Home newInstance(String param1, String param2) {
Home fragment = new Home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recview = view.findViewById(R.id.rvDenuncias);
recview.setLayoutManager(new LinearLayoutManager(getContext()));
Query query = FirebaseFirestore.getInstance()
.collection("Ocorrencias")
.limit(50);
FirestoreRecyclerOptions<Modelo> options = new FirestoreRecyclerOptions.Builder<Modelo>()
.setQuery(query, Modelo.class)
.build();
adapter = new Adapter(options);
recview.setAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
Adapter.java
package com.example.safe;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
//Vinculando o reclycler view ao firestore
public class Adapter extends FirestoreRecyclerAdapter<Modelo, Adapter.myviewholder> {
public Adapter(#NonNull FirestoreRecyclerOptions<Modelo> options) {
super(options);
}
//Sobrescrevendo o método
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Modelo model) {
//Associando os itens do atalho ocorrências
holder.IDText.setText(model.getID());
holder.tipoText.setText(model.getTipo());
Glide.with(holder.img1.getContext()).load(model.getImg()).into(holder.img1);
//Ação de entrar abrir a ocorrência
holder.RLAYOUT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
///////////////////////////////////////THE PROBLEM IS HERE///////////////////////////////////////////
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
//importando as variáveis do Modelo e enviado para o DescDenun
model.getEmpresa(),
model.getArea(),
model.getSetor(),
model.getTipo(),
model.getRisco(),
model.getImg(),
model.getData(),
model.getPrazo(),
model.getDesc(),
model.getResolucao(),
model.getID()
)).addToBackStack(null).commit();
}
});
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view);
}
//Coneção do reclycler view com essa classe
public class myviewholder extends RecyclerView.ViewHolder {
//Variáveis do modelo atalho
TextView tipoText, IDText;
RelativeLayout RLAYOUT;
ImageView img1;
//Associando os objetos ao modelo atalho
public myviewholder(#NonNull View itemView) {
super(itemView);
tipoText = itemView.findViewById(R.id.txtTipo);
img1 = itemView.findViewById(R.id.imageView);
IDText = itemView.findViewById(R.id.txtModeloID);
RLAYOUT = itemView.findViewById(R.id.RLlayout);
}
}
}
DescDenuncia.java
package com.example.safe;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.firebase.firestore.FirebaseFirestore;
public class DescDenuncia extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
ImageButton bt_Voltar, bt_Manutencao;
FirebaseFirestore db = FirebaseFirestore.getInstance();
public DescDenuncia() {
}
public DescDenuncia(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public static DescDenuncia newInstance(String param1, String param2) {
DescDenuncia fragment = new DescDenuncia();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_desc_denuncia, container, false);
TextView EmprHolder = view.findViewById(R.id.txtDenunEmpr);
TextView AreaHolder = view.findViewById(R.id.txtDenunArea);
TextView SetorHolder = view.findViewById(R.id.txtDenunSetor);
TextView TipoHolder = view.findViewById(R.id.txtDenunTipo);
TextView RiscoHolder = view.findViewById(R.id.txtDenunRisco);
ImageView ImgDenun = view.findViewById(R.id.txtDenunImg);
TextView DataHolder = view.findViewById(R.id.txtDenunData);
TextView PrazoHolder = view.findViewById(R.id.txtDenunPrazo);
TextView DescHolder = view.findViewById(R.id.txtDesc);
TextView ResolHolder = view.findViewById(R.id.txtFeedback);
//Definindo os as variáveis para o valor
EmprHolder.setText(empresa);
AreaHolder.setText(area);
SetorHolder.setText(setor);
TipoHolder.setText(tipo);
RiscoHolder.setText(risco);
Glide.with(getContext()).load(img).into(ImgDenun);
DataHolder.setText(data);
PrazoHolder.setText(prazo);
DescHolder.setText(desc);
ResolHolder.setText(resolucao);
return view;
}
public void onBackPressed()
{
AppCompatActivity activity=(AppCompatActivity)getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,new Home()).addToBackStack(null).commit();
}
}
I have a problem with my android app.
I have a RecyclerView and a click handler for it. When you click on a list item, one of the class fields is displayed on the screen. Also inside there is a button, by clicking on which another class field should be displayed. But the program throws a NullPointerException. I understand why this is happening, but I cannot understand how to modify my code, please help.
here is my Adapeter
package com.skorbr.stock_yandextest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class TickerAdapter extends RecyclerView.Adapter<TickerAdapter.TickerViewHolder> {
private List<Ticker> tickers;
private Context context;
// listener
private final Listener onTickerClickListener;
// constructor
public TickerAdapter(List<Ticker> tickers, Listener onTickerClickListener) {
this.tickers = tickers;
this.onTickerClickListener = onTickerClickListener;
}
#NonNull
#Override
public TickerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_stock_item, parent, false);
// click on RecyclerView
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onTickerClick((Ticker) v.getTag());
}
});
// click on button
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
}
});
return new TickerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
}
#Override
public int getItemCount() {
return tickers.size();
}
class TickerViewHolder extends RecyclerView.ViewHolder {
private TextView ticker;
private TextView tickerFull;
private TextView price;
private TextView priceChange;
private ImageView tickerLogo;
private Button favouriteButton;
public TickerViewHolder(#NonNull final View itemView) {
super(itemView);
ticker = itemView.findViewById(R.id.ticker);
tickerFull = itemView.findViewById(R.id.ticker_full);
price = itemView.findViewById(R.id.price);
priceChange = itemView.findViewById(R.id.price_change);
tickerLogo = itemView.findViewById(R.id.ticker_image);
favouriteButton = itemView.findViewById(R.id.button_favourite);
}
// заполнение элемента RecyclerView данными
void bind(Ticker ticker) {
double priceNow = ticker.getPrice();
double priceDayAgo = ticker.getPriceDayAgo();
String sign = "";
this.ticker.setText(ticker.getTicker());
this.tickerFull.setText(ticker.getTickerFull());
this.price.setText("$" + priceNow);
// check price
if (priceNow < priceDayAgo) {
sign = "-";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorRedDm));
} else if (priceNow > priceDayAgo) {
sign = "+";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorGreenDm));
}
// check favourites
if (ticker.isFavourite()) {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_on));
} else {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_off));
}
this.priceChange.setText(String.format("%s$%.2f (%.2f%%)", sign, Math.abs(priceNow-priceDayAgo), Math.abs(priceNow/priceDayAgo*100-100)));
this.tickerLogo.setImageResource(ticker.getTickerLogo());
}
}
interface Listener {
void onTickerClick(Ticker ticker);
void onFavouriteClick(Ticker ticker);
}
}
Here is my Main Activity
package com.skorbr.stock_yandextest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ActivityMain extends Activity {
private RecyclerView tickerList;
private TickerAdapter tickerAdapter;
private List<Ticker> tickerListList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tickerListList = tickerList();
tickerList = findViewById(R.id.tickers_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
tickerList.setLayoutManager(layoutManager);
tickerAdapter = new TickerAdapter(tickerListList, new TickerAdapter.Listener() {
#Override
public void onTickerClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTickerFull(), Toast.LENGTH_SHORT);
}
#Override
public void onFavouriteClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTicker(), Toast.LENGTH_SHORT);
}
});
tickerList.setAdapter(tickerAdapter);
}
private List<Ticker> tickerList() {
List<Ticker> tickers = new ArrayList<>();
tickers.add(new Ticker("APPL", "Apple Inc.", 138.54, 150.22, R.drawable.apple_logo, false));
tickers.add(new Ticker("TSLA", "Tesla Motors", 904.37, 753.92, R.drawable.tesla_logo, true));
tickers.add(new Ticker("GOOGL", "Alphabel Class A", 1845.90, 1845.90, R.drawable.google_logo, false));
return tickers;
}
}
Here is my class for data
package com.skorbr.stock_yandextest;
public class Ticker {
private String ticker;
private String tickerFull;
private double price;
private double priceDayAgo;
private int tickerLogo;
private boolean isFavourite;
public Ticker(String ticker, String tickerFull, double price, double priceDayAgo, int tickerLogo, boolean isFavourite) {
this.ticker = ticker;
this.tickerFull = tickerFull;
this.price = price;
this.priceDayAgo = priceDayAgo;
this.tickerLogo = tickerLogo;
this.isFavourite = isFavourite;
}
public String getTicker() {
return ticker;
}
public String getTickerFull() {
return tickerFull;
}
public double getPrice() {
return price;
}
public double getPriceDayAgo() {
return priceDayAgo;
}
public int getTickerLogo() {
return tickerLogo;
}
public boolean isFavourite() {
return isFavourite;
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
// add this line
holder.favouriteButton.setTag(ticker);
}
Or you can modify the onCreateViewHolder()
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// instead of
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
// use
onTickerClickListener.onFavouriteClick((Ticker) view.getTag());
}
});
I can't seems to find the issue for the problem that i have encounter that is when i navigate to ResidenceFrag fragment it will stop working after i have implemented recycle view into it. It was working fine with just fragments but after i have implemented recycle view, the view doesn't work anymore. Below are my files. Thank you.
ResidenceFrag.java
package com.example.ezhome;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ResidenceFrag extends Fragment {
View v;
MHS mhs;
private RecyclerView recyclerView;
private ArrayList<Residence> resList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.residence_frag, container, false);
mhs = new MHS();
resList = mhs.getResidences();
Collections.sort(resList, new Comparator<Residence>(){
#Override
public int compare(Residence r1, Residence r2){
return r1.getName().compareTo(r2.getName());
}
});
recyclerView = (RecyclerView) v.findViewById(R.id.rvItems);
ViewResidenceAdapter adapter = new ViewResidenceAdapter(getContext(),resList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
}
MHS.java
package com.example.ezhome;
import java.util.ArrayList;
public class MHS {
public ArrayList<Residence> residences;
public Applicant applicant;
public MHS() {
setResidences(new ArrayList<Residence>());
residences.add(new Residence("ResB","A_address123",12,200,300,"micro1.jpg"));
residences.add(new Residence("ResA","B_address123",17,228,390,"micro2.jpg"));
}
public void submitApp(Application app){
applicant.addApplication(app);
}
public ArrayList<Residence> getResidences() {
return residences;
}
public void setResidences(ArrayList<Residence> residences) {
this.residences = residences;
}
}
Residence.java
package com.example.ezhome;
import java.util.ArrayList;
public class Residence {
private static int nextResidenceID = 1;
private String residenceID, address;
private int numUnits, i;
private double sizePerUnit, monthlyRental;
private ArrayList<Unit> units;
private String name;
private String image;
public Residence(String name, String address, int numUnits, double sizePerUnit, double monthlyRental, String image) {
setName(name);
setAddress(address);
setNumUnits(numUnits);
setSizePerUnit(sizePerUnit);
setMonthlyRental(monthlyRental);
setResidenceID();
setImage(image);
// setUnits(new ArrayList<Unit>());
// for(i = 0; i < numUnits; i++){
// Unit unit = new Unit(this);
// }
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static int getNextResidenceID() {
return nextResidenceID;
}
public static void setNextResidenceID(int nextResidenceID) {
Residence.nextResidenceID = nextResidenceID;
}
public String getResidenceID() {
return residenceID;
}
public void setResidenceID() {
this.residenceID = String.format("RES" + nextResidenceID++);
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumUnits() {
return numUnits;
}
public void setNumUnits(int numUnits) {
this.numUnits = numUnits;
}
public double getSizePerUnit() {
return sizePerUnit;
}
public void setSizePerUnit(double sizePerUnit) {
this.sizePerUnit = sizePerUnit;
}
public double getMonthlyRental() {
return monthlyRental;
}
public void setMonthlyRental(double monthlyRental) {
this.monthlyRental = monthlyRental;
}
public ArrayList<Unit> getUnits() {
return units;
}
public void setUnits(ArrayList<Unit> units) {
this.units = units;
}
public void addUnit(Unit unit) {
getUnits().add(unit);
}
}
ViewResidenceAdapter.java
package com.example.ezhome;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class ViewResidenceAdapter extends RecyclerView.Adapter<ViewResidenceAdapter.ViewHolder>{
private ArrayList<Residence> resList;
private Context context;
public ViewResidenceAdapter(Context context, ArrayList<Residence> resList){
this.context = context;
this.resList = resList;
}
#Override
public ViewResidenceAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View inflater = LayoutInflater.from(context).inflate(R.layout.customlayout, parent, false);
ViewHolder viewHolder = new ViewHolder(inflater);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewResidenceAdapter.ViewHolder holder, int position) {
Residence res = resList.get(position);
try{
holder.nameTextView.setText(res.getName());
holder.sizeTextView.setText(res.getSizePerUnit() + " sqft");
holder.addressTextView.setText(res.getAddress());
holder.monthlyRentalTextView.setText("RM " + res.getMonthlyRental() + "/month");
holder.applyButton.setTag(res.getResidenceID());
String imageFile = res.getImage();
InputStream inputStream = context.getAssets().open(imageFile);
Drawable d = Drawable.createFromStream(inputStream, null);
holder.resImg.setImageDrawable(d);
} catch (IOException e){
e.printStackTrace();
}
}
public int getItemCount() {
return resList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public TextView sizeTextView;
public TextView addressTextView;
public TextView monthlyRentalTextView;
public ImageView resImg;
public Button applyButton;
public ViewHolder (View itemView){
super(itemView);
nameTextView = (TextView)itemView.findViewById(R.id.nameTextView);
sizeTextView = (TextView)itemView.findViewById(R.id.sizeTextView);
addressTextView = (TextView)itemView.findViewById(R.id.addressTextView);
monthlyRentalTextView = (TextView)itemView.findViewById(R.id.monthlyRentalTextView);
resImg = (ImageView)itemView.findViewById(R.id.resImg);
applyButton = (Button)itemView.findViewById(R.id.applyButton);
}
}
}
MainActivity.java
package com.example.ezhome;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.nav_drawer_open, R.string.nav_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFrag()).commit();
navigationView.setCheckedItem(R.id.nav_home);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.nav_home){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFrag()).commit();
} else if (item.getItemId() == R.id.nav_res){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ResidenceFrag()).commit();
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Solved: drawable image v24 issue
I want to display a bunch of custom markers(IconGenerator from com.google.maps.android:android-maps-utils:0.5) in a google map. But the data to build the markers, the LatLong location are in a firebase database, each child has its own location values, how can I read the location of each child and pass it to the class that will display the markers?
package com.realty.drake.kunuk;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Keep;
import com.google.android.gms.maps.model.LatLng;
/**
* Created by drake on 5/1/18.
* This class is the model class
*/
#Keep
public class Property implements Parcelable {
private int price;
private String address;
private int numberOfBed;
private int numberOfBath;
private int numberOfCar;
private String propertyImage;
private float lotDim;
private String propertyDesc;
private float propertyDim;
private String lotTerrainType;
private String lotTerrainDimExt;
private String lotTerrainSteepness;
private LatLng location;
public Property() { } //Needed for Firebase's auto data mapping
public Property(int price, String address, int numberOfBed, int numberOfBath,
int numberOfCar, String propertyImage, float lotDim,
String propertyDesc, float propertyDim, String lotTerrainType,
String lotTerrainDimExt, String lotTerrainSteepness,
LatLng location) {
this.price = price;
this.address = address;
this.numberOfBed = numberOfBed;
this.numberOfBath = numberOfBath;
this.numberOfCar = numberOfCar;
this.propertyImage = propertyImage;
this.lotDim = lotDim;
this.propertyDesc = propertyDesc;
this.propertyDim = propertyDim;
this.lotTerrainType = lotTerrainType;
this.lotTerrainDimExt = lotTerrainDimExt;
this.lotTerrainSteepness = lotTerrainSteepness;
this.location = location;
}
protected Property(Parcel in) {
price = in.readInt();
address = in.readString();
numberOfBed=in.readInt();
numberOfBath = in.readInt();
numberOfCar = in.readInt();
propertyImage = in.readString();
lotDim = in.readFloat();
propertyDesc = in.readString();
propertyDim = in.readFloat();
lotTerrainType = in.readString();
lotTerrainDimExt = in.readString();
lotTerrainSteepness = in.readString();
location = in.readParcelable(getClass().getClassLoader());
}
public static final Creator<Property> CREATOR = new Creator<Property>() {
#Override
public Property createFromParcel(Parcel in) {
return new Property(in);
}
#Override
public Property[] newArray(int i) {
return new Property[i];
}
};
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumberOfBed() {
return numberOfBed;
}
public void setNumberOfBed(int numberOfBed) {
this.numberOfBed = numberOfBed;
}
public int getNumberOfBath() {
return numberOfBath;
}
public void setNumberOfBath(int numberOfBath) {
this.numberOfBath = numberOfBath;
}
public int getNumberOfCar() {
return numberOfCar;
}
public void setNumberOfCar(int numberOfCar) {
this.numberOfCar = numberOfCar;
}
public String getPropertyImage() {
return propertyImage;
}
public void setPropertyImage(String propertyImage) {
this.propertyImage = propertyImage;
}
public float getLotDim() {
return lotDim;
}
public void setLotDim(float lotDim) {
this.lotDim = lotDim;
}
public String getPropertyDesc() {
return propertyDesc;
}
public void setPropertyDesc(String propertyDesc) {
this.propertyDesc = propertyDesc;
}
public float getPropertyDim() {
return propertyDim;
}
public void setPropertyDim(float propertyDim) {
this.propertyDim = propertyDim;
}
public String getLotTerrainType() {
return lotTerrainType;
}
public void setLotTerrainType(String lotTerrainType) {
this.lotTerrainType = lotTerrainType;
}
public String getLotTerrainDimExt() {
return lotTerrainDimExt;
}
public void setLotTerrainDimExt(String lotTerrainDimExt) {
this.lotTerrainDimExt = lotTerrainDimExt;
}
public String getLotTerrainSteepness() {
return lotTerrainSteepness;
}
public void setLotTerrainSteepness(String lotTerrainSteepness) {
this.lotTerrainSteepness = lotTerrainSteepness;
}
public LatLng getLocation() {
return location;
}
public void setLocation(LatLng location) {
this.location = location;
}
#Override
public int describeContents(){
return 0;
}
#Override
public void writeToParcel( Parcel dest, int flags){
dest.writeInt(price);
dest.writeString(address);
dest.writeInt(numberOfBed);
dest.writeInt(numberOfBath);
dest.writeInt(numberOfCar);
dest.writeString(propertyImage);
dest.writeFloat(lotDim);
dest.writeString(propertyDesc);
dest.writeFloat(propertyDim);
dest.writeString(lotTerrainType);
dest.writeString(lotTerrainDimExt);
dest.writeString(lotTerrainSteepness);
dest.writeParcelable(location,flags);
}
}
The Fragment that use the model class, it takes data from firebase database, and also has anintent to a detailed view
package com.realty.drake.kunuk;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CircularProgressDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Created by drake on 4/11/18
*/
public class Tab1Buy extends Fragment {
private DatabaseReference propertyRef;
private RecyclerView mPropertyRecyclerView;
FirebaseRecyclerAdapter<Property, PropertyViewHolder> mPropertyAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.property_tab, container, false);
mPropertyRecyclerView = rootView.findViewById(R.id.property_recyclerView);
return rootView;
}
//TODO Check internet and display error msg if internet down
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPropertyRecyclerView.hasFixedSize();
mPropertyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final ProgressBar progressBar = view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
propertyRef = FirebaseDatabase.getInstance()
.getReference()
.child("Buy");
propertyRef.keepSynced(true);
// keyQuery - the Firebase location containing the list of keys to be found in dataRef
//Query personQuery = propertyRef.orderByKey();
FirebaseRecyclerOptions<Property> options =
new FirebaseRecyclerOptions.Builder<Property>()
.setQuery(propertyRef, Property.class)
.build();
mPropertyAdapter = new FirebaseRecyclerAdapter<Property, PropertyViewHolder>(options) {
#Override
// Bind the Property object to the ViewHolder PropertyHolder
public void onBindViewHolder(#NonNull PropertyViewHolder holder,
final int position, #NonNull final Property model) {
holder.setPrice(model.getPrice());
holder.setAddress(model.getAddress());
holder.setNumberOfBed(model.getNumberOfBed());
holder.setNumberOfBath(model.getNumberOfBath());
holder.setNumberOfCar(model.getNumberOfCar());
holder.setPropertyImage(model.getPropertyImage());
//This Intent send Parcelable from Property to PropertyDetail
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().startActivity(new Intent(getActivity(), PropertyDetail.class)
.putExtra("Property", model));
}
});
}
#Override
public PropertyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.property_card for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.property_card, parent, false);
return new PropertyViewHolder(view);
}
#Override
public void onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
progressBar.setVisibility(View.GONE);
}
//TODO Implement onError
#Override
public void onError(#NonNull DatabaseError e) {
// Called when there is an error getting data. You may want to update
// your UI to display an error message to the user.
// ...
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "DatabaseError", Toast.LENGTH_SHORT).show();
}
};
mPropertyRecyclerView.setAdapter(mPropertyAdapter);
}
#Override
public void onStart() {
super.onStart();
mPropertyAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
mPropertyAdapter.stopListening();
}
public class PropertyViewHolder extends RecyclerView.ViewHolder {
View mView;
public PropertyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPrice(int price) {
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView Price = mView.findViewById(R.id.post_price);
Price.setText(currencyPrice);
}
public void setAddress(String address){
TextView Address = mView.findViewById(R.id.post_address);
Address.setText(String.valueOf(address));
}
public void setNumberOfBed(int numberOfBed){
TextView NumberOfBed = mView.findViewById(R.id.post_bedroom);
NumberOfBed.setText(String.valueOf(numberOfBed));
}
public void setNumberOfBath(int numberOfBath){
TextView NumberOfBath = mView.findViewById(R.id.post_bathroom);
NumberOfBath.setText(String.valueOf(numberOfBath));
}
public void setNumberOfCar(int numberOfCar) {
TextView NumberOfCar = mView.findViewById(R.id.post_garage);
NumberOfCar.setText(String.valueOf(numberOfCar));
}
public void setPropertyImage(String propertyImage){
ImageView imageView = mView.findViewById(R.id.post_propertyImage);
//take one long string containing multiple url in and parse it
String propertyImageArray[] = propertyImage.split(",");
//Loading circle for placeholder, ColorAccent has been used
CircularProgressDrawable progressDrawable =
new CircularProgressDrawable(getContext());
progressDrawable.setStrokeWidth(5f);
progressDrawable.setCenterRadius(30f);
progressDrawable.setColorSchemeColors(Color.argb(1,255,145,0));
progressDrawable.start();
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getContext())
.load(propertyImageArray[0])
.placeholder(progressDrawable)
.fitCenter()
.into(imageView);
}
}
}
The detailed activity which is called by an intent from Tab1Buy
package com.realty.drake.kunuk;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.MenuItem;
import android.widget.Toast;
import java.text.NumberFormat;
import java.util.Locale;
public class PropertyDetail extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.property_detail);
Toolbar myToolbar = (Toolbar) findViewById(R.id.kunuk_toolbar);
myToolbar.inflateMenu(R.menu.menu_detail);
setSupportActionBar(myToolbar);
myToolbar.setOnMenuItemClickListener(this);
//collect our intent
Intent intent = getIntent();
Property property = intent.getParcelableExtra("Property");
boolean isRent = getIntent().getBooleanExtra("isRent", false);
//collect all property values from Parcelable
int price = property.getPrice();
String address = property.getAddress();
int numberOfBed = property.getNumberOfBed();
int numberOfBath = property.getNumberOfBath();
int numberOfCar = property.getNumberOfCar();
String propertyImage = property.getPropertyImage();
float propertyDim = property.getPropertyDim();
String propertyDesc = property.getPropertyDesc();
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_call:
Uri callNumberUri = Uri.parse("tel:+50937438713");
Intent callIntent = new Intent(Intent.ACTION_DIAL, callNumberUri);
startActivity(callIntent);
break;
case R.id.action_sms:
Uri smsNumberUri = Uri.parse("sms:+50937438713");
Intent smsIntent = new Intent(Intent.ACTION_SENDTO, smsNumberUri);
startActivity(smsIntent);
break;
case R.id.action_email:
//TODO get a property id to use in subject email field
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Kunuk Request");
emailIntent.putExtra(Intent.EXTRA_EMAIL,
new String[] {"drakecolinj#gmail.com"});
startActivity(emailIntent);
}
return false;
}
});
//Bind the data from the Parcelable to the Views
TextView addressDetail = findViewById(R.id.post_address);
addressDetail.setText(String.valueOf(address));
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView priceDetail = findViewById(R.id.post_price);
priceDetail.setText(currencyPrice);
ImageView imageView = findViewById(R.id.post_propertyImage);
//take one long string containing multiple url and parse it
String propertyImageArray[] = propertyImage.split(",");
//TODO add loading icon for placeholder
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getApplication())
.load(propertyImageArray[0])
.fitCenter()
.into(imageView);
TextView bathroomDetail = findViewById(R.id.post_bathroom);
bathroomDetail.setText(String.valueOf(numberOfBath));
TextView bedroomDetail = findViewById(R.id.post_bedroom);
bedroomDetail.setText(String.valueOf(numberOfBed));
TextView garageDetail = findViewById(R.id.post_garage);
garageDetail.setText(String.valueOf(numberOfCar));
TextView propertyDimDetail = findViewById(R.id.property_dim);
propertyDimDetail.setText(String.valueOf(propertyDim));
TextView propertyDescDetail = findViewById(R.id.property_desc);
propertyDescDetail.setText(String.valueOf(propertyDesc));
if (isRent) {
final TextView rentUnit = findViewById(R.id.rent_unit_detail);
rentUnit.setVisibility(View.VISIBLE);
}
}
#Override
public boolean onMenuItemClick(MenuItem item){
switch (item.getItemId()) {
case R.id.action_share:
Toast.makeText(this, "Shared", Toast.LENGTH_SHORT).show();
return true;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
}
In Child "Buy", each of its child has its own location key and the same for Rent and Lot.
Please help, conceptual explanation and code please
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Buy");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// Let us retrieve value of location
Log.i("Price", dataSnapshot.child("location").getValue().toString());
// In this way you can retrieve all the fileds.
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Similarly for Rent & Lot you can pass as -
DatabaseReference dbRent = FirebaseDatabase.getInstance().getReference("Rent");
DatabaseReference dbLot = FirebaseDatabase.getInstance().getReference("Lot");
I hope this will helps!
My code was worked perfectly just before i added header image, after that listview not showing the given datas.
These are the main pages.
Can anyone help please.Any help will be appreciated.
MyRecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyRecyclerViewAdapter extends
RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
Context context;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public MyRecyclerViewAdapter(String[] data) {
this.data = data;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView desc;
ImageView image,head_img;
public DataObjectHolder(View itemView) {
super(itemView);
desc = (TextView) itemView.findViewById(R.id.description);
image = (ImageView) itemView.findViewById(R.id.image);
head_img=(ImageView) itemView.findViewById(R.id.header_img);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
this.mDataset = myDataset;
this.context=context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType==TYPE_ITEM) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
else if (viewType==TYPE_HEADER){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
if(holder instanceof VHItem) {
holder.desc.setText(mDataset.get(position ).getDescription());
// holder.image.setText(mDataset.get(position).getImage_url());
Picasso.with(holder.image.getContext()).load(mDataset.get(position ).getImage_url()).into(holder.image);
}
else if(holder instanceof VHHeader){
holder.head_img.setImageResource(R.drawable.cam);
}
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return (null != mDataset ? mDataset.size() + 1 : 0);
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private class VHItem extends DataObjectHolder {
public VHItem(View itemView) {
super(itemView);
}
}
private class VHHeader extends DataObjectHolder {
public VHHeader(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
}
Profile2Fragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Profile2Fragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.recycler_view, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
return rootview;
}
private ArrayList<DataObject> getDataSet() {
ArrayList<DataObject> results = new ArrayList<DataObject>();
for (int index = 0; index < 1; index++) {
DataObject obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://mediastream.jumeirah.com/webimage/heroactual//globalassets/global/hotels-and-resorts/dubai/madinat-jumeirah/restaurants/pierchic/madinat-jumeirah-pierchic-inside-restaurant-02-hero.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://photos.smugmug.com/Portfolio/i-HBk894k/0/db7f0344/L/The%20Black%20Couches-L.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "http://thesmartlocal.com/images/easyblog_images/82/Pollen.jpg");
results.add(obj);
}
return results;
}
}
DataObject.java
public class DataObject {
private String description;
private String image_url;
DataObject (String text1, String text2){
description = text1;
image_url = text2;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
try to change return statement
`return new DataObjectHolder(view);
to your specific Class like return
new VHHeader(view);
and
return new VHItem(view);
in onCreateViewHolder..