Array Adapter Crash - java

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

Related

Can't convert object of type java.util.ArrayList to type com.example.soas.POJO.Service

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();
}
});

Using an unspecified index

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.

how to get the post key with position in Firebase Android

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();

Getting error index out of bound exception in my recyclerview

I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}

Show data from Firebase in RecyclerView on Android

I currently have implemented RecyclerView, but my CarView does not show the data.
These are my current data in Firebase:
But the RecyclerView shows all three CardViews, but without the records:
These are the files I'm using:
DomiciliarySearchFragment.java
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
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 com.didierzuniga.domix.R;
import com.didierzuniga.domix.adapter.OrderAdapterRecyclerView;
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.HashMap;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* A simple {#link Fragment} subclass.
*/
public class DomiciliarySearchFragment extends Fragment {
#Bind(R.id.recycler_order) RecyclerView recyclerView;
public DomiciliarySearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_domiciliary_search, container, false);
showToolbar(getResources().getString(R.string.tab_search), true, view);
ButterKnife.bind(this, view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
new GetDataFromFirebase().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("order");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, String> values = (HashMap<String, String>) dataSnapshot.getValue();
recyclerView.setAdapter(new OrderAdapterRecyclerView(values));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});
return view;
}
private class GetDataFromFirebase extends AsyncTask<Void,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... voids) {
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
public void showToolbar(String tittle, boolean upButton, View view){
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(tittle);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
}
}
OrderAdapterRecyclerView.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.didierzuniga.domix.R;
import java.util.HashMap;
import java.util.Map;
public class OrderAdapterRecyclerView extends RecyclerView.Adapter<OrderAdapterRecyclerView.ViewHolder>{
private HashMap<String, String> values;
public OrderAdapterRecyclerView(HashMap<String, String> values) {
this.values = values;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_order,parent,false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.fromm.setText(values.get(position));
holder.too.setText(values.get(position));
holder.moneyToPayy.setText(values.get(position));
}
#Override
public int getItemCount() {
return values.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView fromm;
private TextView too;
private TextView moneyToPayy;
ViewHolder(View itemView) {
super(itemView);
fromm = (TextView) itemView.findViewById(R.id.from);
too = (TextView) itemView.findViewById(R.id.to);
moneyToPayy = (TextView) itemView.findViewById(R.id.moneyToPay);
}
}
}
Model: Order.java
public class Order {
public String uid;
public String oFrom;
public String oTo;
public String oHeader;
public String oDescription;
public String oMoneyToPay;
public String oAuthor;
public boolean completed;
public Order(){
}
public Order(String oFrom, String oTo, String oHeader, String oDescription, String oMoneyToPay, String oAuthor) {
this.oFrom = oFrom;
this.oTo = oTo;
this.oHeader = oHeader;
this.oDescription = oDescription;
this.oMoneyToPay = oMoneyToPay;
this.oAuthor = oAuthor;
this.completed = false;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getoFrom() {
return oFrom;
}
public void setoFrom(String oFrom) {
this.oFrom = oFrom;
}
public String getoTo() {
return oTo;
}
public void setoTo(String oTo) {
this.oTo = oTo;
}
public String getoHeader() {
return oHeader;
}
public void setoHeader(String oHeader) {
this.oHeader = oHeader;
}
public String getoDescription() {
return oDescription;
}
public void setoDescription(String oDescription) {
this.oDescription = oDescription;
}
public String getoMoneyToPay() {
return oMoneyToPay;
}
public void setoMoneyToPay(String oMoneyToPay) {
this.oMoneyToPay = oMoneyToPay;
}
public String getoAuthor() {
return oAuthor;
}
public void setoAuthor(String oAuthor) {
this.oAuthor = oAuthor;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
¿What I need to do to be able to display the registers in each CardView?
Thank you!
In DomiciliarySearchFragment.java /onDataChange,
Can you confirm that hashmap has been correctly populated?
I had a similar problem, but the reason was that the data was not stored correctly in the collection
Thanks uguboz, I should have use dataSnapshot.getChildren(), and get all the records one by one in a loop
rv = (RecyclerView) view.findViewById(R.id.recycler_order);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
orders = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new OrderAdapter(orders);
rv.setAdapter(adapter);
database.getReference().child("order").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
orders.removeAll(orders);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Order order = snapshot.getValue(Order.class);
orders.add(order);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you everyone.

Categories

Resources