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 :)
Related
I'm trying to set a value of '1' or '0' to my list of users on a node named 'Blocked Users' in Firebase. However, I'm only retrieving the UID of the account that is logged in on the app I'm currently using instead of the ones on the list:
{
"Blocked Users" : {
"HnREoOYynjVfPlTQKCt5744SzAt1" : 1
},
"User Location" : {
"latitude" :
"longitude" :
},
"Users" : {
"RCX2HZXIwlSmMHFgDytf1DgZBgi2" : {
"Alert Level" :
"Emergency Type" :
"address" : ,
"emergencyNum" :
"name" :
"phoneNum" :
}
}
}
I'm trying to get the UID in 'Users', the ones on the RecyclerView, not the current user in the app. Here's how I'm doing so far:
My adapter:
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull MainData model) {
holder.name.setText(model.getName());
holder.address.setText(model.getAddress());
holder.phoneNum.setText(model.getPhoneNum());
}
String uid = FirebaseAuth.getInstance().getUid();
Context context;
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
return new myViewHolder(view);
}
public MainAdapter(#NonNull FirebaseRecyclerOptions<MainData> mainDataFirebaseRecyclerOptions) {
super(mainDataFirebaseRecyclerOptions);
}
class myViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView name, address, phoneNum;
ToggleButton toggleButton;
public myViewHolder(#NonNull View itemView) {
super(itemView);
image = (CircleImageView) itemView.findViewById(R.id.img1);
name = (TextView) itemView.findViewById(R.id.nameText);
address = (TextView) itemView.findViewById(R.id.addressText);
phoneNum = (TextView) itemView.findViewById(R.id.numberText);
itemView.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
blockUser();
}
});
itemView.findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unblockUser();
}
});
}
}
private void blockUser() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Blocked Users").child(uid);
reference.setValue(1)
.addOnCompleteListener((OnCompleteListener<Void>) unused -> {
Toast.makeText(context, "User Blocked", Toast.LENGTH_SHORT).show();
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "Failed"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void unblockUser(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Blocked Users").child(uid);
reference.setValue(0)
.addOnCompleteListener((OnCompleteListener<Void>) unused -> {
Toast.makeText(context, "User Unblocked", Toast.LENGTH_SHORT).show();
})
.addOnFailureListener(e -> Toast.makeText(context, "Failed"+e.getMessage(),Toast.LENGTH_SHORT).show());
}
}
RecyclerView Activity:
public class Report extends AppCompatActivity {
RecyclerView recyclerView;
MainAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
recyclerView = (RecyclerView) findViewById(R.id.userList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<MainData> mainDataFirebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<MainData>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Users"), MainData.class)
.build();
mainAdapter = new MainAdapter(mainDataFirebaseRecyclerOptions);
recyclerView.setAdapter(mainAdapter);
}
#Override
protected void onStart() {
super.onStart();
mainAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mainAdapter.stopListening();
}
The layout for the RecyclerView:
<?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:cardCornerRadius="6dp"
android:layout_margin="16dp"
android:elevation="6dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:padding="15dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/img1"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp" />
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/nameText"
android:text="Name"
android:textStyle="bold"
android:textSize="15sp"
android:textColor="#000"
android:layout_toRightOf="#+id/img1"
android:layout_marginLeft="10dp"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/addressText"
android:text="Address"
android:textStyle="bold"
android:textSize="15sp"
android:textColor="#000"
android:layout_toRightOf="#+id/img1"
android:layout_marginLeft="10dp"
android:layout_below="#+id/nameText"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/numberText"
android:text="Emergency Number"
android:textStyle="bold"
android:textSize="15sp"
android:textColor="#000"
android:layout_toRightOf="#+id/img1"
android:layout_marginLeft="10dp"
android:layout_below="#+id/addressText"
/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="-76dp"
android:layout_toRightOf="#+id/numberText"
android:backgroundTint="#color/design_default_color_error"
android:text="Revoke Access"
android:textSize="10sp" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button3"
android:layout_marginLeft="-76dp"
android:layout_marginTop="0dp"
android:layout_toRightOf="#+id/numberText"
android:backgroundTint="#android:color/holo_green_dark"
android:text="Grant Access"
android:textSize="10sp" />
</RelativeLayout>
I want to know if what I am doing so far is the correct way of making this possible or not.
I create one recyclerview with address. When this recyclerview is empty, want one spesicif LinearLayout appear and when recyclerView has one or more items this LinearLayout disapear.But it is not working. I use funtions setVisibility(). Please help!!!
My code for xml is:
<?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/user_location_bg_color"
android:orientation="vertical"
tools:context=".UserLocationActivity">
<ImageButton
android:id="#+id/user_location_back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="50dp"
android:background="#color/my_account_bg_color"
android:contentDescription="#null"
android:src="#drawable/ic_back" />
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="40dp"
android:text="#string/user_location_text"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:background="#color/black" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/coffee_recycler_bg_color" />
<LinearLayout
android:id="#+id/empty_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
tools:visibility="invisible">
<pl.droidsonroids.gif.GifImageView
android:id="#+id/location_giffy"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:src="#drawable/location_gif" />
<TextView
android:id="#+id/user_location_blank_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="60dp"
android:gravity="center"
android:text="#string/user_address_blank_text"
android:textColor="#color/black"
android:textSize="15sp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center|bottom"
android:orientation="vertical">
<Button
android:id="#+id/add_new_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="10dp"
android:backgroundTint="#color/btn_add_new_address"
android:text="#string/btn_add_new_address_text"
android:textAllCaps="false"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
My code for Activity is:
public class UserLocationActivity extends AppCompatActivity implements AddressAdapter.OnAddressListener {
//Init Variables
RecyclerView recyclerAddress;
private FirebaseDatabase db = FirebaseDatabase.getInstance();
private DatabaseReference ref = db.getReference().child("UserAddress");
private AddressAdapter adapter;
private ArrayList<UserLocation> list;
public LinearLayout empty_address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_location);
recyclerAddress = findViewById(R.id.recycler_address);
recyclerAddress.setHasFixedSize(true);
recyclerAddress.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new AddressAdapter(this, list, this);
recyclerAddress.setAdapter(adapter);
empty_address = findViewById(R.id.empty_address);
if (adapter.getItemCount() == 0) {
//making it semi-transparent
empty_address.setVisibility(LinearLayout.VISIBLE);
}
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UserLocation userLocation = dataSnapshot.getValue(UserLocation.class);
list.add(userLocation);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onAddressItemDelete(int position) {
}
}
My adapter code is:
public class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.AddressViewHolder> {
private List<UserLocation> listData = new ArrayList<>();
UserLocationActivity userLocationActivity;
private OnAddressListener mOnAddressListener;
public AddressAdapter(UserLocationActivity userLocationActivity, List<UserLocation> listData, OnAddressListener onAddressListener){
this.listData = listData;
this.userLocationActivity = userLocationActivity;
this.mOnAddressListener = onAddressListener;
}
#NonNull
#Override
public AddressViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(userLocationActivity).inflate(R.layout.address_item , parent, false);
return new AddressViewHolder(v,mOnAddressListener);
}
#Override
public void onBindViewHolder(#NonNull AddressViewHolder holder, int position) {
UserLocation userLocation = listData.get(position);
holder.addressItem.setText(userLocation.getUserLocation());
}
#Override
public int getItemCount() {
if (listData.size() == 0){
userLocationActivity.empty_address.setVisibility(LinearLayout.VISIBLE);
}
return listData.size();
}
public static class AddressViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView addressItem;
public ImageView btnAddressItemDelete;
OnAddressListener onAddressListener;
public AddressViewHolder(View itemView, OnAddressListener onAddressListener){
super(itemView);
addressItem = itemView.findViewById(R.id.address_item);
btnAddressItemDelete = itemView.findViewById(R.id.btn_address_item_delete);
this.onAddressListener = onAddressListener;
}
#Override
public void onClick(View v) {
onAddressListener.onAddressItemDelete(getAdapterPosition());
}
}
public interface OnAddressListener{
void onAddressItemDelete(int position);
}
}
It seems there's a bug in your code, I have fixed it.
The bug is you're checking recyclerView is empty first then adding the data into recyclerView
public class UserLocationActivity extends AppCompatActivity implements AddressAdapter.OnAddressListener {
//Init Variables
RecyclerView recyclerAddress;
private FirebaseDatabase db = FirebaseDatabase.getInstance();
private DatabaseReference ref = db.getReference().child("UserAddress");
private AddressAdapter adapter;
private ArrayList<UserLocation> list;
public LinearLayout empty_address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_location);
recyclerAddress = findViewById(R.id.recycler_address);
recyclerAddress.setHasFixedSize(true);
recyclerAddress.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new AddressAdapter(this, list, this);
recyclerAddress.setAdapter(adapter);
empty_address = findViewById(R.id.empty_address);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UserLocation userLocation =
dataSnapshot.getValue(UserLocation.class);
list.add(userLocation);
}
adapter.notifyDataSetChanged();
if (list.size() == 0) {
empty_address.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onAddressItemDelete(int position) {
}
}
I am retrieving Data from MySQL Database in Android and I am using Recyclerview .I test php file and it is working fine but nothing shows in the activity. I checked every thing and it seems fine, I don't know what is the problem ?
Waiting Activity :
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="1dp"
android:layout_height="1dp"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="51dp" />
</RelativeLayout>
list_layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/imageView"
android:layout_width="120dp"
android:layout_height="90dp"
android:padding="4dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:text=" Waiting Time :"
android:textColor="#000000"
android:textStyle="bold"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"/>
<TextView
android:id="#+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/imageView"
android:text="00"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textViewRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewTime"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/imageView"
android:background="#color/colorPrimary"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Bus Number : "
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewBusNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewRating"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/imageView"
android:text="255"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large" />
</RelativeLayout>
</LinearLayout>
WaitingActivity :
public class WaitingActivity extends AppCompatActivity {
private static final String URL_PRODUCTS = "http://192.168.1.2/Android/v1/test1.php";
List<Product> productList;
RecyclerView recyclerView;
ProductsAdapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waiting);
recyclerView = (RecyclerView) findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void loadProducts() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for (int i = 0; i < products.length(); i++) {
JSONObject productObject = products.getJSONObject(i);
int Temp_dt = productObject.getInt("Temp_dt");
int BusNumber =productObject.getInt("BusNumber");
Product product = new Product(Temp_dt, BusNumber);
productList.add(product);
}
adapter = new ProductsAdapter(WaitingActivity.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(WaitingActivity.this, error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
Product class :
public class Product {
private int Temp_dt;
private int BusNumber;
public Product(int Temp_dt, int BusNumber) {
this.Temp_dt = Temp_dt;
this.BusNumber = BusNumber ;
}
public int getWaitingTime() {
return Temp_dt;
}
public int getBusNumber() {
return BusNumber ;
}
}
ProductAdapter :
public class ProductsAdapter extends
RecyclerView.Adapter<ProductsAdapter.ProductViewHolder> {
private Context mCtx;
private List<Product> productList;
public ProductsAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.list_layout, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
holder.textViewTime.setText(String.valueOf(product.getWaitingTime()));
holder.textViewBusNumber.setText(String.valueOf(product.getBusNumber()));
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTime;
TextView textViewBusNumber;
public ProductViewHolder(View itemView) {
super(itemView);
textViewTime = itemView.findViewById(R.id.textViewTime);
textViewBusNumber = itemView.findViewById(R.id.textViewBusNumber);
}
}
}
I expect to show temp_dt and waiting time from php file but the actual output is nothing just empty activity.
I'm trying to fetch the data from my Firebase database but from some reason it doesn't work, so I'll try to provide as much info as posible ..
This is the database snapshot:
This is a POJO class:
public class Result2 implements Serializable {
private int score;
private String userName;
public Result2(int score, String userName) {
this.score = score;
this.userName = userName;
}
public int getScore() {
return score;
}
public String getUserName() {
return userName;
}
}
This is my activitys layout called activity_results.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:weightSum="2"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:textColor="#000"
android:textSize="16sp"
android:gravity="center"
android:text="USERNAME"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<TextView
android:textColor="#000"
android:textSize="16sp"
android:text="SCORE"
android:gravity="center"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
<View
android:background="#000"
android:layout_width="match_parent"
android:layout_height="1dp"
/>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:clipToPadding="false"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
As you can see, I want to have 2 TextViews that will act like tabs and a RecyclerView underneath that will show the data
Here is my Adapters ViewHolder layout called score_view_holder.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/username"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textSize="14sp" />
<TextView
android:id="#+id/score"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textSize="14sp" />
</LinearLayout>
<View
android:background="#4545"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"/>
So it will contain two horizontal TextViews and a View as a line below..
Here is my Adapter:
public class ScoreAdapter extends RecyclerView.Adapter<ScoreAdapter.ScoreViewHolder> {
private List<Result2> results = new ArrayList<>();
public void setResults(List<Result2> results) {
this.results.clear();
this.results.addAll(results);
notifyDataSetChanged();
}
#Override
public ScoreAdapter.ScoreViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.score_view_holder, parent, false);
return new ScoreAdapter.ScoreViewHolder(view);
}
#Override
public void onBindViewHolder(ScoreAdapter.ScoreViewHolder holder, int position) {
Result2 result = getResult(position);
if (result != null) {
holder.setUsername(result.getUserName() != null ? result.getUserName() : "-");
holder.setScore(String.valueOf(result.getScore()));
}
}
private Result2 getResult(int position) {
return !results.isEmpty() ? results.get(position) : null;
}
#Override
public int getItemCount() {
return results.size();
}
public class ScoreViewHolder extends RecyclerView.ViewHolder {
private TextView username;
private TextView score;
public ScoreViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
score = itemView.findViewById(R.id.score);
}
public void setUsername(String username) {
this.username.setText(username);
}
public void setScore(String score) {
this.score.setText(score);
}
}
}
It should get List of Result2 objects and just set text in those two TextViews (username and score)
And finally my Activity where all the magic doesn't happen :)
public class Results extends AppCompatActivity {
private DatabaseReference mDatabase;
private ScoreAdapter scoreAdapter;
private RecyclerView recyclerView;
private List<Result2> results = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
recyclerView = findViewById(R.id.recycler_view);
scoreAdapter = new ScoreAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(scoreAdapter);
mDatabase = FirebaseDatabase.getInstance().getReference();
loadResults();
}
private void loadResults() {
mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Result2 result = childSnapshot.getValue(Result2.class);
if(result != null) {
results.add(result);
}
}
Toast.makeText(Results.this, String.valueOf(results.size()), Toast.LENGTH_SHORT).show();
scoreAdapter.setResults(results);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
}
Funniest thing, Toast shows correct number of Results, but when scoreAdapter.setResults(results); is called, screen blinks and goes back to first screen... Does it have something to do with a POJO class, or onDataChange method or main thread?
I tried with debugging and also funny thing here.. This is what is caught on breakpoint inside ScoreAdapter setResult method:
I tried setting breakpoints inside onBindViewHolder and getResults() but none of them gets called :o
if(result != null) {
results.add(result);
}
See here you are checking result != null. But result is a reference variable of type Results. So it will not be null, it will contains some value.
So, try removing that if statement and do only -
results.add(result);
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...