My main activity shows an empty RecyclerView. My CardView is not displayed.
The data is stored in a Firebase Database but is not displayed for some reason.
I have also searched the web but nothing helped me. I tried everything listed on web as well as on Stack Overflow.
MainActivity.java
public class MainActivity1 extends AppCompatActivity {
private RecyclerView mQuestionList;
private CardView mCardVieww;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference mDatabaseUsers;
private LinearLayoutManager layoutManager;
private DatabaseReference mDatabaseCurrentUsers;
private DatabaseReference mDatabaseLike;
private boolean mProcessLike = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
mAuth=FirebaseAuth.getInstance();
mAuthListener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser()== null){
Intent loginIntent=new Intent(MainActivity1.this,LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase= FirebaseDatabase.getInstance().getReference().child("Question");
mDatabaseUsers=FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike=FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mDatabase.keepSynced(true);
mQuestionList=(RecyclerView) findViewById(R.id.question_list);
layoutManager=new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mQuestionList.setHasFixedSize(true);
mQuestionList.setLayoutManager(layoutManager);
checkUserExist();
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter <Question,QuestionViewHolder> fireRecyclerAdapter = new FirebaseRecyclerAdapter <Question,QuestionViewHolder>(
Question.class,
R.layout.question,
QuestionViewHolder.class,
mDatabase
){
#Override
protected void populateViewHolder(QuestionViewHolder viewHolder,Question model, int position){
final String post_key = getRef(position).getKey()
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(),model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setLikeBtn(post_key);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity1.this,post_key,Toast.LENGTH_LONG).show();
Intent singleQuestionIntent=new Intent(MainActivity1.this,QuestionSingleActivity.class);
singleQuestionIntent.putExtra("question_id",post_key);
startActivity(singleQuestionIntent);
}
});
viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mQuestionList.setHasFixedSize(true);
mQuestionList.setLayoutManager(layoutManager);
mQuestionList.setAdapter(fireRecyclerAdapter);
}
//cgeck user exist or not
private void checkUserExist() {
if (mAuth.getCurrentUser() != null) {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)) {
Intent setupIntent = new Intent(MainActivity1.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
public static class QuestionViewHolder extends RecyclerView.ViewHolder{
View mView;
ImageButton mLikeBtn;
DatabaseReference mDatabaseLike;
FirebaseAuth mAuth;
public QuestionViewHolder(View itemView) {
super(itemView);
mView=itemView;
mLikeBtn=(ImageButton) mView.findViewById(R.id.likeBtn);
mDatabaseLike= FirebaseDatabase.getInstance().getReference().child("Likes");
mAuth=FirebaseAuth.getInstance();
mDatabaseLike.keepSynced(true);
}
public void setLikeBtn(final String post_key){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mLikeBtn.setImageResource(R.mipmap.thumb_grey);
}else{
mLikeBtn.setImageResource(R.mipmap.thumb_grey);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setTitle(String title){
TextView post_title=(TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc=(TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setUsername(String username){
TextView post_username=(TextView) mView.findViewById(R.id.post_username);
post_username.setText(username);
}
public void setImage(final Context ctx, final String image){
final ImageView post_image=(ImageView) mView.findViewById(R.id.post_image);
//Picasso.with(ctx).load(image).into(post_image);
Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(image).into(post_image);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_add){
startActivity(new Intent(MainActivity1.this,PostActivity.class));
}
if(item.getItemId()==R.id.action_logout){
logout();
}
if(item.getItemId()==R.id.action_Qp){
startActivity(new Intent(MainActivity1.this,MainActivity2.class));
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
Question.java
public class Question {
private CardView mCardView;
private String title;
private String desc;
private String image;
private String username;
public Question(){
}
public Question(String title, String desc, String image,String username) {
this.title = title;
this.desc = desc;
this.image = image;
this.username = username;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
activity_main1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.akhil.rtmnuforum.MainActivity1">
<android.support.v7.widget.RecyclerView
android:id="#+id/question_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
question.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:visibility="visible"
tools:context="com.example.akhil.rtmnuforum.MainActivity1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/post_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#mipmap/add_btn" />
<TextView
android:id="#+id/post_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Post Title Goes here"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="#+id/post_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Question Description Goes here" />
<TextView
android:id="#+id/post_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="username"
android:textSize="12dp"
android:textStyle="bold" />
<ImageButton
android:id="#+id/likeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#color/cardview_light_background"
app:srcCompat="#mipmap/ic_thumb_up_black_24dp" />
</LinearLayout>
</android.support.v7.widget.CardView>
Related
my code
**I have a UserAdapter, and a Search Fragment and the user_item and user class. The problem is, the three Click Listeners to open the "Search Fragment " the app crashe!! and close.
i hope so i give u good explanation for the problem
and thanks for the help in advance
**
public class SearchFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> userList;
EditText search_bar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
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);
userList = new ArrayList<>();
userAdapter = new UserAdapter(getContext(), userList, true);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
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) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
** my code class Use**
public class User {
private String id;
private String username;
private String fullname;
private String imageurl;
private String bio;
public User(String id, String username, String fullname, String imageurl, String bio) {
this.id = id;
this.username = username;
this.fullname = fullname;
this.imageurl = imageurl;
this.bio = bio;
}
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
}
my code UserAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ImageViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean isFragment;
private FirebaseUser firebaseUser;
public UserAdapter(Context context, List<User> users, boolean isFragment){
mContext = context;
mUsers = users;
this.isFragment = isFragment;
}
#NonNull
#Override
public UserAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final UserAdapter.ImageViewHolder holder, final int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final User user = mUsers.get(position);
holder.btn_follow.setVisibility(View.VISIBLE);
isFollowing(user.getId(), holder.btn_follow);
holder.username.setText(user.getUsername());
holder.fullname.setText(user.getFullname());
Glide.with(mContext).load(user.getImageurl()).into(holder.image_profile);
if (user.getId().equals(firebaseUser.getUid())){
holder.btn_follow.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isFragment) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", user.getId());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
} else {
Intent intent = new Intent(mContext, Main2Activity.class);
intent.putExtra("publisherid", user.getId());
mContext.startActivity(intent);
}
}
});
holder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.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);
addNotification(user.getId());
} 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();
}
}
});
}
private void addNotification(String userid){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userid", firebaseUser.getUid());
hashMap.put("text", "started following you");
hashMap.put("postid", "");
hashMap.put("ispost", false);
reference.push().setValue(hashMap);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public TextView fullname;
public CircleImageView image_profile;
public Button btn_follow;
public ImageViewHolder(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){
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
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) {
}
});
}
}
** user_item**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/image_profile"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/image_profile"
android:layout_marginStart="5dp"
android:orientation="vertical"
android:layout_centerVertical="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/username"
android:text="username"
android:maxLines="1"
android:textStyle="bold"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fullname"
android:text="full_name"
android:maxLines="1"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#drawable/button_background"
android:id="#+id/btn_follow"
android:textColor="#color/colorPrimary"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</RelativeLayout>
stack trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: commenting, PID: 24881
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatButton cannot be cast to androidx.recyclerview.widget.RecyclerView
at commenting.Fragment.SearchFragment.onCreateView(SearchFragment.java:47)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
I/Process: Sending signal. PID: 24881 SIG: 9
Fragment.SearchFragment
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment.SearchFragment">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bar"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:id="#+id/toolbar">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_search_light"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/search_bar"
android:background="#android:color/transparent"
android:hint="search_bar"
android:layout_marginStart="10dp"
android:inputType="text"/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bar"
android:id="#+id/recycler_view"/>
</RelativeLayout>
It looks like your search fragment layout doesn't have the RecyclerView component and the button on that layout has the recycler_view id which you try to use to inflate your RecyclerView. That's why you're getting this exception.
Add a RecyclerView to your layout and set its id to recycler_view so that you can grab the RV in your code.
I can't retrieve data from the firebase and view it at recyclerView
this my database at firebaseenter image description here
There are no problem appear but in my run is not display the items this is my run enter image description here
and this my code I tried every thing I don't know what the problem help me please
public class account_preview extends AppCompatActivity {
private ArrayList<outflow>outflows;
private RecyclerView recyclerView;
RecyclerAdapter adapter;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_preview);
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef =
database.getReference("user_account/(username)/bank_accounts/1");
adapter = new RecyclerAdapter(outflows, account_preview.this);
recyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
recyclerView.setLayoutManager(llm);
llm.setOrientation(LinearLayoutManager.VERTICAL);
onStart();
new GetDataFromFirebase().
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
myRef.child("outflow").child("1").addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
outflows=new ArrayList<outflow>();
for (DataSnapshot dataSnapshot1:
dataSnapshot.getChildren()){
outflow values =
dataSnapshot1.getValue(outflow.class);
outflows.add(values);}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." +
error.toException());
}
});
}
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 class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder>{
private Context context;
private ArrayList<outflow> values;
public RecyclerAdapter(ArrayList<outflow> values, account_preview
context) {
this.values = values;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_outflows, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText( values.get(position).getCategory());
holder.c.setText((int) values.get(position).getAmount());
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(values.size()==0){
arr = 0;
}
else{
arr=values.size();
}
}catch (Exception e){
}
return arr;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name,c;
ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.totaloutflow);
c=(TextView)itemView.findViewById(R.id.total);
}
}
}
public class outflow {
private double amount;
private String date;
private String time;
private String attachment;
private String category;
private String location;
private String vendor;
private int rate;
public outflow(double amount, String date, String time, String attachment, String category, String location, String vendor) {
this.amount = amount;
this.date = date;
this.time = time;
this.attachment = attachment;
this.category = category;
this.location = location;
this.vendor = vendor;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
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 getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
activity_account_preview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
list_outflows.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".account_preview">
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#27233A"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
<TextView
android:id="#+id/textView"
android:layout_width="84dp"
android:layout_height="44dp"
android:layout_marginEnd="36dp"
android:layout_marginStart="8dp"
android:padding="5dp"
android:text="(التاريخ)"
android:textColor="#000000"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="64dp"
tools:ignore="MissingConstraints" />
<Button
android:id="#+id/button"
android:layout_width="251dp"
android:layout_height="61dp"
android:layout_marginBottom="24dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#9FB4C7"
android:text="حذف الحساب"
android:textColor="#ffffff"
android:textSize="30dp"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.437"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:background="#D6C9C9"
android:clickable="true"
app:backgroundTint="#D6C9C9"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.976"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#android:drawable/ic_input_add" />
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="392dp"
android:layout_height="64dp"
android:layout_margin="2.5dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="184dp"
app:cardBackgroundColor="#color/lightgrey"
app:cardCornerRadius="4dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="0.30"
android:orientation="vertical">
<TextView
android:id="#+id/totaloutflow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="الفواتير"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp" />
<TextView
android:id="#+id/total"
android:layout_width="388dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:text="ريال سعودي"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
Firebase has its own Adapter for RecyclerView so better use that.
public FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> getmFirebaseAdapter() {
return mFirebaseAdapter;
}
public void setmFirebaseAdapter(FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> mFirebaseAdapter) {
this.mFirebaseAdapter = mFirebaseAdapter;
}
//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
private final TextView image_title ;
public ShowDataViewHolder(final View itemView)
{
super(itemView);
image_title = itemView.findViewById(R.id.taskname);
}
private void Image_Title(String title)
{
image_title.setText(title);
}
}
#Override
public void onStart() {
super.onStart();
FirebaseAuth mauth = FirebaseAuth.getInstance();
String userod = mauth.getCurrentUser().getUid();
myref = FirebaseDatabase.getInstance().getReference("Yourself").child(userod).child("task");
setmFirebaseAdapter(new FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder>(
taskdata.class, R.layout.taskitem, ShowDataViewHolder.class, myref.orderByValue()) {
public void populateViewHolder(final ShowDataViewHolder viewHolder, taskdata model, final int position) {
viewHolder.Image_Title(model.getTaskname());
}
});
recyclerView.setAdapter(getmFirebaseAdapter());
myref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() == null){
Toast.makeText(getContext(),"No Bookmarks added yet!",Toast.LENGTH_SHORT).show();
}else {
mFirebaseAdapter.notifyItemChanged(0);
mFirebaseAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFirebaseAdapter.notifyItemInserted(taskdata2.size()-1);
}
If you need more help on the code please go to my github - https://github.com/afreakyelf/Yourself/blob/master/app/src/main/java/com/example/rajat/yourself/taskadapterhome.java
To solve this, please just add the following lines of code inside the costructor:
public RecyclerAdapter(List<outflow> list, account_preview context) {
this.list = list
this.context = context
}
I have a Fragment class where i want to display a list of layouts where the layout is updated with firebase data values.
This is how my data base looks (user_dubs > user_id > photo id):
Here's the fragment (UPDATED):
public class DubsFragment extends Fragment {
private static final String TAG = "DubsFragment";
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
//widgets
private EditText mthisdub;
private ListView mListView;
//vars
private ArrayList<String> mDubs;
private ArrayAdapter<String> adapter;
private Context mContext;
private PostDubs mpostdubs;
private String userID;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mydubs, container, false);
mListView = (ListView) view.findViewById(R.id.listViewz);
mDubs = new ArrayList<>();
mContext = getActivity();
mpostdubs = new PostDubs();
adapter = new ArrayAdapter<String>(mContext, R.layout.layout_dubs_listitem, R.id.getusername, mDubs);
mListView.setAdapter(adapter);
setupFirebaseAuth();
return view;
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
userID = mAuth.getCurrentUser().getUid();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_userdubs))
.child(userID)
.orderByChild(getString(R.string.field_photoid));
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
mpostdubs = singleSnapshot.getValue(PostDubs.class);
mDubs.add(mpostdubs.getEditdub().toString());
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
Post Dubs Class:
public class PostDubs {
private String editdub;
private String dubdate;
private String user_id;
private String photoid;
private String username;
private Context mContext;
public PostDubs(String user_id, String editdub, String photoid, String dubdate, String username){
this.user_id = user_id;
this.editdub = editdub;
this.dubdate = dubdate;
this.photoid = photoid;
this.username = username;
}
public PostDubs() {
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getEditdub() {
return editdub;
}
public void setEditdub(String editdub) {
this.editdub = editdub;
}
public String getDubdate() {
return dubdate;
}
public void setDubdate(String dubdate) {
this.dubdate = dubdate;
}
public String getPhotoid() {
return photoid;
}
public void setPhotoid(String photoid) {
this.dubdate = photoid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString() {
return "User{" +
"user_id='" + editdub + '\'' +
", phone_number='" + dubdate + '\'' +
'}';
}
}
Here's the layout_dubs_listitem.xml:
<?xml version="1.0" encoding="utf-8" ?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="100dp">
<de.hdodenhof.circleimageview.CircleImageView android:layout_width="75dp"
android:layout_height="75dp"
app:civ_border_color="#color/black"
app:civ_border_width="0.5dp"
android:id="#+id/profile_image"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true" />
<RelativeLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/profile_image"
android:layout_centerVertical="true">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textSize="22sp"
android:textColor="#color/black"
android:id="#+id/editdub"
android:text=""/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textSize="15sp"
android:layout_centerVertical="true"
android:textColor="#color/black"
android:id="#+id/getusername"
android:text=""/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
For the test, I'm just trying to get the edit dub in the layout but it is not working at all. I am sure I am doing something stupid.
Please guide me with this problem and it would be very helpful if you could help me update the layout with other child values like username. Thanks.
I fixed it by ordering my child in the firebase correctly.
I'm new to the concepts of RecyclerView and Firebase; I'm working on this chat app that takes input from the user (message) and takes the DisplayName(Google sign in, so the Username) and stores it to the realtime database of the Firebase. The storing of the "mAuthor" and "mMessage" is working fine, the problem arises when I'm trying to retrieve the data and display it in the recyclerView. There's no crash error as per the Logcat, however, there's nothing getting displayed on my chat app screen (in the recyclerView).
The dependencies of firebase and recyclerView have been carefully added.
Here's my activity class:
private String mDisplayName;
private EditText mMessage;
private ImageView mSendButton;
private RecyclerView mRecycler;
private DatabaseReference mDatabaseReference;
private MyAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mMessage=(EditText) findViewById(R.id.messageInput);
mSendButton=(ImageView) findViewById(R.id.sendButton);
setupDisplayName();
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
mRecycler=(RecyclerView) findViewById(R.id.chat_recycler_view);
mRecycler.setHasFixedSize(true);
LinearLayoutManager layoutManager= new LinearLayoutManager(ChatActivity.this);
mRecycler.setLayoutManager(layoutManager);
mMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
sendMessage();
return true;
}
});
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
private void setupDisplayName(){
Intent mIntent= getIntent();
String option= mIntent.getStringExtra("Options");
if(option.equals("normal")){
SharedPreferences prefs= getSharedPreferences(RegisterActivity.CHAT_PREFS,0);
mDisplayName=prefs.getString(RegisterActivity.DISPLAY_NAME_KEY,null);
Log.d("Google","Shared prefs: DisplayName:"+mDisplayName);
}
else if(option.equals("google")){
SharedPreferences prefs= getSharedPreferences(MainActivity.CHAT_PREFS,0);
mDisplayName=prefs.getString(MainActivity.DISPLAY_NAME_KEY,null);
Log.d("Google","Shared prefs: DisplayName:"+mDisplayName);
}
if(mDisplayName==null)
mDisplayName="Anonymous";
}
private void sendMessage() {
String input= mMessage.getText().toString();
if(!input.equals("")){
Log.d("Google","I sent something");
InstantMessage mObject= new InstantMessage(mDisplayName, input);
mDatabaseReference.child("messages").push().setValue(mObject);
mMessage.setText("");
}
}
#Override
public void onStart() {
super.onStart();
mAdapter= new MyAdapter(mDatabaseReference, mDisplayName);
mRecycler.setAdapter(mAdapter);
}
#Override
public void onStop(){
super.onStop();
mAdapter.CleanUp();
}
Here's my Model class:
public class InstantMessage {
private String mAuthor;
private String mMessage;
public InstantMessage(String mAuthor, String mMessage) {
this.mAuthor = mAuthor;
this.mMessage = mMessage;
}
public InstantMessage() {
}
public String getmAuthor() {
return mAuthor;
}
public void setmAuthor(String mAuthor) {
this.mAuthor = mAuthor;
}
public void setmMessage(String mMessage) {
this.mMessage = mMessage;
}
public String getmMessage() {
return mMessage;
}
}
Here's my Adapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private DatabaseReference mReference;
private String mDisplayName;
private List<InstantMessage> mList;
private ChildEventListener mListener= new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
InstantMessage msg= dataSnapshot.getValue(InstantMessage.class);
mList.add(msg);
Log.d("Google","Datasnapshot added:"+dataSnapshot.toString());
notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
public MyAdapter( DatabaseReference mReference, String mDisplayName) {
this.mReference = mReference.child("messages");
mReference.addChildEventListener(mListener);
this.mDisplayName = mDisplayName;
mList= new ArrayList<>();
}
#NonNull
#Override
public MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_chat_row, parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.ViewHolder holder, int position) {
holder.mAuthorName.setText(mList.get(position).getmAuthor());
holder.mText.setText(mList.get(position).getmMessage());
}
#Override
public int getItemCount() {
Log.d("Google","Item count:"+mList.size());
return mList.size();
}
public void CleanUp(){
mReference.removeEventListener(mListener);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mAuthorName;
TextView mText;
public ViewHolder(View itemView) {
super(itemView);
mAuthorName=(TextView) itemView.findViewById(R.id.Chatauthor);
mText= (TextView) itemView.findViewById(R.id.Chatmessage);
}
}
}
I'm not sure what I'm doing wrong. In the log statement of onChildAdded method, the datasnapshot.toString() returns legit values. However, the Log.d("Google","Item Count:"+mList.size()) returns ItemCount: 1 everytime
PS: Here's the data that is being sent to the firebase: https://imageshack.com/a/img922/1458/HoOWxO.png
My activity_chat_row.xml code:
<?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="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/Chatauthor"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_gravity="start"
android:textColor="#3CB371"
android:gravity="center_vertical"
android:textSize="15sp"
android:textStyle="bold"
android:text="Author"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/Chatmessage"
android:layout_gravity="start"
android:gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:padding="10dp"
android:textSize="15sp"
android:text="Text"
android:textColor="#android:color/primary_text_light"
/>
</LinearLayout>
So I did some research about this but was unable to solve this problem and every solution online led to me to a new error.
I am currently working on an Events App and relatively new to Android Studio.
I have a RecyclerView in an Admin app that verifies all the Event data uploaded on Firebase by an organizer. The organizer uploads the data such as event_tile, event_desc and event_image. This is stored in Firebase under root "Event". Later the Admin App receives these requests in the form of a recycler view, and has a button to approve them. All the approved events are would be stored in a separate table in Firebase with root "Approved_Events".
I am getting stuck in the approval part. The code is running fine with no errors but no data is being uploaded to my Firebase console.
Here is my Main Activity
public class MainActivity extends AppCompatActivity {
private RecyclerView request_eventList;
private DatabaseReference mRef, aRef;
private Button verify_button;
private TextView request_title, request_desc;
private ImageView request_image;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressDialog = new ProgressDialog(this);
mRef = FirebaseDatabase.getInstance().getReference().child("Event");
setContentView(R.layout.activity_main);
request_eventList = (RecyclerView) findViewById(R.id.request_eventList);
request_eventList.setHasFixedSize(true);
request_eventList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Event, RequestViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, RequestViewHolder>(
Event.class,
R.layout.admin_event_row,
RequestViewHolder.class,
mRef
) {
#Override
protected void populateViewHolder(RequestViewHolder viewHolder, Event model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
request_eventList.setAdapter(firebaseRecyclerAdapter);
}
public static class RequestViewHolder extends RecyclerView.ViewHolder {
View mView;
public Button verify_button;
DatabaseReference mRef, aRef;
ProgressDialog progressDialog;
public RequestViewHolder(View itemView) {
super(itemView);
mView = itemView;
progressDialog = new ProgressDialog(mView.getContext());
verify_button = (Button) mView.findViewById(R.id.approve_button);
mRef = FirebaseDatabase.getInstance().getReference().child("Event");
aRef = FirebaseDatabase.getInstance().getReference().child("ApprovedEvents");
verify_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map <String, String> map = (Map<String, String>) dataSnapshot.getValue();
String title_val = map.get("title");
String desc_val = map.get("desc");
String image_val = map.get("image");
aRef.child("approved_title").setValue(title_val);
aRef.child("approved_desc").setValue(desc_val);
aRef.child("approved_image").setValue(image_val);
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
public void setTitle(String title) {
TextView request_title = (TextView) mView.findViewById(R.id.request_title);
request_title.setText(title);
}
public void setDesc(String desc) {
TextView request_desc = (TextView) mView.findViewById(R.id.request_desc);
request_desc.setText(desc);
}
public void setImage(Context ctx, String image) {
ImageView request_image = (ImageView) mView.findViewById(R.id.request_image);
Picasso.with(ctx).load(image).into(request_image);
}
}
}
MainActivity XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.admin.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/request_eventList"
android:clickable="true">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Event Java Class
public class Event {
private String title, desc, image;
public Event(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public Event(){
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
admin_event_row XML file that will fill the recyclerView
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/request_image"
android:src="#drawable/abc_btn_check_material"
android:adjustViewBounds="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/request_title"
android:text="Title will come here "
android:padding="10dp"
android:textStyle="bold"
android:textSize="15dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/request_desc"
android:text="Desc will come here "
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/approve_button"
android:text="Yeah it's Cool "/>
</LinearLayout>
Final App Look
If your Event has more unapproved child, move verify_button.setOnClickListener from Holder to Adapter-populateViewHolder. You have to connect verify_button.setOnClickListener to row in recycleviewer to get values of title, desc and image from clicked item.
protected void populateViewHolder(RequestViewHolder viewHolder, Event model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
final String title = model.getTitle();
final String desc = model.getDesc();
final String image = model.getImage();
final DatabaseReference aRef = FirebaseDatabase.getInstance().getReference();
viewHolder.verify_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String key = aRef.child("ApprovedEvents").push().getKey();
Event event = new Event(title, desc, image );
Map<String, Object> eventValues = event.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/ApprovedEvents/" + key, eventValues);
aRef.updateChildren(childUpdates);
}
});
}
};