Получение данных по ключу - Firebase - PullRequest
0 голосов
/ 13 марта 2020

Итак, у меня есть база данных Firebase: enter image description here

У меня есть список просмотра переработчика с именами заданий. Когда человек нажимает на элемент, он должен развернуться, чтобы показать больше информации о нем. Я полагаю, что для этого мне нужно получить данные по основным дочерним ключам, таким как Job1, Job2 и c. Как бы я это сделал? Я пытался посмотреть на похожие вопросы, но я не могу не чувствовать себя немного потерянным, так как я только начинающий. Я был бы признателен, если бы кто-то ответил на это простыми объяснениями, которые помогут мне учиться.

Это мой основной Домашний класс :

package com.example.oddsynew;

import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.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 Home extends AppCompatActivity {

    DatabaseReference myRef;
    RecyclerView newJobList;
    ArrayList<Job> list;
    HomeAdapter adapter;

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

        newJobList = (RecyclerView) findViewById(R.id.newJobs);
        newJobList.setLayoutManager(new LinearLayoutManager(this));
        list = new ArrayList<Job>();

        adapter = new HomeAdapter(Home.this, list);
        newJobList.setAdapter(adapter);



        myRef = FirebaseDatabase.getInstance().getReference().child("Jobs");
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    String jobkey = ds.getKey();
                    Job j = ds.getValue(Job.class);
                    list.add(j);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(Home.this, "Error", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

За ним следуют мои адаптер класса :

package com.example.oddsynew;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

    Context context;
    ArrayList<Job> jobs;

    public HomeAdapter(Context c, ArrayList<Job> j){
        context = c;
        jobs = j;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.job_row, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
        holder.recruiterName.setText(jobs.get(position).getRecruiter_name());
        holder.jobName.setText(jobs.get(position).getJob_name());
        holder.jobLocation.setText(jobs.get(position).getLocation());
        holder.jobCharge.setText(jobs.get(position).getJob_charge());
        Picasso.get().load(jobs.get(position).getProf_pic()).into(holder.profPic);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String recruiter_id; //I'm not sure what to do here.
            }
        });
    }

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

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView recruiterName, jobName, jobLocation, jobCharge;
        ImageView profPic;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            recruiterName = itemView.findViewById(R.id.recruiterName);
            jobName = itemView.findViewById(R.id.jobName);
            jobLocation = itemView.findViewById(R.id.jobLocation);
            jobCharge = itemView.findViewById(R.id.jobCharge);
            profPic = itemView.findViewById(R.id.prof_pic);

        }
    }

}

А вот и моя модель :

package com.example.oddsynew;

public class Job {
    private String job_name;
    private String recruiter_name;
    private String location;
    private String job_charge;
    private String prof_pic;

    public Job() {
    }

    public Job(String job_name, String recruiter_name, String location, String job_charge, String prof_pic) {
        this.job_name = job_name;
        this.recruiter_name = recruiter_name;
        this.location = location;
        this.job_charge = job_charge;
        this.prof_pic = prof_pic;
    }

    public Job(String prof_pic) {
        this.prof_pic = prof_pic;
    }

    public String getJob_name() {
        return job_name;
    }

    public void setJob_name(String job_name) {
        this.job_name = job_name;
    }

    public String getRecruiter_name() {
        return recruiter_name;
    }

    public void setRecruiter_name(String recruiter_name) {
        this.recruiter_name = recruiter_name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getJob_charge() {
        return job_charge;
    }

    public void setJob_charge(String job_charge) {
        this.job_charge = job_charge;
    }

    public String getProf_pic() {
        return prof_pic;
    }

    public void setProf_pic(String prof_pic) {
        this.prof_pic = prof_pic;
    }
}

My Recycler View UI

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="14dp"
    android:layout_marginRight="14dp"
    android:elevation="90dp"
    android:orientation="vertical"
    app:cardCornerRadius="4dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#fff"
        android:orientation="vertical">


        <ImageView
            android:id="@+id/prof_pic"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginStart="12dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:scaleType="centerCrop"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.3" />

        <TextView
            android:id="@+id/recruiterName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="15dp"
            android:layout_marginEnd="16dp"
            android:fontFamily="@font/roboto"
            android:textColor="#000"
            android:textSize="14sp"
            android:textStyle="normal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toEndOf="@+id/prof_pic"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/jobName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="16dp"
            android:fontFamily="@font/roboto_bold"
            android:textColor="#000"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/prof_pic"
            app:layout_constraintTop_toBottomOf="@+id/recruiterName" />

        <TextView
            android:id="@+id/jobLocation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="24dp"
            android:fontFamily="@font/roboto_light"
            android:textColor="#000"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@+id/prof_pic"
            app:layout_constraintTop_toBottomOf="@+id/jobName"
            app:layout_constraintVertical_bias="0.0" />

        <TextView
            android:id="@+id/jobCharge"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="16dp"
            android:fontFamily="@font/roboto_light"
            android:textColor="#000"
            android:textSize="12sp"
            app:layout_constraintBaseline_toBaselineOf="@+id/jobLocation"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/jobLocation" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

РЕДАКТИРОВАТЬ: Это мой список списков переработчиков. Я получил данные из базы данных и отобразил их на элементах. Первый элемент списка - это информация из Job1. Когда я нажимаю на первый элемент, он должен go перейти на другую страницу, назовем его «jobInfo» , чтобы отобразить дополнительную информацию об этой конкретной работе. То, с чем я бьюсь, это как сделать так, чтобы информация, только о job1, отображалась при нажатии на первый элемент. Извините, если я не был ясен раньше.

enter image description here

Ответы [ 2 ]

0 голосов
/ 13 марта 2020

Я смог заставить его работать с этим кодом в моем классе информации о работе:

package com.example.oddsynew;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.squareup.picasso.Picasso;

public class JobInfo extends AppCompatActivity {

    TextView jobName, jobCharge, jobLocation;
    ImageView profPic;
    String jobname, jobloc, jobcharge, profpic;


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

        jobName = (TextView) findViewById(R.id.jobName_info);
        jobCharge = (TextView) findViewById(R.id.jobCharge_info);
        jobLocation = (TextView) findViewById(R.id.jobLocation_info);
        profPic = (ImageView) findViewById(R.id.prof_pic_info);

        jobname = getIntent().getStringExtra("jobName");
        jobloc = getIntent().getStringExtra("jobLocation");
        jobcharge = getIntent().getStringExtra("jobCharge");
        profpic = getIntent().getStringExtra("profPic");

        jobName.setText(jobname);
        jobCharge.setText(jobcharge);
        jobLocation.setText(jobloc);

        Picasso.get().load(profpic).into(profPic);


    }
}

И добавить это в setOnClickListener в моем классе адаптера:

 holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, JobInfo.class);
                intent.putExtra("recruiterName",jobs.get(position).getRecruiter_name());
                intent.putExtra("jobName",jobs.get(position).getJob_name());
                intent.putExtra("jobCharge",jobs.get(position).getJob_charge());
                intent.putExtra("jobLocation",jobs.get(position).getLocation());
                intent.putExtra("profPic",jobs.get(position).getProf_pic());
                context.startActivity(intent);
            }
        });
    } 
0 голосов
/ 13 марта 2020

В домашнем задании:

     myRef = FirebaseDatabase.getInstance().getReference().child("Jobs");
     myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds: dataSnapshot.getChildren()){
                String jobkey = ds.getKey();
                Job j = ds.getValue(Job.class);
                list.add(j);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(Home.this, "Error", Toast.LENGTH_SHORT).show();
        }
    });

В классе модели заданий внедрить Сериализуемый

public class Job implements Serializable

В адаптере щелкните прослушиватель

holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, jobInfo.class);
            intent.putExtra("yourKey",jobs.get(position));
            startActivity(intent);
        }
    });

В задании JobInfo

Job job = (Job) getIntent().getSerializableExtra("yourKey");

в работе вы получите все значения

...