Hello StackOverflow Community, I wrote a Code to Search Users in the Firebase Database and every time I try to launch the Code it doesn't Show me the users.
In my Run log I get the following Message:
W/PersistentConnection: pc_0 - Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding '".indexOn": "username"' at users to your security and Firebase Database rules for better Performance
This is the Code which I wrote:
package com.example.ts.tsp.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.example.ts.tsp.Adapter.UserAdapter;
import com.example.ts.tsp.Model1.User;
import com.example.ts.tsp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class SearchFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
EditText search_bar;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
search_bar = view.findViewById(R.id.search_bar);
mUsers = new ArrayList<>();
userAdapter = new UserAdapter(getContext(), mUsers);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
searchUsers(s.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
private void searchUsers(String s){
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("User");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")){
mUsers.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
And the Other Class:
package com.example.ts.tsp.Adapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.ts.tsp.Fragment.ProfileFragment;
import com.example.ts.tsp.Model1.User;
import com.example.ts.tsp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.Viewholder>{
private Context mContext;
private List<User> mUsers;
private FirebaseUser firebaseUser;
public UserAdapter(Context mContext, List<User> mUsers) {
this.mContext = mContext;
this.mUsers = mUsers;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext) .inflate(R.layout.user_item, viewGroup, false);
return new UserAdapter.Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final Viewholder viewHolder, int i) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final User user = mUsers.get(i);
viewHolder.btn_follow.setVisibility(View.VISIBLE);
viewHolder.username.setText(user.getUsername());
viewHolder.fullname.setText(user.getFullname());
Glide.with(mContext) .load(user.getImageurl()) .into(viewHolder.image_Profile);
isFollowing(user.getId(), viewHolder.btn_follow);
if (user.getId().equals(firebaseUser.getUid())){
viewHolder.btn_follow.setVisibility(View.GONE);
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences( "PREFS", Context.MODE_PRIVATE) .edit();
editor.putString("profileid", user.getId());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
viewHolder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.btn_follow.getText().toString().equals("follow")) {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).removeValue();
}
}
});
}
#Override
public int getItemCount() {
return 0;
}
public class Viewholder extends RecyclerView.ViewHolder{
public TextView username;
public TextView fullname;
public CircleImageView image_Profile;
public Button btn_follow;
public Viewholder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
fullname = itemView.findViewById(R.id.fullname);
image_Profile = itemView.findViewById(R.id.image_Profile);
btn_follow = itemView.findViewById(R.id.btn_follow);
}
}
private void isFollowing (final String userid, final Button button) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Follow").child(firebaseUser.getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(userid).exists()){
button.setText("following");
} else {
button.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I hope someone can help you
Best Regard Tim schmitt
For using orderby:
FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
you have to add index on the specific field, update your rules in the Firebase Database console.
{
"rules": {
// By default all nodes are private
".read":false,
".write":false,
"Users": {
".read": true,
".write": "(auth!=null)",
".indexOn" : ["username"]
}
}
}
I would recommend using Cloud Firestore instead of Firebase Realtime Database.
Related
My items are fetching information from database and showing the list in recycleview.
I want to get the unique id by clicking the each.How can I get it?Here is my code of Myadapter class and the java activity where I have worked on to show the user details.
My Code:
MyAdapter.class:
package com.example.bookingapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
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) {
User user = list.get(position);
holder.name.setText(user.getname());
holder.email.setText(user.getemail());
holder.phone.setText(user.getphone());
holder.specialization.setText(user.getSpecialization());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
public View mView;
TextView name, email, phone, specialization;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvname);
email = itemView.findViewById(R.id.tvemail);
phone = itemView.findViewById(R.id.tvphone);
specialization = itemView.findViewById(R.id.tvspecialization);
}
}
}
list:
package com.example.bookingapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Doctorslist extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database;
MyAdapter myAdapter;
ArrayList<User> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctorslist);
recyclerView = findViewById(R.id.userList);
database = FirebaseDatabase.getInstance().getReference("Doctors");
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) {
}
});
}
}
I tried with this code in MyAdapter.java 's onBindViewHolder but it shows error
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MyAdapter.this,RegisterPatientActivity.class);
intent.putExtra("userKey",getRef(position).getKey().toString());
startActivity(intent);
}
});
I manage to solved my own question just by reconstructing my code.
1. In the adapter class, I created an interface for itemClickListener
public interface RecyclerViewItemClick {
public void OnItemClickListener(UsersViewHolders holder, int position);
}
and create a global
private RecyclerViewItemClick mListener;
add it to constructor
public MyAdapter(Context context, ArrayList<User>list,RecyclerViewItemClick listener) {
this.context = context;
this.list = list;
this.mListener = listener;
}
2. In onBindViewHolder() I passed the holder and the position
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.OnItemClickListener(holder, position);
}
});
}
3. In your activity, add this code. Declare a global variable for ArrayList to store the keys and call the addListenerForSingleValueEvent to your DatabaseReference
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
String uid = datas.getKey();
//mUserKey is an ArrayList<String>
mUserKey.add(uid);
User user = dataSnapshot.getValue(User.class);
list.add(user);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
4. Now add this to get the key for every position
mAdapter = new MyAdapter(new MyAdapter.RecyclerViewItemClick() {
#Override
public void OnItemClickListener(MyAdapter.MyViewHolder holder, int position) {
String userKey = mUserKey.get(position);
//do you job
}
});
I am facing error While retrieving data from firebase Here is the error that i am receiving while getting data from firebase..
com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type com.example.soas.POJO.Service
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##19.3.0:435)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##19.3.0:231)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##19.3.0:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##19.3.0:203)
at com.example.soas.Activities.Services$2.onDataChange(Services.java:80)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.3.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.3.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.3.0:55)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2020-11-03 14:53:29.178 9848-9848/com.example.soas I/Process: Sending signal. PID: 9848 SIG: 9
Firebase Database Structure:
Services.Java
package com.example.soas.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.soas.Adapters.ServiceAdapter;
import com.example.soas.POJO.Service;
import com.example.soas.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Services extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton fab;
FirebaseDatabase database;
DatabaseReference reference;
ArrayList<Service> serviceList;
String user;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_services);
database = FirebaseDatabase.getInstance();
recyclerView = findViewById(R.id.serviceRecycler);
fab = findViewById(R.id.fab);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser().getUid();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
database = FirebaseDatabase.getInstance();
reference = database.getReference("Services");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Services.this, AddNewService.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
if (reference != null) {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
serviceList = new ArrayList<>();
for (DataSnapshot ds: snapshot.getChildren()) {
if (ds.getKey().equals(user)) {
serviceList.add(ds.getValue(Service.class));
ServiceAdapter serviceAdapter = new ServiceAdapter(serviceList);
recyclerView = findViewById(R.id.serviceRecycler);
recyclerView.setAdapter(serviceAdapter);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Services.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Service.class(Object)
package com.example.soas.POJO;
public class Service {
public String name;
public Service() {
}
public Service(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ServiceAdapter.java
package com.example.soas.Adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.soas.POJO.Service;
import com.example.soas.R;
import java.util.ArrayList;
public class ServiceAdapter extends RecyclerView.Adapter<ServiceAdapter.MyViewHolder> {
ArrayList<Service> serviceList;
public ServiceAdapter(ArrayList<Service> serviceList) {
this.serviceList = serviceList;
}
#NonNull
#Override
public ServiceAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.service_item,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ServiceAdapter.MyViewHolder myViewHolder, int i) {
myViewHolder.name.setText(serviceList.get(i).getName());
// myViewHolder.price.setText(serviceList.get(i).getPrice());
}
#Override
public int getItemCount() {
return serviceList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name, price;
public MyViewHolder(View view) {
super(view);
name = itemView.findViewById(R.id.vServiceName);
price = itemView.findViewById(R.id.servicePrice);
}
}
}
You're missing a for loop over the 1...4 children in your JSON. In addition: you're loading all Services, while you only need the ones for the current user, so your code is wasting bandwidth and likely less secure.
To fix both problems, you can listen one level lower in the JSON tree, and update the code on onDataChange to match:
reference.child(user).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
serviceList = new ArrayList<>();
for (DataSnapshot ds: snapshot.getChildren()) {
serviceList.add(ds.getValue(Service.class));
}
ServiceAdapter serviceAdapter = new ServiceAdapter(serviceList);
recyclerView = findViewById(R.id.serviceRecycler);
recyclerView.setAdapter(serviceAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Services.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.
But the values are not getting retrieved. It displays a blank activity. I have attached the code.
Applications.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Applications extends AppCompatActivity {
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
RecyclerView recyclerView;
FirebaseUser user;
FirebaseAuth mAuth;
ArrayList<Post> posts;
MyAdap adap;
ProgressDialog pd;
long maxid=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_applications);
recyclerView = findViewById(R.id.work);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
posts = new ArrayList<>();
pd= new ProgressDialog(Applications.this);
pd.setMessage("Loading...");
pd.show();
getSupportActionBar().setTitle("Your Applications");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Job Applications");
Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Post p = ds.getValue(Post.class);
posts.add(p);
}
pd.dismiss();
adap = new MyAdap(Applications.this, posts);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
}
}
Posts.java
public class Post {
private String jobtitle, jobtype, company, location;
public Post() {
}
public Post(String jobtitle, String jobtype, String company, String location) {
this.jobtitle = jobtitle;
this.jobtype = jobtype;
this.company = company;
this.location = location;
}
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getJobtype() {
return jobtype;
}
public void setJobtype(String jobtype) {
this.jobtype = jobtype;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
MyAdap.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdap extends RecyclerView.Adapter<MyAdap.ViewHolder> {
Context cb;
ArrayList<Post> posts;
public MyAdap(Context c, ArrayList<Post> applications){
cb=c;
posts=applications;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.jobTitle.setText(posts.get(position).getJobtitle());
holder.jobType.setText(posts.get(position).getJobtype());
holder.location.setText(posts.get(position).getLocation());
holder.companyName.setText(posts.get(position).getCompany());
}
#Override
public int getItemCount() {
return posts.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView jobTitle, jobType,companyName,location;
public ViewHolder(#NonNull View itemView) {
super(itemView);
jobTitle = itemView.findViewById(R.id.jobTitle);
jobType = itemView.findViewById(R.id.jobType);
companyName = itemView.findViewById(R.id.companyName);
location = itemView.findViewById(R.id.location);
}
}
}
Here is the image of the database.
I think you have a problem with your orderByChild and equalTo method in the Query section. Please try without the Query and if you want to add sorting read details here.
And one more thing you don't have any jobtype in your database but in your POJO class you have this field in your Constructor.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Post p = ds.getValue(Post.class);
posts.add(p);
}
pd.dismiss();
adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
You are not attaching adapter to recycle view
adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap)
you need to set adpater to recycle view
As said by abdul add the adapter to the recycler view and also add the android lifecycle method onStart(); method and in the add adapter.startlisteneing();
I am creating an app using swipecards. It is supposed to pull through data from the Bookmakers Firebase table however when I launch it it crashes the app.
The code for the 3 referenced Java filed is below but there is no bugs and I can't spot the reason why it crashes.
BETSWIPE.java
package com.example.swoddz.swoddz;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import java.util.List;
public class BetSwipe extends AppCompatActivity {
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
private FirebaseAuth mAuth;
List<cards2> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
//add the view via xml or programmatically
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bet_swipe);
al = new ArrayList<>();
al.add("php");
arrayAdapter = new ArrayAdapter<>(this, R.layout.item2, R.id.helloText, al );
rowItems = new ArrayList<cards2>();
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowItems.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(BetSwipe.this, "Left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(BetSwipe.this, "Right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(BetSwipe.this, "clicked!", Toast.LENGTH_SHORT).show();
}
});
}
public void checkBookmakers() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference BookmakerDB = FirebaseDatabase.getInstance().getReference().child("Football-Bets");
BookmakerDB.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()){
al.add(dataSnapshot.child("Bookmaker").getValue().toString());
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
ArryayApadpter2.JAVA
package com.example.swoddz.swoddz;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by manel on 9/5/2017.
*/
public class arrayAdapter2 extends ArrayAdapter<cards>{
Context context;
public arrayAdapter2(Context context, int resourceId, List<cards> items){
super(context, resourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent){
cards card_item = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
TextView Bookmaker = (TextView) convertView.findViewById(R.id.name);
ImageView image = (ImageView) convertView.findViewById(R.id.image);
Bookmaker.setText(card_item.getName());
// image.setImageResource(R.mipmap.ic_launcher);
return convertView;
}
}
CARDS2.Java
package com.example.swoddz.swoddz;
public class cards2 {
private String userId;
private String Bookmaker;
public cards2(String userId, String name){
this.userId = userId;
this.Bookmaker = Bookmaker;
}
public String getUserId(){
return userId;
}
public void setUserID(String userID){
this.userId = userId;
}
public String getBookmaker(){
return Bookmaker;
}
public void setBookmaker(String Bookmaker){
this.Bookmaker = Bookmaker;
}
}
Stack Trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.swoddz.swoddz, PID: 371
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.remove(ArrayList.java:477)
at com.example.swoddz.swoddz.BetSwipe$1.removeFirstObjectInAdapter(BetSwipe.java:63)
at com.lorentzos.flingswipe.SwipeFlingAdapterView$1.onCardExited(SwipeFlingAdapterView.java:223)
at com.lorentzos.flingswipe.FlingCardListener$1.onAnimationEnd(FlingCardListener.java:256)
at android.view.ViewPropertyAnimator$AnimatorEventListener.onAnimationEnd(ViewPropertyAnimator.java:1121)
at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1149)
at android.animation.ValueAnimator.doAnimationFrame(ValueAnimator.java:1309)
at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
at android.animation.AnimationHandler.-wrap2(AnimationHandler.java)
at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
at android.view.Choreographer.doCallbacks(Choreographer.java:702)
at android.view.Choreographer.doFrame(Choreographer.java:635)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
Database Structure
package com.novela.minha.novela;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<Beaches> beaches;
private long itemId;
private Firebase firebase;
Firebase likeRef;
FirebaseAuth user;
public com.firebase.client.Firebase Ref ;
private DatabaseReference Database = FirebaseDatabase.getInstance().getReference();
private DatabaseReference mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
private boolean mProcessLike = false;
public MyAdapter(Context c, ArrayList<Beaches> beaches){
this.c= c;
this.beaches=beaches;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
final MyHolder holder= new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final MyHolder holder, final int position) {
final String post_key = Database.getRef(position).getKey().toString(); // <- Error
mDatabaseLike.keepSynced(true);
holder.nameTxt.setText(beaches.get(position).getName());
holder.textoTxt.setText(beaches.get(position).getTexto());
holder.siteTxt.setText(beaches.get(position).getSite());
holder.emissoraTxt.setText(beaches.get(position).getEmissora());
holder.enderecoTxt.setText(beaches.get(position).getEndereco());
PicassoClient.downloadimg(c, beaches.get(position).getUrl(),holder.img);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String url = beaches.get(position).getEndereco().toString();
Intent intent = new Intent( v.getContext().getApplicationContext(), Web.class);
intent.putExtra("VALOR", url);
v.getContext().getApplicationContext().startActivity(intent);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
Toast.makeText(v.getContext(), post_key, Toast.LENGTH_SHORT).show();
mProcessLike = true ;
if (mProcessLike) {
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
#Override
public int getItemCount() {
return beaches.size();
}
}
Note that getRef does not accept position,
returns an error, which could be done in the code, I already searched here in the Forum but I did not find a solution, thank you ,Note that getRef does not accept position,
returns an error, which could be done in the code, I already searched here in the Forum
but I did not find a solution, I'm new to programming, thank you
final String post_key = Database.push().getKey();