Java Code Examples for com.google.firebase.database.Query#keepSynced()

The following examples show how to use com.google.firebase.database.Query#keepSynced() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeepSyncedTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void differentQueriesAreIndependent() throws Exception {
  DatabaseReference ref = IntegrationTestHelpers.getRandomNode();
  Query query1 = ref.limitToFirst(1);
  Query query2 = ref.limitToFirst(2);

  query1.keepSynced(true);
  assertIsKeptSynced(query1);
  assertNotKeptSynced(query2);

  query2.keepSynced(true);
  assertIsKeptSynced(query1);
  assertIsKeptSynced(query2);

  query1.keepSynced(false);
  assertIsKeptSynced(query2);
  assertNotKeptSynced(query1);

  query2.keepSynced(false);
  assertNotKeptSynced(query1);
  assertNotKeptSynced(query2);
}
 
Example 2
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void getPostListByUser(final OnDataChangedListener<Post> onDataChangedListener, String userId) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY);
    Query postsQuery;
    postsQuery = databaseReference.orderByChild("authorId").equalTo(userId);

    postsQuery.keepSynced(true);
    postsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            PostListResult result = parsePostList((Map<String, Object>) dataSnapshot.getValue());
            onDataChangedListener.onListChanged(result.getPosts());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "getPostListByUser(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
 
Example 3
Source File: KeepSyncedTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDifferentIndependentQueries() throws Exception {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  Query query1 = ref.limitToFirst(1);
  Query query2 = ref.limitToFirst(2);

  query1.keepSynced(true);
  assertIsKeptSynced(query1);
  assertNotKeptSynced(query2);

  query2.keepSynced(true);
  assertIsKeptSynced(query1);
  assertIsKeptSynced(query2);

  query1.keepSynced(false);
  assertIsKeptSynced(query2);
  assertNotKeptSynced(query1);

  query2.keepSynced(false);
  assertNotKeptSynced(query1);
  assertNotKeptSynced(query2);
}
 
Example 4
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void getPostListByUser(final OnDataChangedListener<Post> onDataChangedListener, String userId) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY);
    Query postsQuery;
    postsQuery = databaseReference.orderByChild("authorId").equalTo(userId);

    postsQuery.keepSynced(true);
    postsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            PostListResult result = parsePostList((Map<String, Object>) dataSnapshot.getValue());
            onDataChangedListener.onListChanged(result.getPosts());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "getPostListByUser(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
 
Example 5
Source File: RestorePresenter.java    From FastAccess with GNU General Public License v3.0 6 votes vote down vote up
@Override public void onRestore(@NonNull DatabaseReference databaseReference, @Nullable String userId) {
    this.userId = userId;
    FirebaseUser user = getView().user();
    if (InputHelper.isEmpty(userId)) {
        if (user != null) userId = user.getUid();
    }
    if (InputHelper.isEmpty(userId)) {
        getView().onShowMessage(R.string.login_first_msg);
        getView().finishOnError();
    } else {
        getView().onShowProgress();
        Query query = databaseReference
                .child(userId);
        query.keepSynced(true);
        query.addListenerForSingleValueEvent(this);
    }
}
 
Example 6
Source File: KeepSyncedTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void keepSyncedAffectsQueries() throws Exception {
  DatabaseReference ref = IntegrationTestHelpers.getRandomNode();
  ref.keepSynced(true);
  Query query = ref.limitToFirst(5);
  query.keepSynced(true);
  assertIsKeptSynced(ref);

  ref.keepSynced(false);
  assertNotKeptSynced(ref);
  assertNotKeptSynced(
      query); // currently, setting false on the default query affects all queries at that
  // location
}
 
Example 7
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void getPostList(final OnPostListChangedListener<Post> onDataChangedListener, long date) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY);
    Query postsQuery;
    if (date == 0) {
        postsQuery = databaseReference.limitToLast(Constants.Post.POST_AMOUNT_ON_PAGE).orderByChild("createdDate");
    } else {
        postsQuery = databaseReference.limitToLast(Constants.Post.POST_AMOUNT_ON_PAGE).endAt(date).orderByChild("createdDate");
    }

    postsQuery.keepSynced(true);
    postsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, Object> objectMap = (Map<String, Object>) dataSnapshot.getValue();
            PostListResult result = parsePostList(objectMap);

            if (result.getPosts().isEmpty() && result.isMoreDataAvailable()) {
                getPostList(onDataChangedListener, result.getLastItemCreatedDate() - 1);
            } else {
                onDataChangedListener.onListChanged(parsePostList(objectMap));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "getPostList(), onCancelled", new Exception(databaseError.getMessage()));
            onDataChangedListener.onCanceled(context.getString(R.string.permission_denied_error));
        }
    });
}
 
Example 8
Source File: KeepSyncedTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeepSyncedAffectOnQueries() throws Exception {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  ref.keepSynced(true);
  Query query = ref.limitToFirst(5);
  query.keepSynced(true);
  assertIsKeptSynced(ref);

  ref.keepSynced(false);
  assertNotKeptSynced(ref);
  // currently, setting false on the default query affects all queries at that location
  assertNotKeptSynced(query);
}
 
Example 9
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void getPostList(final OnPostListChangedListener<Post> onDataChangedListener, long date) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY);
    Query postsQuery;
    if (date == 0) {
        postsQuery = databaseReference.limitToLast(Constants.Post.POST_AMOUNT_ON_PAGE).orderByChild("createdDate");
    } else {
        postsQuery = databaseReference.limitToLast(Constants.Post.POST_AMOUNT_ON_PAGE).endAt(date).orderByChild("createdDate");
    }

    postsQuery.keepSynced(true);
    postsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, Object> objectMap = (Map<String, Object>) dataSnapshot.getValue();
            PostListResult result = parsePostList(objectMap);

            if (result.getPosts().isEmpty() && result.isMoreDataAvailable()) {
                getPostList(onDataChangedListener, result.getLastItemCreatedDate() - 1);
            } else {
                onDataChangedListener.onListChanged(parsePostList(objectMap));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "getPostList(), onCancelled", new Exception(databaseError.getMessage()));
            onDataChangedListener.onCanceled(context.getString(R.string.permission_denied_error));
        }
    });
}
 
Example 10
Source File: LoadFirebaseFriends.java    From kute with Apache License 2.0 4 votes vote down vote up
@Override
protected Void doInBackground(Integer... params) {
    //Through params we can pass the indices for which data is required
    Log.v(TAG,"The indices received here are "+Integer.toString(params[0])+"and "+Integer.toString(params[1]));
    final ArrayList<Person>person_detail_list=new ArrayList<Person>();
    DatabaseReference users= FirebaseDatabase.getInstance().getReference("Users");
    final AsyncTaskListener taskListener=async_task_listener.get();
    taskListener.onTaskStarted(params[0],params[1]);
    for(int i=params[0];i<=params[1];++i) {
        Log.v(TAG,"The size in asynctask is"+Integer.toString(friend_list.size()));
        if (i<friend_list.size()) {
            Log.v(TAG,"Status:entered");
            String first_friend_key = friend_list.get(i);
            Query get_friend = users.orderByKey().equalTo(first_friend_key);
            get_friend.keepSynced(true);
            get_friend.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    try {
                        //Added a a try except just to prevent finding those friends who does not exist now
                        Person p = dataSnapshot.getChildren().iterator().next().getValue(Person.class);
                        if (async_task_listener != null) {
                            //Check if the weak reference still exists
                            Log.v(TAG, "Retrieved Friend " + p.name);
                            taskListener.onTaskCompleted(p);
                        }
                    }catch (Exception e){
                        Log.i(TAG,"Error Receiving particular person details from firebase Person Might not Exist");
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }
        else {
            Log.v(TAG,"All Friends Already Downloaded");
            break;
        }
    }
    return null;
}
 
Example 11
Source File: FragmentListDevs.java    From TwrpBuilder with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.fragment_list_developers, container, false);
    RecyclerView recyclerView = v.findViewById(R.id.rv_list_devs);
    Query query = FirebaseDatabase.getInstance()
            .getReference("Developers");
    FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder()
            .setQuery(query, Developer.class)
            .build();
    query.keepSynced(true);

    String s = null;

    adapter = new FirebaseRecyclerAdapter<Developer, ListContributorsHolder>(options) {
        @NonNull
        @Override
        public ListContributorsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_developers, parent, false);
            return new ListContributorsHolder(view);
        }

        @Override
        protected void onBindViewHolder(@NonNull ListContributorsHolder holder, int position, @NonNull Developer dev) {
            String key = getRef(position).getKey();
            holder.bind(
                    dev.getEmail(),
                    dev.getName(),
                    dev.getPhotoUrl(),
                    dev.getXdaUrl(),
                    dev.getGitId(),
                    dev.getDonationUrl(),
                    dev.getDescription(),
                    key
            );
        }

        @Override
        public void onDataChanged() {
            super.onDataChanged();
            ProgressBar progressBar = v.findViewById(R.id.pb_builds);
            TextView textView = v.findViewById(R.id.tv_no_build);
            new FirebaseProgressBar(progressBar, textView, adapter, "Developers");
        }
    };
    LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

    ProgressBar progressBar = v.findViewById(R.id.pb_builds);
    TextView textView = v.findViewById(R.id.tv_no_build);
    new FirebaseProgressBar(progressBar, textView, adapter, "Developers");

    return v;
}
 
Example 12
Source File: FragmentStatusCommon.java    From TwrpBuilder with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_builds_common, container, false);

    RecyclerView lvBuilds = view.findViewById(R.id.lv_builds);
    Query query;
    if (filterQuery != null) {
        query = FirebaseDatabase.getInstance().getReference().child(reference).orderByChild(filterQuery).equalTo(equalTo);

    } else {
        query = FirebaseDatabase.getInstance()
                .getReference(reference);
    }
    query.keepSynced(true);
    FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder()
            .setQuery(query, Pbuild.class)
            .build();
    adapter = new FirebaseRecyclerAdapter<Pbuild, BuildsHolder>(options) {
        @NonNull
        @Override
        public BuildsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_build_common, parent, false);
            if (filterQuery != null) {
                return new BuildsHolder(view, reference, true, getContext());
            } else {
                return new BuildsHolder(view, reference, false, getContext());
            }
        }

        @Override
        protected void onBindViewHolder(@NonNull BuildsHolder holder, int position, @NonNull Pbuild model) {
            holder.bind(
                    model.getEmail(),
                    model.getModel(),
                    model.getBoard(),
                    model.getDate(),
                    model.getBrand(),
                    model.getDeveloperEmail(),
                    model.getRejector(),
                    model.getNote(),
                    model.getUrl());
        }

        @Override
        public void onDataChanged() {
            super.onDataChanged();
            ProgressBar();
        }
    };
    ProgressBar();
    LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    layoutManager.setReverseLayout(true);
    layoutManager.setStackFromEnd(true);
    lvBuilds.setLayoutManager(layoutManager);
    lvBuilds.setAdapter(adapter);
    return view;

}