How to fetch Firebase data into arrays for recyclerview? - android

This is my HomeActivity
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> mlist;
TextView btnSignOut, UserName;
RecyclerView courseRecycler;
String CourseCode, CourseName;
/*---- Firebase Database stuff ----*/
FirebaseDatabase mFirebaseDatabase;
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
Button btnShow = findViewById(R.id.show);
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
courseRecycler = findViewById(R.id.recyclerviewcourse);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getInstance().getReference();
UserName.setText(user.getDisplayName());
/*------------------------------------------------------------------*/
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
mlist = new ArrayList<CourseModel>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) {
CourseModel value = dataSnapshot1.getValue(CourseModel.class);
CourseModel course = new CourseModel();
String userID = value.getUserId();
course.setUserId(userID);
String courseCode = value.getCourseCode();
course.setCourseCode(courseCode);
for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) {
CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
String courseName = value2.getCourseName();
course.setCourseName(courseName);
mlist.add(course);
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse recyclerAdapter = new RecyclerViewAdapterCourse(mlist, HomeActivity.this);
RecyclerView.LayoutManager recycler = new GridLayoutManager(HomeActivity.this, 2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
courseRecycler.setLayoutManager(recycler);
courseRecycler.setItemAnimator(new DefaultItemAnimator());
courseRecycler.setAdapter(recyclerAdapter);
}
}
This is My RecyclerViewCourse.class
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
class RecyclerViewAdapterCourse extends RecyclerView.Adapter<RecyclerViewAdapterCourse.CourseViewHolder> {
private Context mContext ;
private List<CourseModel> mlist ;
public RecyclerViewAdapterCourse(List<CourseModel> mData, Context mContext) {
this.mContext = mContext;
this.mlist = mData;
}
#Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =LayoutInflater.from(mContext).inflate(R.layout.item_course,parent,false);
CourseViewHolder courseViewHolder = new CourseViewHolder(view);
return courseViewHolder;
}
#Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
CourseModel courselist = mlist.get(position);
holder.userID.setText(courselist.getUserId());
holder.courseCode.setText(courselist.getCourseCode());
holder.courseName.setText(courselist.getCourseName());
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(mlist.size()==0){
arr = 0;
}
else{
arr=mlist.size();
}
}catch (Exception e){
}
return arr;
}
class CourseViewHolder extends RecyclerView.ViewHolder{
TextView userID,courseCode,courseName;
public CourseViewHolder(View itemView) {
super(itemView);
userID = (TextView) itemView.findViewById(R.id.userid);
courseCode= (TextView) itemView.findViewById(R.id.coursecode);
courseName= (TextView) itemView.findViewById(R.id.coursename);
}
}
}
This is My CourseModel.class
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
public class CourseModel {
public String UserId, CourseCode, CourseName;
public String getUserId() {
return UserId;
}
public String getCourseCode() {
return CourseCode;
}
public String getCourseName() {
return CourseName;
}
public void setUserId(String userid) {
this.UserId = userid;
}
public void setCourseCode(String coursecode) {
this.CourseCode = coursecode;
}
public void setCourseName(String coursename) {
this.CourseCode = coursename;
}
}
I want the array list like:
{"***", "TMI4013", "System Programming"}
{"***", "TMI4033", "LogicProgramming"}
I am not really experienced with firebase data retrieval in array. I tried many answers posted in stack. none worked. in some answers, sometime it shows data after a while and then in the realtime database the data get removed, i don't even understand why.
I did not provide the XML files since I tried with local file and generating array in HomeActivity and it worked perfectly.
mlist = new ArrayList<>();
mlist.add(new CourseModel("012223","TMN4013","System Programming"));
mlist.add(new CourseModel("34566","TMN4013","System Programming"));
RecyclerView myrv = (RecyclerView) findViewById(R.id.recyclerview_id);
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,mlist);
myrv.setLayoutManager(new GridLayoutManager(this,3));
myrv.setAdapter(myAdapter);

Retrieve data from firebase and convert list into array like this
for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) {
CourseModel value = dataSnapshot1.getValue(CourseModel.class);
CourseModel course = new CourseModel();
String userID = value.getUserId(); course.setUserId(userID);
String courseCode = value.getCourseCode();
course.setCourseCode(courseCode);
for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) {
CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
String courseName = value2.getCourseName();
course.setCourseName(courseName);
mlist.add(course);
}
}
CourseModel[] array = mlist.toArray(new CourseModel[mlist.size()]);
EDIT:
Change your adapter like this
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, array);
Change the constructor of recyclerView to CourseModel array
public RecyclerViewAdapterCourse(CourseModel[] mData, Context mContext) {
this.mContext = mContext;
this.mArray = mData;
}
#Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
CourseModel courselist = marray[position];
holder.userID.setText(courselist.getUserId());
holder.courseCode.setText(courselist.getCourseCode());
holder.courseName.setText(courselist.getCourseName());
}

Related

Why data apears only after restart the app?

I made small app that gets some values from the user and display it in custom listview in another activity (2nd) after pressing the button in the 1st activity.
The situation now it's works but only after I closing the app and reopen it.
I want it will work immediately after I press the button.
Can someone help me with this issue please ?
mainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList<exampleItem> mExampleList = new ArrayList<>();
RecyclerView mRecyclerView;
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
setInsertButton();
loadData();
buildRecyclerView();
}
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new exampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list8", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list8", json);
editor.apply();
}
private void setInsertButton() {
Button buttonInsert = findViewById(R.id.insert2);
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText line1 = findViewById(R.id.categ2);
final EditText lineimg = findViewById(R.id.summ2);
final EditText line2 = findViewById(R.id.date22);
String lin1 = line1.getText().toString();
String lin2 = line2.getText().toString();
String lin3 = lineimg.getText().toString();
mExampleList.add(new exampleItem(lin1, lin3, lin2));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
saveData();
}
});
}
}
mainActivity2
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<exampleItem> mExampleList = new ArrayList<>();
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setInsertButton();
loadData();
//buildRecyclerView();
}
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new exampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list8", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list8", json);
editor.apply();
}
private void setInsertButton() {
Button buttonInsert = findViewById(R.id.insert);
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText line1 = findViewById(R.id.categ);
final EditText lineimg = findViewById(R.id.summ);
final EditText line2 = findViewById(R.id.date2);
String lin1 = line1.getText().toString();
String lin2 = line2.getText().toString();
String lin3 = lineimg.getText().toString();
mExampleList.add(new exampleItem(lin3, lin2, lin1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
saveData();
finish();
}
});
}
}
Adapter
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class exampleAdapter extends RecyclerView.Adapter<exampleAdapter.ExampleViewHolder> {
private ArrayList<exampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewLine1;
public TextView mTextViewLine2;
public ImageView imageView;
public ExampleViewHolder(View itemView) {
super(itemView);
mTextViewLine1 = itemView.findViewById(R.id.textview_line1);
mTextViewLine2 = itemView.findViewById(R.id.textview_line2);
imageView = itemView.findViewById(R.id.icond);
}
}
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
exampleItem currentItem = mExampleList.get(position);
holder.mTextViewLine1.setText(currentItem.getLine1());
holder.mTextViewLine2.setText(currentItem.getLine2());
if (currentItem.getLineimg().equalsIgnoreCase("s")) {
holder.imageView.setImageResource(R.drawable.salary);
}
if (currentItem.getLineimg().equalsIgnoreCase("e")){
holder.imageView.setImageResource(R.drawable.money);
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Inside loadData() you need to call notifyDataSetChanged() on the mAdapter.
In the class MainActivity under the function "loadData()" you must update the adapter notifying that the data has changed.
The function (loadData()) should look something like:
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared
preferences8", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list8", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
mAdapter.notifyDataSetChanged()
}

How do I get the number of Items in a recyclerView using firebase data?

I create a RecyclerView with a series of CardViews inside. My end goal is being able to change the text inside of an individual CardView in the activity due to the timing of firebase database calls. My question right now is how does one get the number of items in the RecyclerView?
I know that most will reference me to the Adapter.getItemCount() method. However, at the moment that is only returning zero as the adapter seems to have not been created yet. I believe that this question is more along the lines of the timings of when code runs.
The activity class:
package com.cmsc355.forfit;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.cmsc355.forfit.util.exerciseAdapterClass;
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.ArrayList;
import java.util.HashMap;
public class ChallengeView extends AppCompatActivity {
public static Context context;
public static String cCESnapshot;
//Variables
String team;
HashMap<String, String> currChallenges;
ArrayList<String> subAthletes;
ArrayList<String> exerciseList;
ArrayList<String> teamMem;
//System
private Intent intent;
public static String cName;
//XML
private TextView name;
private TextView startDateTV;
private TextView endDateTV;
private TextView description;
private Button bSubscribe;
private Button bDropout;
private ProgressBar difficulty;
//Exercise List
private RecyclerView exerciseRecyclerView;
private RecyclerView.Adapter exerciseAdapter;
private RecyclerView.LayoutManager exerciselayoutManager;
//Database
DatabaseReference databaseReferenceChallenge;
DatabaseReference databaseReferenceAthlete;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Initial setup of activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_challenge_view);
ChallengeView.context = getApplicationContext();
//variable list
currChallenges = new HashMap<>();
subAthletes = new ArrayList<>();
exerciseList = new ArrayList<>();
teamMem = new ArrayList<>();
//system references
intent = getIntent();
cName = intent.getStringExtra("name");
//cCESnapshot = intent.getStringExtra("snapshot");
//System.out.println(cCESnapshot);
//Authentication references
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
final String uid = user.getUid();
//XML references
name = findViewById(R.id.ChallengeName);
startDateTV = findViewById(R.id.DurationTextStart);
endDateTV = findViewById(R.id.DurationTextEnd);
description = findViewById(R.id.DescriptionText);
difficulty = findViewById(R.id.difficultyBar);
bSubscribe = findViewById(R.id.BSignUp);
bDropout = findViewById(R.id.CV_DropOut);
//Exercise List
exerciseRecyclerView = findViewById(R.id.ExerciseView);
exerciseRecyclerView.setHasFixedSize(true);
exerciselayoutManager = new LinearLayoutManager(this);
exerciseRecyclerView.setLayoutManager(exerciselayoutManager);
exerciseAdapter = new exerciseAdapterClass(exerciseList);
exerciseRecyclerView.setAdapter(exerciseAdapter);
exerciseAdapter.notifyDataSetChanged();
//database references
databaseReferenceChallenge = FirebaseDatabase.getInstance().getReference("Challenges");
databaseReferenceAthlete = FirebaseDatabase.getInstance().getReference("Athlete Users");
//Initial population of views and variables
databaseReferenceChallenge.addValueEventListener(new ValueEventListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot da = dataSnapshot.child(cName);
String dateStart = da.child("StartDate").child("day").getValue() + "/" + da.child("StartDate").child("month").getValue()+ "/" + da.child("StartDate").child("year").getValue();
String dateEnd = da.child("EndDate").child("day").getValue() + "/" + da.child("EndDate").child("month").getValue()+ "/" + da.child("EndDate").child("year").getValue();
long diff = (long)da.child("difficulty").getValue();
int tDifficulty = (int)diff;
name.setText((String)da.child("name").getValue());
startDateTV.setText(dateStart);
endDateTV.setText(dateEnd);
description.setText((String)da.child("description").getValue());
difficulty.setMin(1);
difficulty.setMax(5);
difficulty.setProgress(tDifficulty);
for(DataSnapshot ex : da.child("exercises").getChildren()){
exerciseList.add((String)ex.getValue());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//***************************************************************************************************************************************\\
//This should be grabbing all the challenges that the athlete is currently subscribed to.
databaseReferenceAthlete.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot dataSnapshot1 = dataSnapshot.child(uid).child("currChallenges");
HashMap<String, String> currChallengesT = (HashMap<String, String>) dataSnapshot1.getValue();
currChallenges.clear();
if(currChallengesT != null) {
currChallenges.putAll(currChallengesT);
if(currChallenges.containsKey(cName)) {
bSubscribe.setVisibility(View.GONE);
bDropout.setVisibility(View.VISIBLE);
}
else{
bSubscribe.setVisibility(View.VISIBLE);
bDropout.setVisibility(View.GONE);
}
}
else{
bSubscribe.setVisibility(View.VISIBLE);
bDropout.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
//***************************************************************************************************************************************\\
//***************************************************************************************************************************************\\
//This should be grabbing all the athletes subscribed to the challenge.
databaseReferenceChallenge.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot dataSnapshot1 = dataSnapshot.child(cName).child("subscribedAthletes");
ArrayList<String> subAthletesT = (ArrayList<String>) dataSnapshot1.getValue();
if(subAthletesT != null) {
subAthletes.addAll(subAthletesT);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
//***************************************************************************************************************************************\\
databaseReferenceAthlete.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot dataSnapshot1 = dataSnapshot.child(uid).child("currChallenges").child(cName).child("team");
team = (String) dataSnapshot1.getValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart(){
super.onStart();
//This is where I try to call the Recycler View.
System.out.println(exerciseList.size());
for(int i = 0; i < exerciseAdapter.getItemCount(); i ++){
System.out.println("Inside for loop: " + i);
CardView thing = (CardView) exerciselayoutManager.getChildAt(i);
exerciseAdapterClass.exerciseViewHolder holder = (exerciseAdapterClass.exerciseViewHolder) exerciseRecyclerView.getChildViewHolder(thing);
System.out.println("\n\n==============================================================\n" + holder.amount.getText().toString() +
"\n==============================================================");
}
}
public static Context getAppContext() {
return ChallengeView.context;
}
/*
Calls for the transfer to the challenge signup activity
*/
public void Subscribe(View view){
Intent intent = new Intent (this, ChallengeSignUp.class);
intent.putExtra("name", cName);
startActivity(intent);
}
}
The Adapter Class:
package com.cmsc355.forfit.util;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.cmsc355.forfit.ChallengeView;
import com.cmsc355.forfit.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.ArrayList;
public class exerciseAdapterClass extends RecyclerView.Adapter<exerciseAdapterClass.exerciseViewHolder>{
ArrayList<String> exerciseList;
public static class exerciseViewHolder extends RecyclerView.ViewHolder {
public CardView cardView;
public TextView exerciseName;
public TextView amount;
public EditText inputAmount;
public Button bEnter;
DatabaseReference databaseReferenceChallenge;
DatabaseReference databaseReferenceAthlete;
int currDone;
public exerciseViewHolder(View itemView) {
super(itemView);
//Variables
currDone = 0;
//Authentication
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
final String uid = user.getUid();
//Database Reference
databaseReferenceChallenge = FirebaseDatabase.getInstance().getReference("Challenges");
databaseReferenceAthlete = FirebaseDatabase.getInstance().getReference("Athlete Users");
//XML
cardView = itemView.findViewById(R.id.cv_cardView);
exerciseName = itemView.findViewById(R.id.cv_exerciseName);
amount = itemView.findViewById(R.id.cv_amount);
inputAmount = itemView.findViewById(R.id.cv_input);
bEnter = itemView.findViewById(R.id.cv_button);
bEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(inputAmount.getText().toString().trim().length() == 0)){
int input = Integer.parseInt(inputAmount.getText().toString());
final String cName = ChallengeView.cName;
databaseReferenceAthlete.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try{
DataSnapshot snapshot = dataSnapshot.child(uid).child("currChallenges").child(cName).child(exerciseName.getText().toString());
currDone = (int)((long)snapshot.getValue());
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
currDone += input;
databaseReferenceAthlete.child(uid).child("currChallenges").child(cName).child(exerciseName.getText().toString()).setValue(currDone);
}
else{
Toast.makeText(ChallengeView.getAppContext(), "Nothing in there.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
public exerciseAdapterClass(ArrayList<String> inputList){
exerciseList = inputList;
}
#Override
public int getItemCount() {
return exerciseList.size();
}
#Override
public exerciseViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cv_card, viewGroup, false);
exerciseViewHolder pvh = new exerciseViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(final exerciseViewHolder holder, final int i) {
holder.setIsRecyclable(false);
String s1 = exerciseList.get(i);
//Possible error if the name contains "Amount"
final String name = s1.substring(0, s1.indexOf("Amount")-1); //first section of the string to give the name.
String s2 = s1.substring(s1.indexOf(": ")); //cuts of the front of the string and puts to a new substring.
String a = s2.substring(s2.indexOf(' '), s2.indexOf("\n")); //cuts the part after the : but before the \n
a = a.trim(); //trims the inevitable white space
final String units = a.substring(a.indexOf(' ')); //gets the units off the string
a = a.substring(0, a.indexOf(' ')); //cuts off the units
final int amount = Integer.parseInt(a); //parse to use as a number
String s3 = s2.substring(s2.indexOf("\n")); //cuts to the date and new string
s3 = s3.substring(8); //removes the date tag
String y = s3.substring(0, s3.indexOf('/')); //cuts year into new string
final int year = Integer.parseInt(y); //parse year to use as a number
s3 = s3.substring(s3.indexOf('/') + 1); //cuts year off
String d = s3.substring(0, s3.indexOf('/')); //cuts day into new string
final int day = Integer.parseInt(d); //parse day
s3 = s3.substring(s3.indexOf('/') + 1); //cuts day off
final int month = Integer.parseInt(s3); //parses month
/*DatabaseReference databaseReferenceAthlete = FirebaseDatabase.getInstance().getReference("Athlete Users");
databaseReferenceAthlete.addValueEventListener(new ValueEventListener() {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
final String uid = user.getUid();
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot snapshot = dataSnapshot.child(uid).child("currChallenges").child(ChallengeView.cName).child(name);
try{
int val = ((int)((long)snapshot.getValue()));
int printVal = Math.max(0, amount - val);
}
catch(Exception e){}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});*/
holder.amount.setText("0" + units);
holder.exerciseName.setText(name);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
As of right now, when I try to call for anything referencing the RecyclerView, it returns either 0 or null. My thought is that the code to instate the RecyclerView has not been run yet.
What you have done is:
In the adapter class, you are trying to retrieve the firebase data.
By the time it returns data the constructor is being called, and where the size of the list exerciseList is zero. And another thing to notice is you have mentioned firebase call (Which operates in the background) in ViewHolder class.
The best way to do this is:
First, you get the data from firebase outside the adapter and then set adapter. Like
In MainActivity do the background job (to retrieve data from Firebase ) and then after successfully retrieve, set adapter like
exerciseAdapterClass adapter = new Adapter (exerciseList);
recyclerView.setAdapter(adapter);
If you want to notify the recycler view if there are some changes occurred in firebase data you can do that as below:
Get the changed list (exerciseList) Or changed item(String) from the firebase using
databaseReferenceAthlete.addValueEventListener
Or
databaseReferenceAthlete.addChildEventListener
and then
adapter.update(exerciseList);
adapter.notifyDatasetChanged;
Or
adapter.update(newString);
adapter.notifyItemChanged(position)
*Note: you have to set up the update method in adapter class
Example:
Adapter to update list
public class NoteListAdapter extends RecyclerView.Adapter<NoteListAdapter.NoteViewHolder> {
private List<String> list;
public NoteListAdapter(List<String> list) {
this.list = list;
}
public void update(List<String> list){
this.list = list;
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View noteView = inflater.inflate(R.layout.item_note, parent, false);
return new NoteViewHolder(noteView);
}
#Override
public void onBindViewHolder(#NonNull NoteViewHolder holder, int i) {
String itemString = list.get(i);
holder.textView.setText(itemString);
}
#Override
public int getItemCount() {
return list.size();
}
public class NoteViewHolder extends RecyclerView.ViewHolder{
private TextView textView;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_rv);
}
}
}
in mainActivity:
public class NotesActivity extends AppCompatActivity implements NotesContract.View{
private TextView textView;
private Button add;
private NotesContract.UserActionsListener mActionsListener;
private NoteRepository repository;
private RecyclerView recyclerView;
private NoteListAdapter adapter;
List<String> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
add = findViewById(R.id.button);
repository = new NoteRepository();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new NoteListAdapter(list);
recyclerView.setAdapter(adapter);
mActionsListener = new NotePresenter(repository,this);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mActionsListener.loadNotes("hello");
}
});
}
#Override
public void showAddNote(List<String> data) {
String line = "";
for(String s:data){
line = line.concat(s);
}
textView.setText(line);
}
#Override
public void showRecViewNote(List<String> data) {
adapter.update(data);
adapter.notifyDataSetChanged();
}
}
Look at, how the recycler view got set
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new NoteListAdapter(list);
recyclerView.setAdapter(adapter);
and how it is notified
public void showRecViewNote(List<String> data) {
adapter.update(data);
adapter.notifyDataSetChanged();
}

Recycler view doesn't show first item until refresh

I've got an app which saves a number and the date it was recorded in a recycler View, however when the array is empty and then I try to save my number, the RecyclerView does not show the item. The item did save, but it isn't displayed in the view. I know it save because when I go back to the view the item is there. I have looked ages for answer online and have seen nobody with the same issue. Thank you in advance for your help!
Activity 2:
package com.pinet.count;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Activity2 extends AppCompatActivity {
private ExampleAdapter mAdapter;
private static final Date currentTime = Calendar.getInstance().getTime();
private ArrayList<ExampleItem> mexampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent intent = getIntent();
String dateString= DateFormat.format("dd/MM/yyyy",currentTime).toString();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
buildRecyclerView();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
mexampleList.add(0, new ExampleItem(String.valueOf(count), dateString));
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(0,mexampleList.size());
}
saveList();
}
private void buildRecyclerView(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter= new ExampleAdapter(mexampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
private void removeItem(int position){
mexampleList.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, mexampleList.size());
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",0);
sharedPreferences.edit().remove("count list").apply();
}package com.pinet.count;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Activity2 extends AppCompatActivity {
private ExampleAdapter mAdapter;
private static final Date currentTime = Calendar.getInstance().getTime();
private ArrayList<ExampleItem> mexampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent intent = getIntent();
String dateString= DateFormat.format("dd/MM/yyyy",currentTime).toString();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
buildRecyclerView();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
mexampleList.add(0, new ExampleItem(String.valueOf(count), dateString));
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(0,mexampleList.size());
}
saveList();
}
private void buildRecyclerView(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter= new ExampleAdapter(mexampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
private void removeItem(int position){
mexampleList.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, mexampleList.size());
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",0);
sharedPreferences.edit().remove("count list").apply();
}
private void saveList(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mexampleList);
editor.putString("count list", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("count list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mexampleList = gson.fromJson(json, type);
}
}
`
private void saveList(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mexampleList);
editor.putString("count list", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("count list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mexampleList = gson.fromJson(json, type);
}
}
Main Activity:
package com.pinet.count;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int count = 0;
public static final String EXTRA_NUMBER ="com.pinet.count.EXTRA_NUMBER";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView= findViewById(R.id.textView);
Button buttonPos = findViewById(R.id.button);
Button buttonNeg = findViewById(R.id.button2);
Button buttonReset = findViewById(R.id.button3);
Button buttonSave = findViewById(R.id.button4);
Button butonHistory = findViewById(R.id.button5);
buttonPos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count +=1;
textView.setText(String.valueOf(count));
}
});
buttonNeg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count-=1;
textView.setText(String.valueOf(count));
}
});
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count = 0;
textView.setText(String.valueOf(count));
}
});
butonHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenActivity2();
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
}
private void openActivity2(){
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(EXTRA_NUMBER, count);
startActivity(intent);
}
private void OpenActivity2(){
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
}
ExampleAdapter:
package com.pinet.count;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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 java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private final ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
final TextView mTextView1;
final TextView mTextView2;
final ImageView mDeleteImage;
ExampleViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1=itemView.findViewById(R.id.textView);
mTextView2=itemView.findViewById(R.id.textView2);
mDeleteImage=itemView.findViewById(R.id.image_delete);
mDeleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener !=null){
int position = getAdapterPosition();
if (position!=RecyclerView.NO_POSITION){
listener.onDeleteClick(position);
}
}
}
});
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList){
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v, mListener);
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mTextView1.setText(currentItem.getmText1());
holder.mTextView2.setText(currentItem.getmText2());
}
#Override
public int getItemCount() {
if (mExampleList !=null) {
return mExampleList.size();
}
else {
return 0;
}
}
}
ExampleItem :
package com.pinet.count;
class ExampleItem {
private final String mText1;
private final String mText2;
public ExampleItem(String text1, String text2){
mText1= text1;
mText2= text2;
}
public String getmText1(){
return mText1;
}
public String getmText2(){
return mText2;
}
}
If you could also help me figure out animating the recycler view that would be appreciated !
PiNet
Change your onCreate() method inside the "Activity2" Activity to look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
String dateString = DateFormat.format("dd/MM/yyyy",currentTime).toString();
Intent intent = getIntent();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
String value = String.valueOf(count);
ExampleItem exampleItem = new ExampleItem(value, dateString);
mexampleList.add(0, exampleItem);
}
buildRecyclerView();
saveList();
}
I've changed the order of adding the new data to the ArrayList. This way the "new item" will be added to the list before you set the adapter. I have also extrapolated some if the code into distinct code lines. I recommend this because it will be easier to debug.
A few additional comments:
The method removeItem(int position) appears to remove the entire list from your SharedPreferences instead of what I assume you only want to remove the one item.
Also in your "MainActivity" you have two methods:
openActivity2()
and
OpenActivity2()
Firstly, Java naming convention dictates that method names begin with lower case. Secondly, this is very poor programing style to give methods indistinguishable method names.

Error retrieving data from firebase using recycler view: E/RecyclerView: No adapter attached; skipping layout [duplicate]

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
I am on a project now and am trying to obtain data from my firebase using recycler view and viewholder, but using my helper class, immediately when the app launches and I try retrieving data through my helper class it crashes, and when i look through my logcat, I get this error
E/RecyclerView: No adapter attached; skipping layout....
I have searched for a lot o answers and i see some but they are not related to my code...
Here is my mainactivity code
package com.example.android.journalapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
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 com.example.android.journalapp.users.LogInActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT,
Locale.getDefault());
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabase;
String mUserId;
private RecyclerView mRecyclerView;
private FirebaseHelper helper;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mRecyclerView = (RecyclerView) findViewById(R.id.journal_recycler);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
if (mFirebaseUser == null) {
// Not logged in, launch the Log In activity
loadLogInView();
} else {
mDatabase = FirebaseDatabase.getInstance().getReference();
mUserId = mFirebaseUser.getUid();
helper = new FirebaseHelper(context, mDatabase, mRecyclerView,
mUserId);
helper.refreshData();
}
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addJournalIntent = new Intent(MainActivity.this,
AddJournalActivity.class);
addJournalIntent.putExtra("USER_ID", mUserId);
startActivity(addJournalIntent);
}
});
}
private void loadLogInView() {
Intent intent = new Intent(this, LogInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
mFirebaseAuth.signOut();
loadLogInView();
}
return super.onOptionsItemSelected(item);
}
}
here is my firebase helper class
package com.example.android.journalapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.example.android.journalapp.model.Journal;
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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class FirebaseHelper {
private String mUserId;
private Context context;
private DatabaseReference mDb;
RecyclerView mRecyclerView;
ArrayList<Journal> journals = new ArrayList<>();
public JournalAdapter mJournalAdapter;
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
public FirebaseHelper(Context context, DatabaseReference mDb, RecyclerView mRecyclerView, String mUserId) {
this.context = context;
this.mDb = mDb;
this.mRecyclerView = mRecyclerView;
this.mUserId = mUserId;
}
public void saveData(String journal, String date) {
Journal journalEntry = new Journal(journal, date);
mDb.child("users").child(mUserId).child("journals").push().setValue(journalEntry) ;
// .child("journal")
}
public void recieveData(DataSnapshot ds) {
journals.clear();
for (DataSnapshot dataSnapshot : ds.getChildren()) {
Journal journal = dataSnapshot.getValue(Journal.class);
journals.add(journal);
}
mJournalAdapter = new JournalAdapter(context, journals);
mRecyclerView.setAdapter(mJournalAdapter);
// if (journals.size() > 0) {
//
// mJournalAdapter = new JournalAdapter(context, journals);
// mRecyclerView.setAdapter(mJournalAdapter);
// } else {
// Toast.makeText(context, "No data", Toast.LENGTH_SHORT).show();
// }
}
public void refreshData() {
mDb.child("users").child(mUserId).child("journals").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
recieveData(dataSnapshot);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
recieveData(dataSnapshot);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
here is my model class
package com.example.android.journalapp.model;
import java.util.Date;
public class Journal {
private String journalContent;
private String date;
public Journal(String journalContent, String date) {
this.journalContent = journalContent;
this.date = date;
}
public String getJournalContent() {
return journalContent;
}
public void setJournalContent(String journalContent) {
this.journalContent = journalContent;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
///
here is my adapter class
package com.example.android.journalapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.journalapp.model.Journal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
public class JournalAdapter extends RecyclerView.Adapter<JournalHolder> {
Context context;
private ArrayList<Journal> journals;
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
public JournalAdapter(Context context, ArrayList<Journal> journals) {
this.context = context;
this.journals = journals;
}
#NonNull
#Override
public JournalHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.journal_layout, parent, false);
JournalHolder holder = new JournalHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull JournalHolder holder, int position) {
holder.mJournalTextView.setText(journals.get(position).getJournalContent());
String date = journals.get(position).getDate();
holder.mDateTextView.setText(date);
}
#Override
public int getItemCount() {
if (journals == null) {
return 0;
}
return journals.size();
}
}
//
here is my viewholder class
package com.example.android.journalapp;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class JournalHolder extends RecyclerView.ViewHolder {
TextView mJournalTextView;
TextView mDateTextView;
public JournalHolder(View itemView) {
super(itemView);
mJournalTextView = itemView.findViewById(R.id.journal_text_view);
mDateTextView = itemView.findViewById(R.id.journal_date_text_view);
}
}
i am able to push into the data base, but to retrieve data gives me the error E/RecyclerView: No adapter attached; skipping layout
Try this code..
display_data.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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvData"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/dlTvEmpty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Found"
android:textSize="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
DisplayActivity.java..
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List<User> mUserList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
DisplayAdapter.java..
public class DisplayAllData extends RecyclerView.Adapter<DisplayAllData.ItemViewHolder> {
private List<User> mUserLsit = new ArrayList<>();
private Context mContext;
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext, List<User> mUserLsit) {
this.mContext = mContext;
this.mUserLsit = mUserLsit;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user = mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
#Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName, mTvEmail, mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail = itemView.findViewById(R.id.rlTvEmail);
mTvName = itemView.findViewById(R.id.rlTvName);
mTvPwd = itemView.findViewById(R.id.rlTvPwd);
}
}
}
row_layout.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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/rlTvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20dp" />
<TextView
android:id="#+id/rlTvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvName" />
<TextView
android:id="#+id/rlTvPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvEmail" />
</android.support.constraint.ConstraintLayout>
and i hope you add internet permission into android manifest file..
<uses-permission android:name="android.permission.INTERNET"/>
more information refer this link
https://www.simplifiedcoding.net/firebase-realtime-database-crud/

com.google.firebase.database.databaseexception:firebase database error: Permission denied

im retrieving data in my database from firebase. and shoscription herew up this error can anyone help me? this is my mainactivity.java:
package com.example.infamouslegend.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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;
import java.util.List;
public class MainActivity extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef ;
List<FireModel> list;
RecyclerView recycle;
Button view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (Button) findViewById(R.id.view);
recycle = (RecyclerView) findViewById(R.id.recycle);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Complaints");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
list = new ArrayList<FireModel>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
FireModel value = dataSnapshot.getValue(FireModel.class);
FireModel fire = new FireModel();
String Description = value.getDescription();
String Date = value.getDate();
String MediaURL = value.getMediaURL();
fire.setDescription(Description);
fire.setDate(Date);
fire.setMediaURL(MediaURL);
list.add(fire);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
Toast.makeText(MainActivity.this, "Failed to read value !" + error.toException(), Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list,MainActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MainActivity.this,2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recycle.setLayoutManager(recyce);
recycle.setItemAnimator( new DefaultItemAnimator());
recycle.setAdapter(recyclerAdapter);
}
});
}
}
and this is my firemodel.java:
package com.example.infamouslegend.myapplication;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class FireModel {
public String Description;
public String Date;
public String MediaURL;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
this.Description = description;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
this.Date = date;
}
public String getMediaURL() {
return MediaURL;
}
public void setMediaURL(String MediaURL) {
this.MediaURL = MediaURL;
}
}
and my recycleradapter.java:
package com.example.infamouslegend.myapplication;
import android.content.Context;
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 com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyHoder>{
List<FireModel> list;
Context context;
public RecyclerAdapter(List<FireModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public MyHoder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card,parent,false);
MyHoder myHoder = new MyHoder(view);
return myHoder;
}
#Override
public void onBindViewHolder(MyHoder holder, int position) {
FireModel mylist = list.get(position);
holder.Description.setText(mylist.getDescription());
holder.Date.setText(mylist.getDate());
//holder.MediaURL.setText(mylist.getMediaURL());
//Picasso.with(context).load(MediaURL.get(position).getMediaURL()).resize(120, 60).into(MyHoder.MediaURL);
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(list.size()==0){
arr = 0;
}
else{
arr=list.size();
}
}catch (Exception e){
}
return arr;
}
class MyHoder extends RecyclerView.ViewHolder{
TextView Description,Date;
//ImageView MediaURL;
public MyHoder(View itemView) {
super(itemView);
Description = (TextView) itemView.findViewById(R.id.vname);
Date= (TextView) itemView.findViewById(R.id.vemail);
//MediaURL= (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
Can anyone help me this? Im trying to retrieve data from firebase database to recyclerview with cardview. Thanks in advance
this is my firebase realtime database rule:
{
"rules": {
".read": true,
".write":true
}
}
If you have configured the app to connect with firebase correctly i would redownload the google-service.json and replace with an existing one.
check this solution

Categories

Resources