How to Retrieve Data from Firebase Realtime Database in Fragment? - android

This is how my Database look like:
I already write my code inside fragment and have an error like this
java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
this is my Fragment.xml
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#drawable/gradient_hijau_kuning_kotak"
app:layout_constraintTop_toTopOf="parent" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/tampilanFoto"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginTop="88dp"
android:src="#drawable/fotorumahsakit"
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/tampilanNamaUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="#font/swansea_bold"
android:gravity="center"
android:text="Nama User"
android:textColor="#color/black"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tampilanFoto" />
<TextView
android:id="#+id/tampilanLokasiUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="#font/twentycenth"
android:gravity="center"
android:text="Lokasi"
android:textColor="#color/black"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tampilanNamaUser" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#id/tampilanLokasiUser">
<TextView
android:id="#+id/infoAkunText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/swansea_bold"
android:text="Info Akun"
android:textColor="#color/black"
android:textSize="30sp"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:padding="20dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/iconProfile"
android:layout_width="80dp"
android:layout_marginStart="20dp"
android:layout_height="80dp"
android:src="#drawable/man"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:fontFamily="#font/swansea_bold"
android:text="Status :"
android:textColor="#color/black"
android:textSize="18sp"/>
<TextView
android:id="#+id/showStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:fontFamily="#font/swansea_thin"
android:text="status"
android:textColor="#color/black"
android:textSize="18sp"/>
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/gantiPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/twentycenth"
android:layout_gravity="center"
android:gravity="center"
android:text="GANTI PASSWORD"
android:textColor="#color/hijau_cerah"
android:textSize="18sp"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And this is my Fragment.java
public class ProfileFragment extends Fragment {
TextView tampilanNamaUser, tampilanLokasi, statusUser, gantiPassword;
FirebaseAuth mAuth;
SessionManager sessionManager;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://simande-4f3e2-default-rtdb.firebaseio.com/");
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public ProfileFragment() {
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
//Hook
tampilanNamaUser = v.findViewById(R.id.tampilanNamaUser);
tampilanLokasi = v.findViewById(R.id.tampilanLokasiUser);
statusUser = v.findViewById(R.id.showStatus);
gantiPassword = v.findViewById(R.id.gantiPassword);
sessionManager = new SessionManager(getContext(), SessionManager.SESSION_USERSESSION);
HashMap<String, String> usersDetails = sessionManager.getUsersDetailFromSession();
String getName = usersDetails.get(SessionManager.KEY_USERNAME);
getUserInfo(getName);
return v;
}
private void getUserInfo(String getName) {
databaseReference.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
if (snapshot.hasChild(getName)){
String nama = snapshot.child("Nama").getValue().toString();
tampilanNamaUser.setText(nama);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
P.s : This is my CreateAccountActivity I put getName String on this Activity but I didn't know how to call it in another Fragment.
public class BuatAkunActv extends AppCompatActivity {
private EditText userInput, passInput;
private Button buttonRegist;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://simande-4f3e2-default-rtdb.firebaseio.com/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buat_akun_actv);
//Hook
userInput = findViewById(R.id.daftarUser);
passInput = findViewById(R.id.daftarPassword);
buttonRegist = findViewById(R.id.buttonDaftar);
buttonRegist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getName = userInput.getText().toString();
String getPassword = passInput.getText().toString();
databaseReference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild(getName)){
Toast.makeText(BuatAkunActv.this, "User sudah terdaftar", Toast.LENGTH_SHORT).show();
}
else {
databaseReference.child("Users").child(getName).child("nama").setValue(getName);
databaseReference.child("Users").child(getName).child("password").setValue(getPassword);
Toast.makeText(BuatAkunActv.this, "User berhasil dibuat", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
}

There are quite a few problems in your getUserInfo. I'm not sure if they cause the error, but here's what I'd change it to:
private void getUserInfo(String getName) {
databaseReference.child("Users").child(getName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String nama = snapshot.child("Nama").getValue().toString();
tampilanNamaUser.setText(nama);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
}
The significant change:
Instead of loading the entire Users node to check if one child exists in it, load only that child node.
Don't ignore errors in onCancelled, as it makes debugging much harder.

Related

Recyclerview not call any Adapter method: onCreateViewHolder, onBindViewHolder

Here are my codes for MyAdapter, ActivityMain, MinActivity, and User
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<User> list;
public MyAdapter(Context context, ArrayList<User> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
// here is the problem that I don't know how to fix][1]
// I'm tryin to pass data from firebase to Recyclerview
// error I'm getting here is:
// [Cannot resolve method 'getFirstName' in 'User'
// Cannot resolve method 'getLastName' in 'User'
// Cannot resolve method 'getAge' in 'User']
User user = list.get(position);
holder.FirstName.setText(user.getFirstName());
holder.LastName.setText(user.getLastName());
holder.Age.setText(user.getAge());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView FirstName, LastName, Age;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
FirstName = itemView.findViewById(R.id.tvFirstName);
LastName = itemView.findViewById(R.id.tvLastName);
Age = itemView.findViewById(R.id.tvAge);
}
}
}
This is MainActivity code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database;
MyAdapter myAdapter;
ArrayList<User> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Main);
recyclerView = findViewById(R.id.userList);
database = FirebaseDatabase.getInstance().getReference("User");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
list.add(user);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is User codes which I generated with getter
public class User {
String FirstName, LastName, Age;
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public String getAge() {
return Age;
}
{
}
}
This is my layout file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="8dp"
app:cardCornerRadius="8dp"
android:layout_margin="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Name :"
android:textColor="#color/black"
android:textSize="26sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Arya"
android:textColor="#color/black"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/last_name"
android:textColor="#color/black"
android:textSize="26sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="#string/stark"
android:textColor="#color/black"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/age"
android:textColor="#color/black"
android:textSize="26sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="18"
android:textColor="#color/black"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
When I hit RUN it gives me this error:
I'm new to coding.
you can change your code like this
holder.FirstName.setText(list.getFirstName().get(position));
holder.LastName.setText(list.getLastName().get(position));
holder.Age.setText(list.getAge().get(position);
and you should change this code position
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
into under this code
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
list.add(user);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
hope it can solve your problem :)

Attempt to invoke virtual method 'java.lang.String com.tnbdev.ulam.model.Region.getSubregionMark()' on a null object reference

I am build the navigation view using fragment method. in this fragment i create some method to show the view, such as spinner when click value in spinner, it will display in the recycle view. but the problem is in the adapter is show null object references.
public class LRPFragment extends Fragment {
private String mInstituteLocation = "";
private Spinner sp;
DatabaseReference db;
FirebaseHelper helper;
RecyclerView recyclerView;
LRPAdapter adapter;
List<Region> routesList;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
db = FirebaseDatabase.getInstance().getReference();
helper=new FirebaseHelper(db);
View RootView = inflater.inflate(R.layout.fragment_lrp, container, false);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView = RootView.findViewById(R.id.rv_rec_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(llm);
sp = (Spinner) RootView.findViewById(R.id.subreg);
loadRoute("Region");
return RootView;
}
private void loadRoute(final String referenceKey){
db = FirebaseDatabase.getInstance().getReference(referenceKey);
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final List<String> subregionMark = new ArrayList<>();
subregionMark.add(0, "Choose Subregion");
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
for (DataSnapshot dataSnapshot1: snapshot.getChildren()){
subregionMark.add(dataSnapshot1.child("subregionMark").getValue(Region.class).getSubregionMark());//null object references on getSubregionMark
}
}
ArrayAdapter <String> subAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item, subregionMark);
subAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(subAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu LRPFragment");
}
}
This is constructor
public class Region {
String name;
String start;
String end;
String distance;
String regionMark;
String subregionMark;
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getSubregionMark() {
return subregionMark;
}
public void setSubregionMark(String subregionMark) {
this.subregionMark = subregionMark;
}
public Region() {
}
public String getName() {
return name;
}
public String getRegionMark() {
return regionMark;
}
public void setName(String name) {
this.name = name;
}
public void setRegionMark(String regionMark) {
this.regionMark = regionMark;
}
This is layout where i call fragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:id="#+id/rel"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#id/tvreg"
android:layout_centerVertical="true"
android:layout_marginTop="-57dp"
android:text="LRP"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="25dp" />
<TextView
android:id="#+id/tvreg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="17dp"
android:layout_marginTop="49dp"
android:layout_marginEnd="23dp"
android:layout_toStartOf="#+id/regionMark"
android:text="REGION" />
<Spinner
android:id="#+id/regionMark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="47dp"
android:layout_marginEnd="13dp"
android:contextClickable="true"
android:entries="#array/regionMark"
android:spinnerMode="dropdown" />
<TextView
android:layout_width="113dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tvreg"
android:layout_alignParentStart="true"
android:layout_marginStart="20dp"
android:layout_marginTop="17dp"
android:layout_marginEnd="20dp"
android:layout_toStartOf="#+id/subreg"
android:text="SUBREGION" />
<Spinner
android:id="#+id/subreg"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_below="#+id/regionMark"
android:layout_alignParentEnd="true"
android:layout_marginTop="13dp"
android:layout_marginEnd="20dp"
android:spinnerMode="dropdown"
android:visibility="visible" />
<TextView
android:id="#+id/or"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OR"
android:layout_below="#+id/subreg"
android:layout_centerInParent="true"/>
<SearchView
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_centerInParent="true"
android:layout_below="#+id/or"
android:imeOptions="actionSearch"
android:inputType="textAutoComplete|textAutoCorrect"
android:textColor="#FFFFFF"
>
<requestFocus />
</SearchView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/filterTCBtn"
android:text="Filter"
android:layout_below="#+id/editText1"/>
</RelativeLayout>
<TextView
android:layout_below="#+id/rel"
android:id="#+id/route_view_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Route View"
android:textSize="20dp"
android:layout_centerHorizontal="true" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_rec_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/route_view_menu"
android:layout_marginTop="-2dp"
android:padding="3dp" />
</RelativeLayout>
This is myfirebase

Android setVisibility does not work on some logic

Just a little introduction of what I am doing.
I am granting different functionality based on the account type a user has sign in with.
The user's account type will be retrieved via Firebase Reference from Firebase Database. If you look at this image, there's the arrow indicated. That is where the account type will be displayed but to consider the UI, I have set the visibility of the text view to be "gone". I have validated that the database reference codes are working as when I set the visibility of the text view to be visible, and then I run the app, the text view will change accordingly to be either Administrator or Local User.
The problem lies on my setVisibility 'if else' logic. It does not work accordingy. Attached are the list of scenarios I have tested and the outcomes of it.
I have tried adding the visibility to 'gone' on my pencil icon, and use VISIBILE/INVISIBLE/GONE without the View infront of it (like what many have said as their solution on several similar posts), but when I tried that, the icon is invisible for all 8 scenarios.
As such, I am not sure what else I should do to overcome this. Any help is greatly appreciated.
Update #1: Added codes as requested
class SearchViewHolder extends RecyclerView.ViewHolder {
public TextView keyword, description, acronym, relatedkeyword1,
relatedkeyword2, relatedkeyword3, tv_rules_read_more;
public ImageView iv_rules;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
//knowledge feature
keyword = itemView.findViewById(R.id.keyword);
acronym = itemView.findViewById(R.id.acronym);
tv_rules_read_more = itemView.findViewById(R.id.tv_rules_read_more);
iv_rules = itemView.findViewById(R.id.iv_rules);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
implements SectionIndexer {
// private Context context;
private List<Knowledge> knowledge;
private ArrayList<Integer> mSectionPositions;
Activity activity;
String positionUpdated;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;
public SearchAdapter(Activity activity, List<Knowledge> knowledge, String
positionUpdated) {
//this.context = context;
this.knowledge = knowledge;
this.activity = activity;
this.positionUpdated = positionUpdated;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder holder, final int
position) {
holder.keyword.setText(knowledge.get(position).getKeyword());
holder.acronym.setText(knowledge.get(position).getAcronym());
holder.tv_rules_read_more.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(position);
}
});
if (positionUpdated != null && !positionUpdated.equals("")) {
showDialog(Integer.parseInt(positionUpdated));
positionUpdated = "";
}
}
public void showDialog(final int position) {
try {
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.dialog_layout_item_rules);
dialog.setCancelable(false);
final TextView acctype, keyword1, description1, acronym1,
relatedkeyword4, relatedkeyword5, relatedkeyword6;
//final TextView keyword1, description1, acronym1,
relatedkeyword4, relatedkeyword5, relatedkeyword6;
ImageView iv_rules, iv_close_dialog, iv_edit_dialog;
//rules feature
acctype = dialog.findViewById(R.id.tvAccType);
keyword1 = dialog.findViewById(R.id.keyword);
acronym1 = dialog.findViewById(R.id.acronym);
description1 = dialog.findViewById(R.id.description);
relatedkeyword4 = dialog.findViewById(R.id.relatedKeyword1);
relatedkeyword5 = dialog.findViewById(R.id.relatedKeyword2);
relatedkeyword6 = dialog.findViewById(R.id.relatedKeyword3);
iv_rules = dialog.findViewById(R.id.iv_rules);
iv_close_dialog = dialog.findViewById(R.id.iv_close_dialog);
iv_edit_dialog = dialog.findViewById(R.id.iv_edit_dialog);
/////////
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference =
firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile =
dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
////////
keyword1.setText(knowledge.get(position).getKeyword());
description1.setText(knowledge.get(position).getDescription());
acronym1.setText(knowledge.get(position).getAcronym());
relatedkeyword4.setText(knowledge.get(position).getRelatedkeyword1());
relatedkeyword5.setText(knowledge.get(position).getRelatedkeyword2());
relatedkeyword6.setText(knowledge.get(position).getRelatedkeyword3());
byte[] bytesImage = knowledge.get(position).getImage();
if (bytesImage != null && bytesImage.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytesImage, 0,
bytesImage.length);
iv_rules.setImageBitmap(bitmap);
iv_rules.setVisibility(View.VISIBLE);
} else {
iv_rules.setVisibility(View.GONE);
}
dialog.show();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
WindowManager.LayoutParams layoutParams = new
WindowManager.LayoutParams();
Window window = dialog.getWindow();
layoutParams.copyFrom(window.getAttributes());
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(layoutParams);
iv_close_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
}
});
iv_edit_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity,
AddNewKnowledgeActivity.class);
intent.putExtra("id",
String.valueOf(knowledge.get(position).getId()));
intent.putExtra("position", String.valueOf(position));
intent.putExtra("call_type", "update_rule");
intent.putExtra("title",
knowledge.get(position).getKeyword());
intent.putExtra("code",
knowledge.get(position).getAcronym());
intent.putExtra("description",
knowledge.get(position).getDescription());
intent.putExtra("keyword1",
knowledge.get(position).getRelatedkeyword1());
intent.putExtra("keyword2",
knowledge.get(position).getRelatedkeyword2());
intent.putExtra("keyword3",
knowledge.get(position).getRelatedkeyword3());
intent.putExtra("bytesImage",
knowledge.get(position).getImage());
dialog.cancel();
activity.startActivityForResult(intent, 101);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return knowledge.size();
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
List<String> sections = new ArrayList<>(26);
mSectionPositions = new ArrayList<>(26);
for (int i = 0, size = knowledge.size(); i < size; i++) {
String section =
String.valueOf(knowledge.get(i).getKeyword().charAt(0)).toUpperCase();
if (!sections.contains(section)) {
sections.add(section);
mSectionPositions.add(i);
}
}
return sections.toArray(new String[0]);
}
#Override
public int getPositionForSection(int sectionIndex) {
return mSectionPositions.get(sectionIndex);
}
}
Update 2: Added XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#f5f0f0"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_rules"
android:layout_width="200dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:src="#color/deeppurpleColor"
android:visibility="gone" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_edit_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_5sdp"
android:background="#android:drawable/ic_menu_edit"
android:backgroundTint="#android:color/black"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_close_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_5sdp"
android:layout_alignParentRight="true"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:backgroundTint="#android:color/black" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:id="#+id/tvAccType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Account Type"
android:visibility="gone"/>
<TextView
android:id="#+id/keyword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_vertical|start"
android:text="Baggage Management Interface Device (BMID)
Testing 123"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/codeHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Code:"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="bold" />
<TextView
android:id="#+id/acronym"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="GST"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="italic" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/ruleHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Desc:"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="bold" />
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:scrollbars="vertical"
android:text="If none are set then 'GST' is set to NULL"
android:textColor="#a8000000"
android:textSize="13dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/relatedKeyword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Related Keyword:"
android:textColor="#a8000000"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="#+id/relatedKeyword1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 1,"
android:textColor="#a8000000"
android:textSize="12sp" />
<TextView
android:id="#+id/relatedKeyword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 2,"
android:textColor="#a8000000"
android:textSize="12sp" />
<TextView
android:id="#+id/relatedKeyword3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 3"
android:textColor="#a8000000"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Problem is solved by placing the if/else logic inside onDataChange method!
The logic did not work accordingly as my if/else logic were placed outside of the loop. The logic should work while Firebase is retrieving then displaying the values.
As such, instead of these:
DatabaseReference databaseReference =
firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile =
dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
//note: these are outside of the loop at first
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
It should be like this instead:
DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
//granting different functionality based on account type
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I learnt my lesson the hard way! It is very important to understand the logic you want to come out with, followed by the expected work flow!
Many thanks to those who have taken their time to guide me through!

Firebase Children Count to listview

Good Day,
I'm Trying to count the number of children based on votes.
This is my Firebase structure.
Candidate Table
and
Votes table
I successfully recovered the candidates from candidates table to listview, but I can't recover the number of votes they got on the votes table.
This is my xml for the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/count_ssc_president_last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="40sp"
android:textColor="#color/colorBlack"/>
<TextView
android:id="#+id/count_ssc_president_first_middle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20sp"/>
<TextView
android:id="#+id/count_ssc_president_partylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/count_ssc_president_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView"
android:textSize="20sp"
android:textColor="#color/colorBlack"/>
</LinearLayout>
This is my xml for the Main java class
<?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"
tools:context=".Voter_SSC_President">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="14dp"
android:text="#string/choose_ssc_president"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<ListView
android:id="#+id/listCountSSCPresident"
android:layout_width="309dp"
android:layout_height="338dp"
android:layout_marginBottom="32dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="34dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="277dp"
android:layout_height="111dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/textView4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_ssc_logo" />
</android.support.constraint.ConstraintLayout>
This is my adapter
private Activity context;
private List<SSC_Presidents> CountSSC_PresidentsList;
DatabaseReference userReference;
long num;
private LayoutInflater inflater;
public CountSSCPresLists(Activity context, List<SSC_Presidents> CountSSC_PresidentsList )
{
super(context, R.layout.listview_count_ssc_president, CountSSC_PresidentsList);
this.context = context;
this.CountSSC_PresidentsList = CountSSC_PresidentsList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.listview_count_ssc_president, null, false);
TextView textViewLast_name = (TextView) listViewItem.findViewById(R.id.count_ssc_president_last_name);
TextView textViewFirst_middle_name = (TextView) listViewItem.findViewById(R.id.count_ssc_president_first_middle);
TextView textViewPartylist = (TextView) listViewItem.findViewById(R.id.count_ssc_president_partylist);
TextView textViewCount = (TextView) listViewItem.findViewById(R.id.count_ssc_president_count);
SSC_Presidents sscPresidents = CountSSC_PresidentsList.get(position);
/*
userReference = FirebaseDatabase.getInstance().getReference("vote");
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
textViewCount.setText((int) num);*/
textViewLast_name.setText(sscPresidents.getLast_name());
textViewFirst_middle_name.setText(sscPresidents.getFirst_name()+", "+sscPresidents.getMiddle_name());
textViewPartylist.setText(sscPresidents.getPartylist_id());
return listViewItem;
The block-comment is my try to generate the vote number based on the candidate-id
This is my main java class
String stud_no;
DatabaseReference databaseReferenceCountSSCPres;
ListView listViewCountSSCPresident;
List<SSC_Presidents> sscCountPresList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__count__ssc__president);
databaseReferenceCountSSCPres = FirebaseDatabase.getInstance().getReference("candidate");
stud_no = LoginScreen.TBPstud_no1();
listViewCountSSCPresident = findViewById(R.id.listCountSSCPresident);
sscCountPresList = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
Query CountSSCPresident = databaseReferenceCountSSCPres.orderByChild("council_id_position_id_school_year").equalTo("SSC_PRES_201819");
CountSSCPresident.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
sscCountPresList.clear();
for (DataSnapshot CountSSCPresSnapshot : dataSnapshot.getChildren())
{
SSC_Presidents CountSSCPres = CountSSCPresSnapshot.getValue(SSC_Presidents.class);
sscCountPresList.add(CountSSCPres);
}
CountSSCPresLists adapter = new CountSSCPresLists(Admin_Count_SSC_President.this, sscCountPresList);
listViewCountSSCPresident.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is the result
Result
I want to put the count in the TextView in the Result.
Thank you.
PS. When I remove the block comment on the adapter the screen for the result crashes.
EDIT:
The suggestion worked but only on the last candidate.
I also used query now.
userReference = FirebaseDatabase.getInstance().getReference("vote");
Query CountSSCPresident = userReference.orderByChild("candidate_id").equalTo(sscPresidents.getCandidate_id());
CountSSCPresident.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
textViewCount.setText(String.valueOf((int)num));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The result
textViewCount.setText((int) num);
You need to cast num to a string. Try this:
textViewCount.setText(String.valueOf((int)num));
EDIT: Also place it inside the listener:
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
textViewCount.setText(String.valueOf((int)num));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

I am Unable to retrieve data from Firebase database

I am posting this question because I haven't found any proper solution related to my problem.
I am trying to retrieve my sensor data from Firebase but I am unable to do it. Please point out where am I doing wrong
Try.java
public class Try extends AppCompatActivity {
Button button;
ListView list;
DatabaseReference databaseTry;
List<TryObjectClass> tryObjectList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_try);
databaseTry =
FirebaseDatabase.getInstance().getReference("sensor_data");
button = (Button) findViewById(R.id.button);
list = (ListView) findViewById(R.id.list);
//list.setVisibility(View.INVISIBLE);
tryObjectList = new ArrayList<>();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseTry.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tryObjectList.clear();
for (DataSnapshot TrySnapshot : dataSnapshot.getChildren()){
TryObjectClass tryObjectClass =
TrySnapshot.getValue(TryObjectClass.class);
tryObjectList.add(tryObjectClass);
}
TryAdapter adapter = new TryAdapter(Try.this, tryObjectList);
list.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
This is my object class
TryObjectClass.java
public class TryObjectClass {
private String date;
private String time;
private String humidity;
private String motion;
private String distance;
private String temperature;
public TryObjectClass(){
}
public TryObjectClass(String date, String time, String humidity, String
motion, String distance, String temperature) {
this.date = date;
this.time = time;
this.humidity = humidity;
this.motion = motion;
this.distance = distance;
this.temperature = temperature;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getMotion() {
return motion;
}
public void setMotion(String motion) {
this.motion = motion;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
}
This is my adapter class
TryAdapter.java
public class TryAdapter extends ArrayAdapter<TryObjectClass> {
private Activity context;
private List<TryObjectClass> objectList;
public TryAdapter(#NonNull Activity context, List<TryObjectClass>
objectList) {
super(context, R.layout.new_list,0);
this.context = context;
this.objectList = objectList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.new_list,null,true);
TextView date = (TextView) listViewItem.findViewById(R.id.date);
TextView distance = (TextView)
listViewItem.findViewById(R.id.distance);
TextView humidity = (TextView)
listViewItem.findViewById(R.id.humidity);
TextView motion = (TextView) listViewItem.findViewById(R.id.motion);
TextView temperature = (TextView)
listViewItem.findViewById(R.id.temperature);
TextView time = (TextView) listViewItem.findViewById(R.id.time);
TryObjectClass tryObjectClass = objectList.get(position);
date.setText(tryObjectClass.getDate());
distance.setText(tryObjectClass.getDistance());
humidity.setText(tryObjectClass.getHumidity());
motion.setText(tryObjectClass.getMotion());
temperature.setText(tryObjectClass.getTemperature());
time.setText(tryObjectClass.getTime());
return super.getView(position, convertView, parent);
}
}
try_activity.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"
tools:context=".Try"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Retrieved data"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:padding="10dp"
android:layout_marginLeft="90dp"
android:layout_marginTop="20dp"/>
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click here to retrieve the data"/>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
This is my list item
new_list.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Humidity -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Motion -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/motion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperature -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Time -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
This is my database
smartborder-cef61
sensor_data
100
date: 1875
distance: "50M"
humidity: 4573
motion: "yes"
temperature: "30c"
time: 7377200
200
date: 23111996
distance: "50M"
humidity: 45
motion: "yes"
temperature: "30C"
time: 73775
I found something, try to put your setAdapter() outside your listener.
Inside your listener you will put this code:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot TrySnapshot : dataSnapshot.getChildren()){
TryObjectClass tryObjectClass = TrySnapshot.getValue(TryObjectClass.class);
tryObjectList.add(tryObjectClass);
}
adapter.notifyDataSetChanged();
}
And try to put your declared things in onCreate method, like your ValueEventListener, so you can add it in onStart and remove it in onDestroy when your activity have not to listen your changes anymore when your activity is destroyed. Here's part of my fragment ContatsFragment, it is working fine:
public class ContatsFragment extends Fragment {
private ListView listView;
private ArrayAdapter adapter;
private ArrayList<Contat> contats;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListenerContatos;
private Context context;
public ContatsFragment() {
// Required empty public constructor
}
#Override
public void onStart() {
super.onStart();
context = getActivity();
databaseReference.addValueEventListener(valueEventListenerContatos);
}
#Override
public void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListenerContatos);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contats = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_contats, container, false);
listView = (ListView) view.findViewById(R.id.lv_contatos);
adapter = new ContatAdapter(getActivity(), contats);
listView.setAdapter(adapter);
Preferences preferences = new Preferences(getActivity());
String loggedUserId = preferences.getLoggedUserId();
databaseReference = FirebaseConfig.getFirebaseReference();
databaseReference = databaseReference.child("contats")
.child(loggedUserId);
valueEventListenerContatos = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
contats.clear();
for (DataSnapshot dados : dataSnapshot.getChildren()) {
Contat contat = dados.getValue(Contat.class);
contats.add(contat);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
return view;
}
}
I have got the solution...I made mistake in the giving the list object name...

Categories

Resources