Populate details activity with Firebase Real Time Database after click on RecyclerView - java

i want to click in my recyclerview and open a new activity to show the datails. Ultil now i
have accomplished to open the activity and show the values "interno" and "siniiga" with the next intent. how can i get "madre and padre" values from firebase? applying the method to add father and mother, then I will use it for the rest of the values ​​that the xml shows. excuse my horrible code. if someone know a different method, let me know
attached code and images.
Main Activity
RecyclerView rv;
List<cow> vacas;
adapter adapter;
ImageButton mbuttoninf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.recyclerViewGirdView);
rv.setLayoutManager(new LinearLayoutManager(this));
vacas = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new adapter(vacas);
rv.setAdapter(adapter);
database.getReference("Vacas").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
vacas.removeAll(vacas);
for (DataSnapshot snapshot1 :
snapshot.getChildren()) {
cow vaca = snapshot1.getValue(cow.class);
vacas.add(vaca);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
cow
String interno;
String siniiga;
String ulr;
String madre;
String padre;
public cow() {
}
public cow(String interno, String siniiga, String ulr, String madre, String padre) {
this.interno = interno;
this.siniiga = siniiga;
this.ulr = ulr;
this.madre = madre;
this.padre = padre;
}
public String getInterno() {
return interno;
}
public void setInterno(String interno) {
this.interno = interno;
}
public String getSiniiga() {
return siniiga;
}
public void setSiniiga(String siniiga) {
this.siniiga = siniiga;
}
public String getUlr() {
return ulr;
}
public void setUlr(String ulr) {
this.ulr = ulr;
}
public String getMadre() {
return madre;
}
public void setMadre(String madre) {
this.madre = madre;
}
public String getPadre() {
return padre;
}
public void setPadre(String padre) {
this.padre = padre;
}
}
Adapter
List<cow> vacas;
Context context;
public adapter(List<cow> vacas) {
this.vacas = vacas;
}
#NonNull
#Override
public cowviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaca,parent,false);
cowviewHolder holder = new cowviewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final cowviewHolder holder, final int position) {
final cow vacaslist = vacas.get(position);
holder.textViewinterno.setText(String.valueOf(vacaslist.interno));
holder.textViewsiniiga.setText(String.valueOf(vacaslist.siniiga));
Glide.with(holder.imageviewrec.getContext()).load(vacaslist.getUlr()).into(holder.imageviewrec);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(v.getContext(),detailactivity.class);
intent.putExtra("keyint", vacaslist.getInterno());
intent.putExtra("keysin", vacaslist.getSiniiga());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return vacas.size();
}
public static class cowviewHolder extends RecyclerView.ViewHolder {
TextView textViewinterno, textViewsiniiga, tvmadre, tvpadre;
ImageView imageviewrec;
public cowviewHolder(#NonNull View itemView) {
super(itemView);
textViewinterno = itemView.findViewById(R.id.interno);
textViewsiniiga = itemView.findViewById(R.id.siniiga);
imageviewrec = itemView.findViewById(R.id.imgrec);
tvmadre = itemView.findViewById(R.id.tvmadre);
tvpadre = itemView.findViewById(R.id.tvpadre);
}
}
detailsactivity
TextView textView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.informationfire);
TextView tvinterno = (TextView) findViewById(R.id.tvinterno);
TextView tvsiniiga = (TextView) findViewById(R.id.tvsiniiga);
String vinterno = "";
String vsiniiga = "";
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
}
}
firebase
enter image description here
and the xml for details
enter image description here

when you are getting data from firebase you saving that data in a Object and then add that object to list, so your list contains objects , so you can pass through the intents same way as you are doing others.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(v.getContext(),detailactivity.class);
intent.putExtra("keyint", vacaslist.getInterno());
intent.putExtra("keysin", vacaslist.getSiniiga());
intent.putExtra("madre", vacaslist.getMadre());
intent.putExtra("padre", vacaslist.getPadre());
v.getContext().startActivity(intent);
}
});

Related

RecyclerView crashes when I update data to Firestore

I'm showing data from a Firebase Firestore collection, the app worked fine while but when I update data to the collection from other device (I got an Arduino with sensors connected to a PC that executes a Python script to transform the serial data to JSON and then I update that data on the Firestore collection, all the back end of these functionality works perfectly. My problem it's the Java on Android.
I already search for solutions on this forum and It seems like something doesn't work with the Adapter, the RecyclerView and the "notifyDataSetChanged();" None of the current solutions worked for me or maybe I just don't know how to implement them on my project.
This is my model
public class Monitor {
String alias, placa, temp, acid;
public Monitor(){}
public Monitor(String alias, String placa, String temp, String acid) {
this.alias = alias;
this.placa = placa;
this.temp = temp;
this.acid = acid;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getAcid() {
return acid;
}
public void setAcid(String acid) {
this.acid = acid;
}
}
The adapter
public class MonitorAdapter extends FirestoreRecyclerAdapter<Monitor, MonitorAdapter.ViewHolder> {
private FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
Activity activity;
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public MonitorAdapter(#NonNull FirestoreRecyclerOptions<Monitor> options, Activity activity) {
super(options);
this.activity = activity;
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Monitor model) {
DocumentSnapshot documentSnapshot = getSnapshots().getSnapshot(holder.getAbsoluteAdapterPosition());
final String id = documentSnapshot.getId();
holder.alias.setText(model.getAlias());
holder.temp.setText(model.getTemp());
holder.acid.setText(model.getAcid());
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(activity, VincularPlaca.class);
i.putExtra("id_placa",id);
activity.startActivity(i);
}
});
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_monitor_single,parent,false);
return new ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView alias, temp, acid;
Button btn_edit;
public ViewHolder(#NonNull View itemView) {
super(itemView);
alias = itemView.findViewById(R.id.alias);
temp = itemView.findViewById(R.id.temp);
acid = itemView.findViewById(R.id.acid);
btn_edit = itemView.findViewById(R.id.btn_edit);
}
}
}
And my MainActivity
public class MainActivity extends AppCompatActivity {
Button btn_add, btn_exit;
RecyclerView mRecycler;
MonitorAdapter mAdapter;
FirebaseFirestore mFirestore;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestore = FirebaseFirestore.getInstance();
mRecycler = findViewById(R.id.recyclerViewSingle);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
Query query = mFirestore.collection("dispositivos");
FirestoreRecyclerOptions<Monitor> firestoreRecyclerOptions =
new FirestoreRecyclerOptions.Builder<Monitor>().setQuery(query,Monitor.class).build();
mAdapter = new MonitorAdapter(firestoreRecyclerOptions, this);
mAdapter.notifyDataSetChanged();
mRecycler.setAdapter(mAdapter);
btn_add = findViewById(R.id.btn_add);
btn_exit = findViewById(R.id.btn_close);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,VincularPlaca.class));
}
});
btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,LoginActivity.class));
mAuth.signOut();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mAdapter.stopListening();
}
}
class ExampleViewModel : ViewModel() {
var mFirestore : FirebaseFirestore? = null
private val _list = MutableLiveData<FirestoreRecyclerOptions<Monitor>>()
val list: LiveData<FirestoreRecyclerOptions<Monitor>> = _list
init{
mFirestore = FirebaseFirestore.getInstance()
list.value= FirestoreRecyclerOptions.Builder<Monitor>().setQuery(mFirestore!!.collection("dispositivos"),Monitor::class.java).build()
}
}
The problem has solved fixing the AndroidManifest Permissions and outside the code on the Firebase Firestore console, the attribute was supose to be an string but it recieves an int.

Data from Firebase is not displayed in the RecyclerView that is in the fragment

There is a problem with the data displayed in the recyclerview when I run my program
it looks like this:
.
For the data that is displayed I use firebase like this the
data structure:
When I want to display data in recyclerview in a fragment, but the data doesn't appear. I use Firebase as database
NotaAdapter.java
public class NotaAdapter extends RecyclerView.Adapter<NotaAdapter.MyViewHolder> {
Context context;
ArrayList<ListNota> listnota;
public NotaAdapter (Context c,ArrayList<ListNota> p) {
this.context = c;
this.listnota = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
return new MyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.item_nota, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.no_nota.setText(listnota.get(i).getId_nota());
myViewHolder.total_harga.setText(String.valueOf(listnota.get(i).getTotal_seluruh()));
final String getnoNOta = listnota.get(i).getId_nota();
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoDetailNota = new Intent(context, DetailNotaAct.class);
gotoDetailNota.putExtra("no_nota", getnoNOta);
context.startActivity(gotoDetailNota);
}
});
}
#Override
public int getItemCount() {
return listnota.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView no_nota, total_harga;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
no_nota = itemView.findViewById(R.id.xid_nota);
total_harga = itemView.findViewById(R.id.xtotal_seluruh);
}
}
}
ListNota.java
public class ListNota {
private String id_nota;
private Integer total_seluruh;
public ListNota() {
}
public ListNota(String id_nota, Integer total_seluruh) {
this.id_nota = id_nota;
this.total_seluruh = total_seluruh;
}
public String getId_nota() {
return id_nota;
}
public void setId_nota(String id_nota) {
this.id_nota = id_nota;
}
public Integer getTotal_seluruh() {
return total_seluruh;
}
public void setTotal_seluruh(Integer total_seluruh) {
this.total_seluruh = total_seluruh;
}
}
HistoryFragment.java
public class HistoryFragment extends Fragment {
TextView txt_history, txt_toko, txt_report, txt_nama_toko, txt_jenis_toko;
LinearLayout btn_buat_nota;
DatabaseReference databaseUser, databaseToko, databaseNota;
String USERNAME_KEY = "usernamekey";
String username_key = "";
String username_key_new = "";
String id_Toko = "";
ProgressDialog progress;
RecyclerView nota_place;
ArrayList<ListNota> list;
NotaAdapter notaAdapter;
private View Notaview;
public HistoryFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Notaview = inflater.inflate(R.layout.fragment_history, container, false);
txt_nama_toko = (TextView) Notaview.findViewById(R.id.txt_nama_toko);
txt_jenis_toko = (TextView) Notaview.findViewById(R.id.txt_jenis_toko);
txt_history = (TextView) Notaview.findViewById(R.id.txt_history);
txt_toko = (TextView) Notaview.findViewById(R.id.txt_toko);
txt_report = (TextView) Notaview.findViewById(R.id.txt_report);
btn_buat_nota = (LinearLayout) Notaview.findViewById(R.id.btn_buat_nota);
progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Memuat Data");
progress.setCancelable(false);
progress.show();
getUsernameLocal();
databaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(username_key_new);
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
id_Toko = dataSnapshot.child("id_toko").getValue().toString();
databaseToko = FirebaseDatabase.getInstance().getReference().child("Toko").child(id_Toko);
databaseToko.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
txt_nama_toko.setText(dataSnapshot.child("nama_toko").getValue().toString());
//cek apakah child jenis toko ada
if (dataSnapshot.hasChild("jenis_toko")){
txt_jenis_toko.setText(dataSnapshot.child(" jenis_toko").getValue().toString());
}else{
txt_jenis_toko.setText("Jenis toko belum disetting");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn_buat_nota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id_nota = generateRandomString(16);
Intent gotoBuatNota = new Intent(getActivity(), BuatNotaAct.class);
gotoBuatNota.putExtra("id_nota", id_nota);
startActivity(gotoBuatNota);
}
});
nota_place = (RecyclerView) Notaview.findViewById(R.id.nota_place);
notaAdapter = new NotaAdapter(getContext(), list);
nota_place.setAdapter(notaAdapter);
nota_place.setLayoutManager(new LinearLayoutManager(getActivity()));
return Notaview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<ListNota>();
loaddata();
}
private void loaddata(){
databaseNota = FirebaseDatabase.getInstance().getReference().child("Nota").child(id_Toko);
databaseNota.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
ListNota p = dataSnapshot1.getValue(ListNota.class);
list.add(p);
}
progress.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public String generateRandomString(int length){
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for(int i = 0; i < length; i++){
char c = chars[random.nextInt(chars.length)];
stringBuilder.append(c);
}
return stringBuilder.toString();
}
public void getUsernameLocal(){
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
username_key_new = sharedPreferences.getString(username_key,"");
}
}
you are reading it from the wrong node, you are passing reference that you want to read data from the node Named "users".
Your Database reference should look like this
databaseUser = FirebaseDatabase.getInstance().getReference("Nota").child("Toko_Kita20082020371").child(username_key_new);
Also make sure your list should have all the variables that a node has.
For example a node has
name,id,price,description;
then same varibles should be declared in your list to successfully ready dta from the firebase.

attempt to display details in another Activity "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"

I'm trying to use OnItemClick to display details in a user profile page and I still have this error:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at fr.ousoft.suiviemedsbox.ScrollingActivity.OnItemClick(**ScrollingActivity.java:102**)
at fr.ousoft.suiviemedsbox.UsersAdapter$AdapterVH$1.onClick(**UsersAdapter.java:115**)
Here is my Activity code
public class ScrollingActivity extends AppCompatActivity implements UsersAdapter.OnItemClickListener {
public static final String EXTRA_CREATOR_NOM = "Nom";
public static final String EXTRA_CREATOR_PRENOM = "Prenom";
public static final String EXTRA_CREATOR_TEL = "Tel";
public static final String EXTRA_CREATOR_EMAIL = "Email";
public static final String EXTRA_CREATOR_ETABLISSEMENT = "Etablissement";
public static final String EXTRA_CREATOR_TYPE = "Type";
public static final String EXTRA_CREATOR_ACTIVE = "Active";
RecyclerView recyclerView;
ApiInterface apiInterface;
UsersAdapter usersAdapter;
ArrayList<User> mListe = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolBarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolBarLayout.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ScrollingActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerViewList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
usersAdapter = new UsersAdapter();
fetchUsers();
}
public void fetchUsers(){
apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<List<User>> call = apiInterface.getAllUsers();
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()){
List<User> users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.e("success", t.getLocalizedMessage());
}
});
}
#Override
public void OnItemClick(int position) {
Intent detailIntent = new Intent(this,DetailActivity.class);
User clickedUser = mListe.get(position);
detailIntent.putExtra(EXTRA_CREATOR_NOM, clickedUser.getNom());
detailIntent.putExtra(EXTRA_CREATOR_PRENOM, clickedUser.getPrenom());
detailIntent.putExtra(EXTRA_CREATOR_TEL, clickedUser.getTel());
detailIntent.putExtra(EXTRA_CREATOR_EMAIL, clickedUser.getEmail());
detailIntent.putExtra(EXTRA_CREATOR_ETABLISSEMENT, clickedUser.getEtablissement());
detailIntent.putExtra(EXTRA_CREATOR_TYPE, clickedUser.getType());
detailIntent.putExtra(EXTRA_CREATOR_ACTIVE, clickedUser.getActive());
startActivity(detailIntent);
}
}
Adapter:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.AdapterVH>{
private List<User> userList;
private Context context;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void OnItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public UsersAdapter(){
}
public void setData(List<User> userList){
this.userList = userList;
notifyDataSetChanged();
}
#NonNull
#Override
public AdapterVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
return new UsersAdapter.AdapterVH(LayoutInflater.from(context).inflate(R.layout.item_list,parent,false));
}
#SuppressLint("ResourceAsColor")
#Override
public void onBindViewHolder(#NonNull AdapterVH holder, int position) {
User user = userList.get(position);
String nom = user.getNom();
String email = user.getEmail();
String etab = user.getEtablissement();
String active = user.getActive();
String prenom = user.getPrenom();
holder.txtNom.setText(nom);
if (nom == null) {
holder.txtNom.setText("Aucun Nom");
}
holder.txtEmail.setText(email);
if (email == null) {
holder.txtEmail.setText("Aucun Email");
}
holder.txtEttab.setText(etab);
if (etab == null) {
holder.txtEttab.setText("Aucun Etablissement");
}
holder.txtPrenom.setText(prenom);
if (prenom == null) {
holder.txtPrenom.setText("Aucun Prenom");
}
if (active == null) {
holder.ActiveDesactive.setText(R.string.desact);
}else {
holder.ActiveDesactive.setText(R.string.activ);
}
}
#Override
public int getItemCount() {
return userList.size();
}
public class AdapterVH extends RecyclerView.ViewHolder{
TextView txtNom;
TextView txtPrenom;
TextView txtEmail;
TextView txtEttab;
Button ActiveDesactive;
public AdapterVH(#NonNull View itemView) {
super(itemView);
txtNom = itemView.findViewById(R.id.NomUser);
txtPrenom = itemView.findViewById(R.id.PrenomUser);
txtEmail = itemView.findViewById(R.id.EmailUser);
txtEttab = itemView.findViewById(R.id.EtabUser);
ActiveDesactive = itemView.findViewById(R.id.ActiveDesavtive);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int positions = getAdapterPosition();
if (positions != RecyclerView.NO_POSITION){
mListener.OnItemClick(positions);
}
}
}
});
}
}
}
You never fill mListe with any content. If you search for mListe. the only match you get is mListe.get. You have no invocations of mListe.add or mListe.addAll. What you do instead is set a list from a response directly into the adapter:
if (response.isSuccessful()){
// Here is the error
List<User> users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
What should be done instead is the following:
Clear mListe from any previous content;
Fill with new content;
Set new data to the adapter.
if (response.isSuccessful()){
mListe.clear();
mListe.addAll(response.body());
usersAdapter.setData(mListe);
}
I have removed a few lines from this if-statement and moved them into the onCreate. They should be called only once, there is no benefit setting the same adapter and click listener if you call fetchUsers() again.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
usersAdapter = new UsersAdapter();
usersAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(usersAdapter);
fetchUsers();
}
you are not adding anything in ArrayList<User> mListe = new ArrayList<>();
you should add values before implementing any action,
try this
if (response.isSuccessful()){
List<User> users = response.body();
mListe.addAll(users);
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}

How do I use adapter position to retrieve data from firebase to a new activity

SearchPage where I search the books from firebase
public class SearchPage extends AppCompatActivity {
EditText searchbar;
RecyclerView recyclerView;
DatabaseReference reference;
ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
ArrayList<String> Desc;
SearchAdapter searchAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_page);
searchbar = (EditText) findViewById(R.id.searchbar);
reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
BookNameList = new ArrayList<>();
PublisherList = new ArrayList<>();
AuthorNameList = new ArrayList<>();
Shelfnols = new ArrayList<>();
PicList = new ArrayList<>();
Desc=new ArrayList<>();
searchbar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()) {
setAdapter(s.toString());
}
else{
BookNameList.clear();
AuthorNameList.clear();
PicList.clear();
PublisherList.clear();
Shelfnols.clear();
Desc.clear();
}
}
private void setAdapter(final String searchedString) {
reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
BookNameList.clear();
AuthorNameList.clear();
PicList.clear();
PublisherList.clear();
Shelfnols.clear();
Desc.clear();
int counter=0;
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
String uid = snapshot.getKey();
Log.i(uid,"ids");
String desc = snapshot.child("Desc").getValue(String.class);
String bookname = snapshot.child("bookname").getValue(String.class);
String author = snapshot.child("author").getValue(String.class);
String image = snapshot.child("image").getValue(String.class);
String publisher = snapshot.child("Publisher").getValue(String.class);
String shelfno = snapshot.child("Shelf_no").getValue(String.class);
try {
if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
BookNameList.add(bookname);
AuthorNameList.add(author);
PublisherList.add(publisher);
Shelfnols.add(shelfno);
PicList.add(image);
Desc.add(desc);
counter++;
} else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
BookNameList.add(bookname);
AuthorNameList.add(author);
PublisherList.add(publisher);
Shelfnols.add(shelfno);
PicList.add(image);
Desc.add(desc);
counter++;
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
}
if(counter==15){
break;
}
SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
recyclerView.setAdapter(searchAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
this the adapter class SearchAdapter where I am getting the adapter position on click
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
final public String id="bookname";
Context context;
ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
DatabaseReference reference;
class SearchViewHolder extends RecyclerView.ViewHolder{
ImageView bookimage;
TextView bookname, authorname,publisher,shelfno;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
bookimage = itemView.findViewById(R.id.Bookimg);
bookname = itemView.findViewById(R.id.BookName);
authorname = itemView.findViewById(R.id.AuthorName);
publisher = itemView.findViewById(R.id.Publications);
shelfno = itemView.findViewById(R.id.Shelfno);
booklayout=itemView.findViewById(R.id.LinLayout);
reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
}
}
public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
this.context = context;
BookNameList = bookNameList;
AuthorNameList = authorNameList;
PicList = picList;
PublisherList=publisherList;
Shelfnols=shelfnols;
}
#NonNull
#Override
public SearchAdapter.SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
return new SearchAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder holder, final int position) {
holder.bookname.setText(BookNameList.get(position));
holder.authorname.setText(AuthorNameList.get(position));
holder.publisher.setText(PublisherList.get(position));
holder.shelfno.setText(Shelfnols.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
Intent i = new Intent(context,Bookdetailslayout.class);
context.startActivity(i);
}
});
Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);
}
#Override
public int getItemCount() {
return BookNameList.size();
}
this is my new activity where i want the book details to be shown
public class Bookdetailslayout extends SearchPage {
DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookdetailslayout);
image=(ImageView)findViewById(R.id.img) ;
bookname = (TextView)findViewById(R.id.bkname);
author = (TextView) findViewById(R.id.aname);
publisher = (TextView) findViewById(R.id.pname);
desc = (TextView) findViewById(R.id.bkdescription);
location = (TextView) findViewById(R.id.bklocation);
String Bname=getIntent().getStringExtra("bookname");
Log.i(Bname, "onCreate: ");
DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");
}
till now I was able to set onclick to new activity and get the position of the click as item 1,2,etc...how do I use this position to get data from firebase to the new activity
create interface
public interface SetclickListener {
public void getposition(int position);
}
inside adapter create constructor
SetclickListener setclicklistener;
public SetclickListener getSetclick(Context context) {
this.context=context;
return setclicklistener;
}
public void setclicklistener(SetclickListener setclickListener){
setclicklistener=setclickListener;
}
get selected position
setclicklistener.getposition(getAdapterPosition());
then you can implement inside SearchPage activity then you can pass selected position data using Bundle you can send data to other activity
#Override
public void getposition(int position) {
Intent intent = new Intent(context,DetailsActivity.class);
intent.putExtra("name", bookNameList.get(position));
startActivity(intent);
}
}
}
i used this in my adapter class to get position
public void onClick(View v) {
Intent i = new Intent(context,Bookdetailslayout.class);
i.putExtra("bookname",BookNameList.get(position));
i.putExtra("Image",PicList.get(position));
i.putExtra("author_name",AuthorNameList.get(position));
i.putExtra("publisher_name",PublisherList.get(position));
context.startActivity(i);
}
});
then in the next activity
String imgs=getIntent().getStringExtra("Image");
String Bname=getIntent().getStringExtra("bookname");
title.setText(Bname);
String Author=getIntent().getStringExtra("author_name");
author.setText(Author);
String publisher=getIntent().getStringExtra("publisher_name");
pub.setText(publisher);
Toast.makeText(this,"image "+imgs,Toast.LENGTH_LONG).show();
Picasso.get().load(imgs).into(image);
and it works ..thanks for all the help here

Multiply the value from edittext to the value in textview retrieved from firebase

Hello I'm trying to create a Scoring System in Android Studio
My system goes like this, the organizer part will input a criteria and percentage of the criteria and will be saved to firebase.
On the scoring part, I retrieved the criteria and percentage from firebase then I put an Edittext next to it.
What I wanted to do is to multiply the percentage of the criteria to the value I input in edittext.
THIS IS THE CODE OF MY ADAPTER
#NonNull
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View listViewItem = convertView;
ScoringHolder myHolder = null;
if(listViewItem == null) {
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.list_scoring_criteria, parent, false);
myHolder = new ScoringHolder();
myHolder.textViewCriteria = (TextView) listViewItem.findViewById(R.id.textViewCriteria);
myHolder.textViewPercentage = (TextView) listViewItem.findViewById(R.id.textViewPercentage);
myHolder.editTextScore = (EditText) listViewItem.findViewById(R.id.editTextScore);
myHolder.btnSubmit = (ImageButton) listViewItem.findViewById(R.id.btnSubmit);
myHolder.textView6 = (TextView) listViewItem.findViewById(R.id.textView6);
listViewItem.setTag(myHolder);
}
else
{
myHolder = (ScoringHolder) listViewItem.getTag();
}
Criteria criteria = ScoringPageList.get(position);
myHolder.textViewCriteria.setText(criteria.getCriteriaName());
myHolder.textViewPercentage.setText(criteria.getCriteriaPercent());
myHolder.btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Criteria criteria = ScoringPageList.get(position);
}
});
return listViewItem;
}
static class ScoringHolder{
TextView textView6;
TextView textViewCriteria;
TextView textViewPercentage;
EditText editTextScore;
ImageButton btnSubmit;
}
THIS IS THE CODE OF MY ACTIVITY
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scoring_page);
db_Criteria = FirebaseDatabase.getInstance().getReference("Criteria");
db_Contestants = FirebaseDatabase.getInstance().getReference("Contestants");
listViewCriteria = (ListView) findViewById(R.id.listViewCriteria);
scoringPageList = new ArrayList<>();
btnSubmit = (Button) findViewById(R.id.btnSubmit);
textView2 = (TextView) findViewById(R.id.textView2);
String ConNameHolder = getIntent().getStringExtra("ConName");
textView2.setText(ConNameHolder);
}
#Override
protected void onStart() {
super.onStart();
db_Criteria.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot criteriaSnapshot : dataSnapshot.getChildren()){
Criteria criteria = criteriaSnapshot.getValue(Criteria.class);
scoringPageList.add(criteria);
}
ScoringPageList adapter = new ScoringPageList(ScoringPage.this, scoringPageList);
listViewCriteria.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
THIS IS THE CODE OF MY LIST
public class Criteria {
String criteriaId, criteriaName, criteriaPercent;
public Criteria(){
}
public Criteria(String criteriaId, String criteriaName, String criteriaPercent) {
this.criteriaId = criteriaId;
this.criteriaName = criteriaName;
this.criteriaPercent = criteriaPercent;
}
public void setCriteriaId(String criteriaId) {
this.criteriaId = criteriaId;
}
public void setCriteriaName(String criteriaName) {
this.criteriaName = criteriaName;
}
public void setCriteriaPercent(String criteriaPercent) {
this.criteriaPercent = criteriaPercent;
}
public String getCriteriaId() {
return criteriaId;
}
public String getCriteriaName() {
return criteriaName;
}
public String getCriteriaPercent() {
return criteriaPercent;
}
}
add this to your editText
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int dataFromEditText = Integer.parseInt(s.toString);
int dataFromTextView = Integer.parseInt(textView.getText().toString());
int finalData = dataFromEditText * dataFromTextView;
//Do as you wish with your final data
}
#Override
public void afterTextChanged(Editable s) {
}
});

Categories

Resources