I am getting a blank listView on running this code.I have checked the contents of the array by displaying them in a text view to the bottom of the listView.Changing to linear layout didn't work as well.
This is my first time using a listView so forgive me if its a stupid question.
XML CODE
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
tools:context=".current_month">
<ListView
android:id="#+id/barcode_detail"
android:layout_width="374dp"
android:layout_height="403dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.486"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.277" />
<TextView
android:id="#+id/title_tv"
android:layout_width="299dp"
android:layout_height="42dp"
android:layout_marginStart="141dp"
android:layout_marginEnd="141dp"
android:fontFamily="sans-serif-black"
android:textAlignment="center"
android:textColor="#F7F3F3"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.037" />
<TextView
android:id="#+id/resultView"
android:layout_width="245dp"
android:layout_height="143dp"
android:layout_marginStart="29dp"
android:layout_marginTop="29dp"
android:layout_marginEnd="65dp"
android:layout_marginBottom="65dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/bar_code_scan"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/barcode_detail" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/bar_code_scan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:clickable="true"
android:focusable="true"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/fruit_scan"
app:layout_constraintEnd_toEndOf="#+id/fruit_scan"
app:srcCompat="#drawable/ic_barcode_scan" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/scanButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="339dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fruit_scan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:clickable="true"
android:focusable="true"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/scanButton"
app:layout_constraintEnd_toEndOf="#+id/scanButton"
app:srcCompat="#drawable/ic_vegetable_scan" />
</androidx.constraintlayout.widget.ConstraintLayout>
JAVA CODE (A subset of the oncreate function)
final ArrayList<String> dat = new ArrayList<>();
final FirebaseUser users = firebaseAuth.getCurrentUser();
String result = users.getEmail().replace(".","");
DatabaseReference databaseReference2 = FirebaseDatabase.getInstance().getReference().child("Users").child(result).child("January").child("Product");
databaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
dat.add(snapshot.child("productname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ArrayAdapter arrayAdapter = new ArrayAdapter(current_month.this, android.R.layout.simple_list_item_1,dat);
barcode_detail.setAdapter(arrayAdapter);
Your arrayAdapter is not being notified of the changes made to list.
after adding items to the list you should call arrayAdapter.notifyDataSetChanged();
Your code should look something like this:
final ArrayList<String> dat = new ArrayList<>();
final FirebaseUser users = firebaseAuth.getCurrentUser();
String result = users.getEmail().replace(".","");
ArrayAdapter arrayAdapter = new ArrayAdapter(current_month.this, android.R.layout.simple_list_item_1,dat);
barcode_detail.setAdapter(arrayAdapter);
DatabaseReference databaseReference2 = FirebaseDatabase.getInstance().getReference().child("Users").child(result).child("January").child("Product");
databaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
dat.add(snapshot.child("productname").getValue().toString());
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Related
I have beenn struggling to find out why I am getting the error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Below is the full description of the error:
2021-03-15 14:15:49.906 24447-24447/com.goldencrestit.quicky2 D/AndroidRuntime: Shutting down VM
2021-03-15 14:15:49.907 24447-24447/com.goldencrestit.quicky2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.goldencrestit.quicky2, PID: 24447
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.goldencrestit.quicky2.ViewProfileActivity$1.onDataChange(ViewProfileActivity.java:64)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
This error pops up when I click on the "View your Profile" button in order to load the profile page.
Below is the expected result. It is support to fetch data from my firebase realtime database to fill the dummy texts:
Check below my codes:
activity_company_portal.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
android:orientation="vertical"
tools:context=".CompanyPortal">
<include
layout="#layout/toolbar"
android:id="#+id/toolbar_home" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="20dp"
android:orientation="horizontal">
<ImageButton
android:id="#+id/logout_btn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/ic_baseline_power_settings_new_24" />
</LinearLayout>
<ImageView
android:id="#+id/imageView3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
app:srcCompat="#drawable/logo" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<Button
android:id="#+id/view_job"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="20dp"
android:textColor="#color/text_color_secondary"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/view_all_jobs" />
<Button
android:id="#+id/add_job"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/view_job"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/add_a_new_job" />
<Button
android:id="#+id/edit_profile"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/add_job"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/edit_your_profile" />
<Button
android:id="#+id/view_profile"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/edit_profile"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/view_your_profile" />
</RelativeLayout>
</LinearLayout>
CompanyPortalActivity.java
public class CompanyPortalActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_portal);
Toolbar toolbar = findViewById(R.id.toolbar_home);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Quicky Job Portal");
Button viewJobs = findViewById(R.id.view_job);
Button postJobs = findViewById(R.id.add_job);
Button edit_profile = findViewById(R.id.edit_profile);
Button view_profile = findViewById(R.id.view_profile);
viewJobs.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), IndividualPostActivity.class)));
postJobs.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), PostJobsActivity.class)));
edit_profile.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), EditProfileActivity.class)));
view_profile.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), ViewProfileActivity.class)));
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
ImageButton mLogoutBtn = findViewById(R.id.logout_btn);
mLogoutBtn.setOnClickListener(v -> {
mAuth.signOut();
sendUserToLogin();
});
}
#Override
protected void onStart() {
super.onStart();
if(mCurrentUser == null){
sendUserToLogin();
}
}
private void sendUserToLogin() {
Intent loginIntent = new Intent(getApplicationContext(), CompanyLoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
}
activity_view_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".ViewProfileActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:id="#+id/toolbar"/>
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="50dp"
app:srcCompat="#drawable/logo" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginTop="10dp"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Company Name" />
<TextView
android:id="#+id/company_name"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Golden Crest Tech"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Business Type" />
<TextView
android:id="#+id/business_type"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Technology"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Phone Number" />
<TextView
android:id="#+id/phone_number"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="08020345678"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Company Address" />
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Surulere, Lagos"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:layout_marginBottom="5dp"
android:text="Company Detail" />
<EditText
android:id="#+id/editTextTextMultiLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:background="#drawable/text_display_2"
android:clickable="false"
android:editable="false"
android:ems="10"
android:enabled="false"
android:fontFamily="#font/open_sans"
android:gravity="start|top"
android:inputType="textMultiLine"
android:text="#string/company_detail_dummy"
android:textColor="#color/text_color_secondary"
android:textSize="14sp" />
<Button
android:id="#+id/edit_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_bg"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:textColor="#color/text_color_secondary"
android:textAllCaps="false"
android:textSize="16sp"
android:text="Edit Profile" />
</LinearLayout>
</ScrollView>
ViewProfileActivity.java
public class ViewProfileActivity extends AppCompatActivity {
private DatabaseReference myRef;
TextView company_name_txt, business_type_txt, phone_number_txt, company_address_txt;
EditText company_detail_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
company_name_txt = findViewById(R.id.company_name);
business_type_txt = findViewById(R.id.business_type);
phone_number_txt = findViewById(R.id.phone_number);
company_address_txt = findViewById(R.id.address);
company_detail_txt = findViewById(R.id.company_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Company Profile");
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
String phoneNumber = snapshot.child("phone_number").getValue().toString();
String companyAddress= snapshot.child("address").getValue().toString();
String businessType = snapshot.child("business_type").getValue().toString();
company_name_txt.setText(companyName);
business_type_txt.setText(businessType);
company_address_txt.setText(companyAddress);
phone_number_txt.setText(phoneNumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
Below is what I am trying to display on the Job Detail Layout:
The error seems to come from this piece of code:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
String phoneNumber = snapshot.child("phone_number").getValue().toString();
String companyAddress= snapshot.child("address").getValue().toString();
String businessType = snapshot.child("business_type").getValue().toString();
company_name_txt.setText(companyName);
business_type_txt.setText(businessType);
company_address_txt.setText(companyAddress);
phone_number_txt.setText(phoneNumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
The above code is loading all data from /Company Profile and then trying to read the company_name property from it. But if we look at the data you shared, there is no /Company Profile/company_name property, so that explains why getValue() returns null and the toString() then leads to the exception you get.
It seems your JSON tree consists of: /Company Profile/$uid/$pushid. How to property load the data from this structure depends on how much information you already know in your code, so let's look at the options:
If you know both the UID and the push ID of the information you want to load, you can do load just that with:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
String uid = "6babpG...MxLg33"; // must be the exact, complete value
String pushid = "-MVmyqx...3rwsAO"; // must be the exact, complete value
myRef.child(uid).child(pushid().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
If you know the UID, but not the push ID, of the information you want to load, you can load all push IDs and loop over them with:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
String uid = "6babpG...MxLg33"; // must be the exact, complete value
myRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
So here we loop over dataSnapshot.getChildren() to get across the unknown push IDs from the database. This means we can have multiple child nodes, so you may want to consider using a list view/recycler view for displaying the data.
The final case is if you know neither the UID nor the push ID of the data you want to display. In that case you need two nested loops to navigate over the data, one for the UIDs in the JSON, and one for the push IDs. So:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot snapshot: userSnapshot.getChildren()) {
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
You'll note that the solution is quite similar to the previous one, but now with a second loop. Here too, you'll have to consider what is the best UI element to display the structure, as now you're navigating/parsing an entire tree-like structure from the database.
I'm trying to display a Custom Dialog tapping a Card (I use recyclerview and firebase). I have an Adapter in which I have the onClick method. In there I want to put my custom dialog in order to open it when I click the card.
Here is the ArticoloAdapter.java
public class ArticoloAdapter extends RecyclerView.Adapter<ArticoloAdapter.VersionVH> {
private List<Articolo> listaArticoli;
private Context mCtx;
public ArticoloAdapter(Context mCtx, List<Articolo> listaArticoli){
this.mCtx = mCtx;
this.listaArticoli = listaArticoli;
}
#NonNull
#Override
public ArticoloAdapter.VersionVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.articolo_stock, parent, false);
return new VersionVH(view);
}
#Override
public void onBindViewHolder(#NonNull final ArticoloAdapter.VersionVH holder, int position) {
final Articolo articolo = listaArticoli.get(position);
holder.nome.setText(articolo.getNome());
if(articolo.getQuantita() == 1){
String quantita = Integer.toString(articolo.getQuantita()) + " Disponibile";
holder.quantita.setText(quantita);
} else {
String quantita = Integer.toString(articolo.getQuantita()) + " Disponibili";
holder.quantita.setText(quantita);
}
Picasso.get().load(articolo.getImg()).into(holder.img);
}
public int getItemCount(){
return listaArticoli.size();
}
public class VersionVH extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView img;
private TextView nome, quantita;
public VersionVH(View itemView){
super(itemView);
nome = itemView.findViewById(R.id.nomeArticolo);
quantita = itemView.findViewById(R.id.quantita);
img = itemView.findViewById(R.id.immagine);
cardView = itemView.findViewById(R.id.cardView);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here i want to put my custom_dialog
}
});
}
}
}
Here is my StockFragment (in which I have my card retrieved from Firebase):
public class StockFragment extends Fragment {
private RecyclerView recyclerView;
private List<Articolo> listaArticoli;
private ArticoloAdapter articoloAdapter;
private DatabaseReference query;
private LinearLayoutManager mLayoutManager;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_stock, container, false);
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
recyclerView = root.findViewById(R.id.recycleViewStock);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(articoloAdapter);
listaArticoli = new ArrayList<>();
query = FirebaseDatabase.getInstance().getReference("Articoli");
query.addListenerForSingleValueEvent(valueEventListener);
return root;
}
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listaArticoli.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Articolo articolo = snapshot.getValue(Articolo.class);
listaArticoli.add(articolo);
}
articoloAdapter = new ArticoloAdapter(getActivity(), listaArticoli);
recyclerView.setAdapter(articoloAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
};
}
and here is my custom_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="350dp"
android:layout_height="650dp"
android:background="#drawable/dialog_bg"
tools:ignore="UseSwitchCompatOrMaterialXml">
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06999999"
app:srcCompat="#android:drawable/sym_def_app_icon">
</ImageView>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="146dp"
android:layout_marginEnd="146dp"
android:text="Nome Prodotto"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.19999999">
</TextView>
<com.google.android.material.textview.MaterialTextView
android:id="#+id/materialTextView"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:gravity="center_horizontal"
android:inputType="textMultiLine"
android:text="Ciao questo รจ un testo di prova per daniele e vedere se gli piace o meno come esce"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3">
</com.google.android.material.textview.MaterialTextView>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="25dp"
android:layout_marginEnd="32dp"
android:hint="Nome"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/materialTextView"
app:layout_constraintVertical_bias="0.0"
android:layout_marginLeft="50dp"
android:layout_marginRight="32dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textNome"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout2"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:hint="Cognome"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout"
app:layout_constraintVertical_bias="0.0">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textCognome"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout3"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="32dp"
android:hint="Numero Di Telefono"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout2"
app:layout_constraintVertical_bias="0.0"
android:layout_marginLeft="50dp"
android:layout_marginRight="32dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textNumero"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
<EditText
android:id="#+id/testEnabeld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Prova"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/switchGaranzia"
app:layout_constraintVertical_bias="0.0" />
<Switch
android:id="#+id/switchGaranzia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="2dp"
android:text="Garanzia"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout3"
app:layout_constraintVertical_bias="0.0" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="49dp"
android:layout_height="328dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.925">
<ImageView
android:layout_width="35dp"
android:layout_height="54dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="1dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="16dp"
app:srcCompat="#drawable/icons8_utente_24" />
<ImageView
android:layout_width="35dp"
android:layout_height="54dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="16dp"
app:srcCompat="#drawable/icons8_utente_24" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Use the code below and add a child with match_parent attribute width and height inside the CardView and add the listener to the child view instead of the CardVeiw
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here i want to put my custom_dialog
Dialog dialog = new Dialog(mContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
dialog.getWindow().setLayout(ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
});
I've set the visibility of RecyclerView to gone. How would I be able to remove the empty space it takes?
I tried putting layout_height as wrap_content, but it still doesn't show anything.
Recycler View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Card View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:id="#+id/cardView"
android:backgroundTint="#5A10E7"
android:elevation="90dp"
android:orientation="vertical"
android:textColor="#FFFFFF"
app:cardCornerRadius="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.282">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/Requestfulfilled"
android:layout_width="139dp"
android:layout_height="41dp"
android:layout_weight="1"
android:backgroundTint="#4CAF50"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Request Fullfilled"
android:text="Fulfilled"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/DeleteRequest"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="#+id/RlocationView"
app:layout_constraintTop_toBottomOf="#+id/RlocationView" />
<Button
android:id="#+id/DeleteRequest"
android:layout_width="139dp"
android:layout_height="41dp"
android:backgroundTint="#F44336"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Delete"
android:text="Delete"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/RlocationView"
app:layout_constraintHorizontal_bias="0.894"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.904" />
<TextView
android:id="#+id/RemailView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Email"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RdateView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/RbloodView"
android:layout_width="116dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Blood Group"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toStartOf="#+id/RdateView"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RdateView"
android:layout_width="164dp"
android:layout_height="42dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Date of Requirement"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/RbloodView"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RlocationView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Location"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/Requestfulfilled"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RdateView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Code to set Card visibility as GONE:
public class yourRequestActivity extends AppCompatActivity {
private RecyclerView cardView;
private DatabaseReference dbRefForReq, dbRefForResp;
private FirebaseAuth mAuth;
private String AuthUserEmail, UserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request_response_view);
mAuth = FirebaseAuth.getInstance();
AuthUserEmail = mAuth.getCurrentUser().getEmail();
UserID = mAuth.getCurrentUser().getUid();
dbRefForResp = FirebaseDatabase.getInstance().getReference().child("Responses").child(String.valueOf(UserID));
dbRefForReq = FirebaseDatabase.getInstance().getReference().child("Blood Requests");
dbRefForReq.keepSynced(true);
cardView = (RecyclerView) findViewById(R.id.recycleView);
cardView.setHasFixedSize(true);
cardView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<getDbContents> options =
new FirebaseRecyclerOptions.Builder<getDbContents>()
.setQuery(dbRefForReq, getDbContents.class)
.build();
FirebaseRecyclerAdapter<getDbContents, contentHolder> adapter = new FirebaseRecyclerAdapter<getDbContents, contentHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final contentHolder holder, final int position, #NonNull final getDbContents model) {
final int finalPosition = position + 1;
if (model.getUser().equals(AuthUserEmail)) {
dbRefForReq.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot checkFulfillment = dataSnapshot.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment");
if (checkFulfillment.exists()) {
if (checkFulfillment.child("Fulfilled").getValue().equals("yes")) {
/*------------- Set current user card as visible -----------------*/
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
} else {
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.VISIBLE);
holder.requestFulfilled.setVisibility(View.GONE);
/*------------- Set current user card as visible -----------------*/
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else if (model.getUser().equals(null)) {
holder.userEmail.setText("You have not posted any request");
} else {
holder.frameView.setVisibility(View.GONE);
}
/* Fulfilled and Delete button Functionality */
holder.fulfilled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map<String, Object> response = new HashMap<>();
response.put("Fulfilled", "yes");
/*-----------------Remove Responses------------------*/
dbRefForResp.removeValue();
///////////////////////////////////////////////////////
/*-----------------Update and insert child with fulfilled status as yes------------------*/
dbRefForReq.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment").setValue(response).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(yourRequestActivity.this, "Request fulfillment status posted", Toast.LENGTH_SHORT).show();
}
});
////////////////////////////////////////////////////////////////////
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
}
});
}
#NonNull
#Override
public contentHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.your_request_card, viewGroup, false);
contentHolder contentViewHolder = new contentHolder(view);
return contentViewHolder;
}
};
cardView.setAdapter(adapter);
adapter.startListening();
}
public class contentHolder extends RecyclerView.ViewHolder {
TextView userEmail, bloodGroup, dateOfRequirement, Location, requestFulfilled;
Button fulfilled;
FrameLayout frameView;
public contentHolder(#NonNull View itemView) {
super(itemView);
userEmail = itemView.findViewById(R.id.RemailView);
bloodGroup = itemView.findViewById(R.id.RbloodView);
dateOfRequirement = itemView.findViewById(R.id.RdateView);
Location = itemView.findViewById(R.id.RlocationView);
requestFulfilled = (TextView) itemView.findViewById(R.id.fulfilledTextMessage);
frameView = (FrameLayout) itemView.findViewById(R.id.cardFrame);
fulfilled = (Button) itemView.findViewById(R.id.Requestfulfilled);
}
}
}
I want to remove the blank space which occurs while visibility is set to GONE, as shown in the snapshot below.
Image of empty space on removing top card
Image before setting visibility GONE
Simply remove the object from the list if its user is not equal to AuthUserEmail and notify your adapter.
NO NEED TO MAKE VISBILITY GONE OF THE HOLDER VIEW
Your RecyclerView takes space even if visibility is set to gone. It still takes space because there are items that RecyclerView wants to display. Although you can fix this by removing the items RecyclerView wants to show. It would take a lot of memory if you want show that RecyclerView again because you still have to add the items back. What I would recommend is to wrap your RecyclerView with a layout eg. LinearLayout and set that layout's visibility to gone.
Try doing this:
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Place your RecyclerView here -->
<!-- change visibility of container view -->
</LinearLayout>
*Edit: You didn't explain it well. I get what you want now. You simply have to remove the item from your RecyclerView list. The best way to do this is by using DiffUtil. This a great tutorial online showing how you can implement it in Java. https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction
Cover your RecyclerView with a FrameLayout and then set your visibility over there.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
If this doesnt works then:
Cover your Cardview which is the layout that you designed for your Recyclerview with a FrameLayout. Anyone of them will surely work out for you.
I'm developing a android bill management application, and want to retrieve some specified data to an android listview.
I used valueEventListener for this task but still couldn't able to retrieve data. How can I get those data to a listview using the valueEventListener?
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".SubmitReading">
<android.support.v7.widget.Toolbar
android:id="#+id/sr_toolbar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/notosans_bold"
android:text="Submit a Reading"
android:textColor="#color/colorAccent"
android:textSize="70px"
app:layout_constraintBottom_toBottomOf="#+id/sr_toolbar1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<ImageButton
android:id="#+id/bt_submit_a_reading_back"
android:layout_width="52dp"
android:layout_height="56dp"
android:background="#null"
android:foreground="?attr/selectableItemBackground"
android:src="#drawable/ic_arrow_back_black_24dp"
app:layout_constraintEnd_toStartOf="#+id/textView3"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/sr_toolbar1"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/sr_toolbar1">
<SearchView
android:id="#+id/search_address"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:queryHint="Search here">
</SearchView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="68dp"
android:layout_marginEnd="8dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout">
<ListView
android:id="#+id/list_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Java
package com.ceb.meterreaderassistant;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class SubmitReading extends AppCompatActivity {
private ListView listView;
private FirebaseDatabase cebDb;
private DatabaseReference dbRef;
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_reading);
cebDb = FirebaseDatabase.getInstance();
dbRef = cebDb.getReference("clients");
listView = (ListView)findViewById(R.id.list_address);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
}
}
I expect the output of the query to get clientAddress data in a listview, Currently I'm not getting the required output
You need to do the following:
cebDb = FirebaseDatabase.getInstance();
dbRef = cebDb.getReference("clients");
dmyRef.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
for(DataSnapshot ds : dataSnapshot.getChildren()){
String address = ds.child("clientAddress").getValue(String.class);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You need to attach ValueEventListener and then iterate inside the direct children to be able to retrieve the client address.
I am using Recycleview Adapter to show my list of items from Firebase Real-time Database.
I have a button which shows text value from Firebase initially when clicked will change the same key value in Firebase Database and I want it to show the updated text in Button too.
But it doesn't unless exit activity and reopen activity. Then it displays the updated value in Button text instead of the initial one.
How to update and show the value without exiting the Adapter?
I used notifyItemChanged(position) but it doesn't do anything.
Here is my Code
public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
ArrayList<Books> bookslist;
CardView cv;
FirebaseAuth fauth;
FirebaseDatabase database;
DatabaseReference dbreference;
Books g;
SubjectBooksAdapter adapter;
public SubjectBooksAdapter(ArrayList<Books> bookslist){
this.bookslist = bookslist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
Button mSolved;
MyViewHolder(final View itemView) {
super(itemView);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
dbreference.keepSynced(true);
mSolved = (Button) itemView.findViewById(R.id.book_solved);
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
g = bookslist.get(position);
holder.mSolved.setText(g.getMarkid());
holder.bookName.setText(g.getBname());
holder.bookprice.setText("Rs. "+g.getPrice());
holder.sellername.setText(g.getSellername());
holder.mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference classicalMechanicsRef = rootRef.child("books").child(g.getCondition()).child(g.getBookid());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.child("bmark").getRef().setValue("Solved");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
classicalMechanicsRef.addListenerForSingleValueEvent(valueEventListener);
notifyItemChanged(position);
}
});
#Override
public int getItemCount() {
return bookslist.size();
}
}
xml code is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/my_card_view"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="3dp"
android:layout_marginTop="4dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="2dp" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".9"
android:layout_marginBottom="5dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="75dp"
android:layout_height="75dp"
android:scaleType="fitXY"
android:padding="2dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingRight="7dp"
android:gravity="left">
<TextView
android:id="#+id/book_name"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".4"
android:text="Book Name"
android:textStyle="bold"
android:fontFamily="sans-serif-condensed"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_margin="1dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/seller_name"
android:layout_width="match_parent"
android:fontFamily="sans-serif"
android:layout_height="35dp"
android:layout_weight=".3"
android:text="Seller"
android:layout_margin="2dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:fontFamily="sans-serif-condensed"
android:gravity="center"
android:textColor="#ffffff"
android:text="Remove"
android:textStyle="bold"
android:layout_marginEnd="15dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginRight="15dp"
android:layout_width="wrap_content"
android:id="#+id/book_solved"
android:textAllCaps="false"
android:layout_height="35dp"
android:background="#drawable/buttonshape1"
android:padding="8dp"
android:layout_toRightOf="#id/seller_name"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/profile_details"
android:layout_width="match_parent"
android:layout_height="35dp"
android:fontFamily="sans-serif-condensed"
android:text="View Details"
android:background="#drawable/buttonshape1"
android:gravity="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_marginEnd="15dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginRight="15dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Thanks in advance.
Whatever the value you want to change in your adapter you can do using notifyItemChanged(position). NotifyItemChange only works when there is a change in your Model Class.
Let say here you are setting the value your Book Name on a TextView by using this code.
Books g = bookslist.get(position);
holder.bookName.setText(g.getBname());
Now if you want to change the value of Book name on Button click you have to change the value in your ArrayList Model also then notify it.
Books g = bookslist.get(position);
g.setBname("your new value");
After this, your notifyItemChanged(position) will display the new value. This is how notify works in RecyclerView
Why you have to do so?
Whenever the notify is called in RecylerView it again set the value from the ArrayList. But in your case, the value is not updated locally in your list but is updated in the FireBase. That's why you get the updated value whenever you again open your app.
NOTE
To change the value of Button with text Remove, get the Markid in the Datachange of the FireBase. Then set that value in the respective model(of that position) from the ArrayList for String Markid.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.child("bmark").getRef().setValue("Solved");
// Here you need to save the value in the arraylist.
bookslist.get(position).setMardid("Here what ever the value you will pass will get updated on the button after notify"); //Try adding the static string that you want after button click.
notifyItemChanged(position)
}