为什么我的代码会从Firebase中提取两次数据? Android的工作室

时间:2018-05-29 02:30:44

标签: android firebase firebase-realtime-database

我不记得我做错了什么,因为我之前已经修好了。 我想要做的是从firebase检索作业发布数据并将其放在我的列表视图中但是当我这样做时,作业帖子有重复。关于如何解决这个问题的任何想法?

我将在下面添加日志和代码。

这里是日志,我记录了日志和脚本中的日志"首先计算工作数"

 05-28 20:24:06.391 17592-17592/test.com.jobTestApp D/FindWorkFragment: getPhotos: getting photos
    getPhotos: getting jobs count first count = 0
05-28 20:24:06.772 17592-17592/test.com.jobTestApp D/FindWorkFragment: onDataChange: getJOBS  {job_headline=Website, date_posted=yesterday, user_country=United States, time_frame= 7 days, job_desc=Hello, fullname=Tom, category=Web Development, budget=30}
    onDataChange: jobs count = 1
    onDataChange: getJOBS  {job_headline=Website, date_posted=today, user_country=United States, user_id=QkGIMPFXDoPfpnwnPileLRtyR243, time_frame=6 days, job_desc=stuff, fullname=Odi Ohn, category=Web Development, budget=24}
    onDataChange: jobs count = 2
05-28 20:24:06.773 17592-17592/test.com.jobTestApp D/FindWorkFragment: onDataChange: getJOBS  {job_headline=Website, date_posted=yesterday, user_country=United States, time_frame= 7 days, job_desc=Hello, fullname=Tom, category=Web Development, budget=30}
    onDataChange: jobs count = 3
    onDataChange: getJOBS  {job_headline=Website, date_posted=today, user_country=United States, user_id=QkGIMPFXDoPfpnwnPileLRtyR243, time_frame=6 days, job_desc=stuff, fullname=Odi Ohn, category=Web Development, budget=24}
    onDataChange: jobs count = 4
05-28 20:24:06.776 17592-17592/test.com.jobTestApp D/FindWorkFragment: onDataChange: jobs count = 4

以下是代码:

public class FindWorkFragment extends Fragment implements AdapterView.OnItemSelectedListener{

private static final String TAG = "FindWorkFragment";

private ImageView btnBack;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;

private ArrayList<PostJob> mJobs;
private ArrayList<PostJob> mPaginatedPhotos;
private ArrayList<String> mJobsinCat;
private ListView mListView;
private JobFeedListAdapter mAdapter;
private int mResults;

private Spinner mSearchCat;
private String searchCat;
private ArrayAdapter<CharSequence> mSearchCategoryAdapter;

public static FindWorkFragment newInstance(int instance) {
    Bundle args = new Bundle();
    args.putInt("argsInstance", instance);
    FindWorkFragment thirdFragment = new FindWorkFragment();
    thirdFragment.setArguments(args);
    return thirdFragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_findwork, container, false);

    final Fragment fragment = new FindWorkFragment();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    btnBack = (ImageView) view.findViewById(R.id.iv_back);

    mSearchCat = (Spinner) view.findViewById(R.id.spSearchCat);
    mSearchCategoryAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.job_categories, android.R.layout.simple_spinner_item);
    mSearchCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mSearchCat.setAdapter(mSearchCategoryAdapter);
    mSearchCat.setOnItemSelectedListener(this);

    mListView = (ListView) view.findViewById(R.id.joblistview);
    mJobsinCat = new ArrayList<>();
    mJobs = new ArrayList<>();

    getJobsinCat();

    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.main_frag_container, new HomeDashboardFragment());
            ft.commit();
        }
    });

    return view;
}

private void getJobsinCat(){
    Log.d(TAG, "getFollowing: searching for following");
    String key = myRef.child("Web Development").push().getKey();
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    Query query = reference
            .child(getString(R.string.dbname_jobs))
            .child("United States")
            .child("Web Development");
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                Log.d(TAG, "onDataChange: found user: " +
                        singleSnapshot.getKey());

                mJobsinCat.add(singleSnapshot.getKey().toString());
            }
            //mJobsinCat.add(FirebaseAuth.getInstance().getCurrentUser().getUid());
            //get the photos
            getPhotos();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void getPhotos(){
    Log.d(TAG, "getPhotos: getting photos");
    Log.d(TAG, "getPhotos: getting jobs count first count = " + mJobs.size() );
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    for(int i = 0; i < mJobsinCat.size(); i++){
        final int count = i;
        Query query = reference
                .child(getString(R.string.dbname_jobs))
                .child("United States")
                .child("Web Development")
                .orderByKey();
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

                    PostJob job = new PostJob();
                    Log.d(TAG, "onDataChange: getJOBS  " + singleSnapshot.getValue());
                    Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();

                    //job.setUser_country(objectMap.get("user_country").toString());
                    job.setJob_headline(objectMap.get("job_headline").toString());
                    job.setJob_desc(objectMap.get("job_desc").toString());
                    job.setBudget(objectMap.get("budget").toString());
                    job.setTime_frame(objectMap.get("time_frame").toString());
                    //job.setTags(objectMap.get(getString(R.string.field_tags)).toString());
                    //job.setPhoto_id(objectMap.get(getString(R.string.field_photo_id)).toString());
                    //job.setUser_id(objectMap.get(getString(R.string.field_user_id)).toString());
                    //job.setDate_posted(objectMap.get("date_posted").toString());
                    //job.setImage_path(objectMap.get(getString(R.string.field_image_path)).toString());

                    /*
                    // soon going to be the proposals

                    ArrayList<Comment> comments = new ArrayList<Comment>();
                    for (DataSnapshot dSnapshot : singleSnapshot
                            .child(getString(R.string.field_comments)).getChildren()){
                        Comment comment = new Comment();
                        comment.setUser_id(dSnapshot.getValue(Comment.class).getUser_id());
                        comment.setComment(dSnapshot.getValue(Comment.class).getComment());
                        comment.setDate_created(dSnapshot.getValue(Comment.class).getDate_created());
                        comments.add(comment);
                    }

                    photo.setComments(comments);*/
                    mJobs.add(job);
                }
                if(count >= mJobsinCat.size() -1){
                    //display our photos
                    displayPhotos();
                    Log.d(TAG, "onDataChange: jobs count = " + mJobs.size());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

private void displayPhotos(){
    mPaginatedPhotos = new ArrayList<>();
    if(mJobs != null){
        try{
            /*
            Collections.sort(mJobs, new Comparator<PostJob>() {
                @Override
                public int compare(PostJob o1, PostJob o2) {
                    return o2.getDate_posted().compareTo(o1.getDate_posted());
                }
            });*/

            int iterations = mJobs.size();

            if(iterations > 10){
                iterations = 10;
            }

            mResults = 10;
            for(int i = 0; i < iterations; i++){
                mPaginatedPhotos.add(mJobs.get(i));
            }

            mAdapter = new JobFeedListAdapter(getActivity(), R.layout.layout_jobfeed_listitem, mPaginatedPhotos);
            mListView.setAdapter(mAdapter);

        }catch (NullPointerException e){
            Log.e(TAG, "displayPhotos: NullPointerException: " + e.getMessage() );
        }catch (IndexOutOfBoundsException e){
            Log.e(TAG, "displayPhotos: IndexOutOfBoundsException: " + e.getMessage() );
        }
    }
}

public void displayMorePhotos(){
    Log.d(TAG, "displayMorePhotos: displaying more photos");

    try{

        if(mJobs.size() > mResults && mJobs.size() > 0){

            int iterations;
            if(mJobs.size() > (mResults + 10)){
                Log.d(TAG, "displayMorePhotos: there are greater than 10 more photos");
                iterations = 10;
            }else{
                Log.d(TAG, "displayMorePhotos: there is less than 10 more photos");
                iterations = mJobs.size() - mResults;
            }

            //add the new photos to the paginated results
            for(int i = mResults; i < mResults + iterations; i++){
                mPaginatedPhotos.add(mJobs.get(i));
            }
            mResults = mResults + iterations;
            mAdapter.notifyDataSetChanged();
        }
    }catch (NullPointerException e){
        Log.e(TAG, "displayPhotos: NullPointerException: " + e.getMessage() );
    }catch (IndexOutOfBoundsException e){
        Log.e(TAG, "displayPhotos: IndexOutOfBoundsException: " + e.getMessage() );
    }
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    searchCat = parent.getItemAtPosition(position).toString();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

}

1 个答案:

答案 0 :(得分:0)

查看您在getPhotos()循环中添加query.addListenerForSingleValueEvent的{​​{1}},以便根据for执行多次,将其从循环中拉出以便单次调用< / p>

mJobsinCat.size()