-6

I'm having some particular problems with my android project. In particular I have two collections, Users and Courses: the first one comprehend the list of users (teachers) which have two Strings (email and idCourse) in the second one there is the list of courses, each one relating to a user (idCourse is the same of the user), inside each course there is a list of lesson which i need to access with a specific user. I saved in an object admin its data to access to a specific Lessons collection, because in the path there is the admin id.

Courses path to Lessons Users collection

I tried to, but when i save the id in the addCompleteListener method the data get lost outside, indeed in the addSnapshotListener the value of admin.getCourseId() is null so my recyclerView results empty. If I try to copy the second method in the first one, as soon as I save the idCourse in Admin, the method works, but if I click on the lesson when i use the app, the app crashes. I know this may be a specifical issue of mine, but i would like to hear something from you about it. I'm posting my android project too. Android Project on Google Drive Thanks in advance for your help!

CLASS LezioniDocenteActivity:

public class LezioniDocenteActivity extends AppCompatActivity {

    private static final String TAG = "FireLog";
    private RecyclerView mMainList;
    private FirebaseFirestore mFirestore;
    private FirebaseAuth firebaseAuth;
    private LessonsListAdapter lessonsListAdapter;
    private List<Lesson> lessonList;
    private String course_id;

    //admin per memorizzare le info
    private final User admin = new User();

    @Override
    public void onBackPressed(){
        startActivity(new Intent(LezioniDocenteActivity.this, DocenteActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lezioni_docente);

        lessonList = new ArrayList<>();
        lessonsListAdapter = new LessonsListAdapter(lessonList, getApplicationContext());

        mMainList = (RecyclerView)findViewById(R.id.lesson_list);
        mMainList.setHasFixedSize(true);
        mMainList.setLayoutManager(new LinearLayoutManager(this));
        mMainList.setAdapter(lessonsListAdapter);
        firebaseAuth = FirebaseAuth.getInstance();

        //utente in uso corrente
        final FirebaseUser user = firebaseAuth.getCurrentUser();
        admin.setEmail(user.getEmail());
        mFirestore = FirebaseFirestore.getInstance();

        mFirestore.collection("Users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                boolean find = false;
                for (DocumentSnapshot doc : task.getResult()) {
                    String email = doc.getString("email");
                    if (email.equals(admin.getEmail())) {
                        //getting admin's courseID
                        admin.setCourseId(doc.getString("idCorso"));
                        break;
                    }
                }
            }
        });

        mFirestore.collection("Courses /" + admin.getCourseId() + "/Lessons").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot documentSnapshots, @Nullable FirebaseFirestoreException e) {
                if(e!=null){
                    Log.d(TAG, "Error :" + e.getMessage());
                    return;
                }
                for(DocumentChange doc : documentSnapshots.getDocumentChanges()){
                    if(doc.getType() == DocumentChange.Type.ADDED){
                        Lesson lesson = doc.getDocument().toObject(Lesson.class);
                        lessonList.add(lesson);
                        lessonsListAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

    }
}

CLASS LessonListAdapter:

public class LessonsListAdapter extends RecyclerView.Adapter<LessonsListAdapter.ViewHolder> {

    public List<Lesson> lessonList;
    public Context context;
    final User admin = new User();

    public LessonsListAdapter(List<Lesson> lessonList, Context context){
        this.lessonList = lessonList;
        this.context = this.context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_lessons, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

        final FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
        final FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
        final FirebaseUser user = firebaseAuth.getCurrentUser();
        admin.setEmail(user.getEmail());

        holder.dayText.setText(lessonList.get(position).getLessonDate());
        holder.argText.setText(lessonList.get(position).getArgument());
        final String lessID = lessonList.get(position).lessonID;
        final int i = position;

        firebaseFirestore.collection("Users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        boolean find = false;
                        for(DocumentSnapshot doc : task.getResult()){
                            String email = doc.getString("email");

                            if(email.equals(admin.getEmail())) {
                                find = true;
                                //getting admin's courseID
                                admin.setCourseId(doc.getString("courseId"));
                                break;
                            }
                        }
            if (find){
                holder.delete.setVisibility(View.VISIBLE);
                holder.delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(context, "OnClick funziona", Toast.LENGTH_SHORT).show();
                    }
                });
            } else holder.delete.setVisibility(View.GONE);
        }
    });
    }

    @Override
    public int getItemCount() {
        return lessonList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        View mView;

        public TextView dayText;
        public TextView argText;
        public ImageView delete;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
            dayText = (TextView) mView.findViewById(R.id.day_text);
            argText = (TextView) mView.findViewById(R.id.arg_text);
            delete = (ImageView) mView.findViewById(R.id.ic_delete);
        }
    }
}
4
  • 1
    welcome to stack overflow :D In future, please try to make the title of your question more specific, Android project issue doesn't really helping anyone to identify what your problem is, remember : future users or existing users might also be having your issue Commented Oct 4, 2019 at 12:00
  • Also when you have issues with app crashing, post your crash logs too Commented Oct 4, 2019 at 12:03
  • have a look at this here : stackoverflow.com/help/how-to-ask as well as stackoverflow.com/tour for some help getting started here Commented Oct 4, 2019 at 12:03
  • 1
    Please write a title that actually describes your problem. Commented Oct 4, 2019 at 12:18

1 Answer 1

1

The following code will work for you. But you have to make changes according to it. I am not using Android Studio. It's notepad code.

mfirebaseFirestore.collection("Users").orderBy("email")
            .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            for (QueryDocumentSnapshot querySnapshot : task.getResult()){
                if (querySnapshot.get("email").equals(user.getEmail())){
                    mfirebaseFirestore.collection("Courses/"+ querySnapshot.get("idCorso")+"/Lessons")
                            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                                @Override
                                public void onEvent(@Nullable QuerySnapshot documentSnapshots, @Nullable FirebaseFirestoreException e) {
                                    for(DocumentChange doc : documentSnapshots.getDocumentChanges()){
                                        if(doc.getType() == DocumentChange.Type.ADDED){
                                            Lesson lesson = doc.getDocument().toObject(Lesson.class);
                                            lessonList.add(lesson);
                                        }
                                        lessonsListAdapter = new LessonsListAdapter(lessonList, getApplicationContext());
                                        lessonsListAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                }
            }
        }
    });

Explanation about code :

From above code as everyone explained Firebase calls are asynchronous (e.g. answer). So the data your trying to retrieve is receiving null as you said.

The above code will check in your database about email then retrieve the details of that user. Which means you will get the course id from it. Then directly call the function to retrieve lessons list by passing the course id.

Sign up to request clarification or add additional context in comments.

9 Comments

Should that admin.setCourseId(doc.getString("idCorso")); be inside a for each cycle right?
the above code will directly provide single user to u
I mean, what is that doc related to? Because it's not declared
@GabrieleLoprieno sorry it was my bad i wasn't using ide now can you try ?
What do you mean by that "abc" string? I tried to put admin.getEmail() and in both cases it doesn't work, it shows me nothing.. Anyway i tried also to use getString instead of get but there are the same results
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.