首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Firebase/Android -检查来自数据库的数据是否与同一数据库中的其他数据匹配

Firebase/Android -检查来自数据库的数据是否与同一数据库中的其他数据匹配
EN

Stack Overflow用户
提问于 2020-03-23 07:29:09
回答 1查看 93关注 0票数 0

我有一款为人们提供零工的应用程序。有一段,你可以看到他身边的工作机会。当用户单击此选项时,他所在位置上可用的作业将显示出来。我有一个包含两个节点(作业和用户)的防火墙数据库,其中添加了用户的位置和作业的位置。我如何在他的位置显示可用的工作?例如,用户住在迪拜,他希望看到迪拜的工作机会。我希望能够提取当前用户的位置,并检查它是否与作业的位置匹配。这是我试过的,但不起作用。

Home_NearYou.java:

代码语言:javascript
复制
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.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.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Home_NearYou extends AppCompatActivity {

    DatabaseReference myRef;
    FirebaseAuth mAuth;
    RecyclerView nearYouList;
    ArrayList<Job> list;
    HomeAdapter adapter;
    Query query;
    Users user;
    FirebaseUser u;
    String userID;

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

        try {
            mAuth = FirebaseAuth.getInstance();
            u = mAuth.getCurrentUser();
            userID = u.getUid();
            myRef = FirebaseDatabase.getInstance().getReference("Users").child(userID).child("state");

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

            adapter = new HomeAdapter(Home_NearYou.this, list);
            nearYouList.setAdapter(adapter);

            query = FirebaseDatabase.getInstance().getReference("Jobs")
                    .orderByChild("location")
                    .equalTo(myRef.toString());

            query.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot ds : dataSnapshot.getChildren()) {
                        Job j = ds.getValue(Job.class);
                        list.add(j);
                    }
                    adapter.notifyDataSetChanged();
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(Home_NearYou.this, "Error", Toast.LENGTH_SHORT).show();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

Job.java:

代码语言:javascript
复制
package com.example.oddsynew;

public class Job {
    String job_name, recruiter_name, location, job_charge, add_pref, start_date, end_date, start_time, end_time, tasks, job_desc, prof_pic, job_tasks;

    public Job() {
    }

    public Job(String job_name, String recruiter_name, String location, String job_charge, String add_pref, String start_date,
               String end_date, String start_time, String end_time, String tasks, String job_desc, String prof_pic, String job_tasks) {
        this.job_name = job_name;
        this.recruiter_name = recruiter_name;
        this.location = location;
        this.job_charge = job_charge;
        this.add_pref = add_pref;
        this.start_date = start_date;
        this.end_date = end_date;
        this.start_time = start_time;
        this.end_time = end_time;
        this.tasks = tasks;
        this.job_desc = job_desc;
        this.prof_pic = prof_pic;
        this.job_tasks = job_tasks;
    }

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

    public String getAdd_pref() {
        return add_pref;
    }

    public void setAdd_pref(String add_pref) {
        this.add_pref = add_pref;
    }

    public String getStart_time() {
        return start_time;
    }

    public void setStart_time(String start_time) {
        this.start_time = start_time;
    }

    public String getEnd_time() {
        return end_time;
    }

    public String getStart_date() {
        return start_date;
    }

    public void setStart_date(String start_date) {
        this.start_date = start_date;
    }

    public String getEnd_date() {
        return end_date;
    }

    public void setEnd_date(String end_date) {
        this.end_date = end_date;
    }

    public void setEnd_time(String end_time) {
        this.end_time = end_time;
    }

    public String getTasks() {
        return tasks;
    }

    public void setTasks(String tasks) {
        this.tasks = tasks;
    }

    public String getJob_desc() {
        return job_desc;
    }

    public void setJob_desc(String job_desc) {
        this.job_desc = job_desc;
    }

    public String getJob_tasks() {
        return job_tasks;
    }

    public void setJob_tasks(String job_tasks) {
        this.job_tasks = job_tasks;
    }
}

Users.java:

代码语言:javascript
复制
package com.example.oddsynew;

public class Users {
    private String fname;
    private String lname;
    private String email;
    private String pass;
    private String state;
    private String city;
    private String age;

    public Users() {
    }

    public String getFname() {
        return fname;
    }

    public String getLname() {
        return lname;
    }

    public String getEmail() {
        return email;
    }

    public String getPass() {
        return pass;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

作业数据库:

用户数据库:

更新:这是我如何将数据插入Firebase的一个例子。

SignUp2.java:

代码语言:javascript
复制
package com.example.oddsynew;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class SignUp2 extends AppCompatActivity {
    EditText state, city, age;
    Button submitBtn;
    FirebaseAuth mAuth;
    DatabaseReference myRef;
    Users user;
    String firstName, lastName, _email, _pass, state_, city_, age_;

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

        state = (EditText) findViewById(R.id.state);
        city = (EditText) findViewById(R.id.city);
        age = (EditText) findViewById(R.id.age);
        submitBtn = (Button) findViewById(R.id.submitBtn);
        user = new Users();

        myRef = FirebaseDatabase.getInstance().getReference().child("Users");
        mAuth = FirebaseAuth.getInstance();

        /*if(mAuth.getCurrentUser() != null){
            startActivity(new Intent(getApplicationContext(), Home.class));
            Toast.makeText(SignUp2.this, "Welcome Back",Toast.LENGTH_LONG).show();
            finish();
        }*/

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firstName = getIntent().getStringExtra("fName");
                lastName = getIntent().getStringExtra("lName");
                _email = getIntent().getStringExtra("email");
                _pass = getIntent().getStringExtra("pass");

                state_ = state.getText().toString().trim();
                city_ = city.getText().toString().trim();
                age_ = age.getText().toString();

                user.setFname(firstName);
                user.setLname(lastName);
                user.setEmail(_email);
                user.setPass(_pass);
                user.setState(state_);
                user.setCity(city_);
                user.setAge(age_);

                if(state_.matches("") || city_.matches("") || age_.matches("")){
                    Toast.makeText(SignUp2.this, "Please fill all fields",Toast.LENGTH_LONG).show();
                }
                else{
                    myRef.push().setValue(user);
                    Toast.makeText(SignUp2.this, "Data Inserted",Toast.LENGTH_LONG).show();
                }

                mAuth.createUserWithEmailAndPassword(_email, _pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()){
                            Toast.makeText(SignUp2.this, "User Created",Toast.LENGTH_LONG).show();
                            startActivity(new Intent(getApplicationContext(), Home.class));
                        }else{
                            Toast.makeText(SignUp2.this, "Error",Toast.LENGTH_LONG).show();

                        }
                    }
                });
            }
        });

    }
}
EN

Stack Overflow用户

回答已采纳

发布于 2020-03-23 07:51:34

Users节点中,您没有使用userID,图片中的In是由push()方法生成的in。因此,首先将结构更改为使用userID而不是push(),然后您可以这样做:

代码语言:javascript
复制
mAuth = FirebaseAuth.getInstance();
u = mAuth.getCurrentUser();
userID = u.getUid();
myRef = FirebaseDatabase.getInstance().getReference("Users").child(userID);

            myRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                   String state = dataSnapshot.child("state").getValue(String.class);
                   query = FirebaseDatabase.getInstance().getReference("Jobs")
                    .orderByChild("location")
                    .equalTo(state);

                   query.addValueEventListener(new ValueEventListener() {
                    @Override
                   public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                     if(dataSnapshot.exists()){
                         //do whatever you want
                      }
                    }
                    @Override
                  public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(Home_NearYou.this, "Error", Toast.LENGTH_SHORT).show();
                     }
                  });

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

因此,首先从用户节点检索state。检索数据的唯一方法是使用addValueEventListener。检索state后,对jobs节点执行不同的查询,该查询检查location是否等于检索到的state,附加valueEventListener并使用exists()方法检查是否从该查询获得任何数据。

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60809410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档