Check for identical value in firebase collection - database

How would you implement a matching system to check when two values are the same in one collection from different documents? This code has to call a function to run every-time it detects that the two values are matching.

As mentioned in the documentation :
Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection or collection group. These queries > can also be used with either get() or addSnapshotListener(), as described in Get Data and Get Realtime Updates.
I will recommend you to use a unique identifier for each entry and then you can add a listener that will match each data from the collections.
Syntax :
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
} } }
You can refer to the Stackoverflow answer where Frank has explained it briefly with the following function code.
public interface AlreadyBookedCallback {
void onCallback(boolean isAlreadyBooked);
}
private void alreadyBooked(final String boname, final String bodept, final String botime, AlreadyBookedCallback callback) {
CollectionReference cref=db.collection("bookingdetails");
Query q1=cref.whereEqualTo("time",botime).whereEqualTo("dept",bodept);
q1.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot ds : queryDocumentSnapshots) {
String rname, rdept, rtime;
rname = ds.getString("name");
rdept = ds.getString("dept");
rtime = ds.getString("time");
if (rdept.equals(botime)) {
if (rtime.equals(botime)) {
isExisting = true;
}
}
}
callback.onCallback(isExisting)
}
});
}
For more information you can also refer to this thread on how to check duplicate values in documents.

Related

Objectify - save order of Ref<?>-s

I have a system where I'm trying to minimize the number of Datastore writes (who wouldn't?), all the while using ancestor relations. Consider the following simplified classes:
public class Ancestor {
#Id
private String id;
private String field;
private Ref<Descendant> descendantRef;
public Descendant getDescendant() {
return this.descendantRef.get();
}
public void setDescendant(Descendant des) {
this.descendantRef = Ref.create(des);
}
}
public class Descendant {
#Id
private String id;
private String field;
#Parent
private Key parent;
}
My problem: even though I set the descendant ref, upon saving the Ancestor entity, a null is saved, but if I save the Descendant as well, Objectify complains Attempted to save a null entity.
My question: I gathered that Objectify optimizes the order of get() operations with the #Load annotation, so is there a way to make it do the same on save() operations as well, so that by the time the Ancestor is being sent to the Datastore, the Descendant ref is populated properly?
Thank you in advance for any advice!
You can hide this implementation like this:
public Descendant getDescendant() {
// You probably don't want to break your code on null descendantRef
if (this.descendantRef != null) {
return this.descendantRef.get();
}
return null;
}
public void setDescendant(Descendant des) {
// Insert if this des have never been insert
if (getDescendant() != null) {
new DescendantEndpoint().insert(des);
}
// You probably don't want to break your code on null des
if (des != null) {
this.descendantRef = Ref.create(des);
}
}
By this, you don't have to do deal with each insertion of the ref on each endpoint you will make. Still, this method is not optimized for bulk insert as it will insert on each seperate datastore connection.
For this you can do something like this:
private Object bulkInsertAncestor(ArrayList<Ancestor> list){
ArrayList<Descendant> descendantArrayList = //get descendant list
// You should do all this inside a transaction
new DescendantEndpoint().bulkInsertDescendant(descendantArrayList);
return ofy().save().entities(list);
}
Objectify only complains that you Attempted to save a null entity if you literally pass a null value to the save() method.
This isn't an order-of-operations issue. FWIW, neither Objectify nor the underlying datastore provides any kind of referential integrity checks. It does not matter which you save first.

Retrieve more than 1000 results Google App Engine Search API

I need to be able to retrieve all records available in the index. Seems like 1000 is the limit. Is there something else I can do?
I was also facing some similar issue in one of my projects so researched over internet and got one idea that instead of using the Search API, I created a workaround scenario. What I did is I have only one attribute in my table which needs to have a pattern based search. I am sharing my code as well here.
Objectify Entity Class
#Entity
public class NewsFeed {
#Id
#Index
private Long feedID;
private String title;
private Set<String> titleKeywords;
// getters and setter
}
Logic for storing the keyword in the same table. I have split all the title words for my entity into keywords, and stored them in a Set Object.
NewsFeed newsFeed = new NewsFeed();
newsFeed.setTitle(title);
newsFeed.setTitleKeywords(getKeywordsSet(newsTitle));
// save entity here
Method for extracting keywords from title(field to be searched)
public Set<String> getKeywordsSet(String title) {
Set<String> keywords = new HashSet<String>();
String titleNews = title.toLowerCase();
String[] array = titleNews.split(" ");
for (int i = 0; i < array.length; i++) {
// replacing all special characters here
String word = array[i].replaceAll("\\W", "");
keywords.add(word);
}
return keywords;
}
Listing all the feeds from our DB, and finally matching the parameter to be searched, by the logic below.
public List<NewsFeed> getFilterJsonArray(String param){
// Listing all the objects of entity
List<NewsFeed> list = newsFeedDao.listOrderedFeeds();
List<NewsFeed> matchedObject = new ArrayList<NewsFeed>();
for (NewsFeed newsFeed : list) {
/**
* main logic for pattern matched keywords
**/
if (isAnElementInSet(newsFeed.getTitleKeywords(), param.toLowerCase())) {
matchedObject.add(newsFeed);
}
}
return matchedObject;
}
public boolean isAnElementInSet(Set<String> keywords, String param) {
String []params = param.split(" ");
if (keywords.size() > 0) {
for(String splittedParam : params){
if (keywords.contains(splittedParam)) {
return true;
} else{
for (String keyword : keywords) {
if(keyword.contains(splittedParam)){
return true;
}
}
return false;
}
}
return true;
}else{
return false;
}
}
I know this cannot be the best solution for searching things but this solution worked very fine for me. I just shared it here so as to get improvements in this logic as well.

updating values per row in parse.com using android platform

I have a problem with updating values per row in a cloud storage site called parse.com. I am only a newbie in using parse.com. I have read the documentation about it and have understand it. But what I want to do is a little bit different from the example there. Here's my code..
public void onClick(View arg0) {
if (arg0.getId() == R.id.button1) {
ParseQuery query = new ParseQuery("inventory");
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> test, ParseException e) {
ParseObject testObject = new ParseObject("inventory");
if(e==null) {
String str="";
String str2="";
for(int x =0;x<test.size();x++){
str = test.get(x).getString("name");
str2 = test.get(x).getString("quantity");
if (!str.equals(et1.getText().toString())){
str = "";
}
if(str.equals(et1.getText().toString()))
{
testObject.put("quantity", et2.getText().toString());
testObject.saveInBackground();
x = test.size();
}
else{
tv1.setText("error" + e.getMessage());
}
}
}}
});
} }
I want to update the quantity of the product name that i have inputted. when my input is equal to the name on the cloud it will update the other column which refers to the product name that I have inputted. But as a result of my code, it creates a new row, instead of updating the existing row.. what is lacking/wrong in my code? can someone please help me? :) thanks in advance! :)
I'm figuring out the same problem. I have found this:
The answer says to update an existing object, you need to retrieve it first. The retrieve method is given in the documentation on their website.
Edit:
Done! Here is how you do it; first fetch the object and then update the values you want to through the update method.
ParseQuery query = new ParseQuery("UserName");
query.getInBackground("GKIp4pxBrF", new GetCallback() {
public void done(final ParseObject object, ParseException e) {
if (e == null) {
object.put("Name", username);
object.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
object.put("Name", oldname);
}
});
}
else {
e.printStackTrace();
}
}
});
In case you don't know the object code before hand, I suggest you find the required row through a query.

saving variables wp7

Whats the best way to save variables like userid that is stored and reachable from different pages in WP7.
There's the querystring method, but can be kind of a pain to implement.
When navigating, pass the parameter like a HTTP querystring.
Then, on the otherside, check if the key exists, and extract the value. The downside of this is if you need to do more than 1, you need to type it in yourself, and it only supports strings.
So to pass an integer, you'd need to convert it. (And to pass a complex object, you need to take all the pieces you need to recompile it on the other side)
NavigationService.Navigate(new Uri("/PanoramaPage1.xaml?selected=item2", UriKind.Relative));
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string selected = String.Empty;
//check to see if the selected parameter was passed.
if (NavigationContext.QueryString.ContainsKey("selected"))
{
//get the selected parameter off the query string from MainPage.
selected = NavigationContext.QueryString["selected"];
}
//did the querystring indicate we should go to item2 instead of item1?
if (selected == "item2")
{
//item2 is the second item, but 0 indexed.
myPanorama.DefaultItem = myPanorama.Items[1];
}
base.OnNavigatedTo(e);
}
Here's a sample app that uses a querystring.
http://dl.dropbox.com/u/129101/Panorama_querystring.zip
A easier (and better) idea is to define a variable globally, or use a static class. In App.xaml.cs, define
using System.Collections.Generic;
public static Dictionary<string,object> PageContext = new Dictionary<string,object>;
Then, on the first page, simply do
MyComplexObject obj;
int four = 4;
...
App.PageContext.Add("mycomplexobj",obj);
App.PageContext.Add("four",four);
Then, on the new page, simply do
MyComplexObj obj = App.PageContext["mycomplexobj"] as MyComplexObj;
int four = (int)App.PageContext["four"];
To be safe, you should probably check if the object exists:
if (App.PageContext.ContainsKey("four"))
int four = (int)App.PageContext["four"];
You may use an App level variable (defined in App.xaml.cs) and access it from anywhere within your app. If you want to persist, shove it into Isolated Storage and read it on App launch/activate. There are helpers available to JSon serialize/deserialize your reads/writes from the Isolated Storage.
Check out Jeff's post (here) on tips to use Isolated Storage.
Hope this helps!
Well "best" is always subjective, however, I think an application service is a good candidate for this sort of thing:-
public interface IPhoneApplicationService : IApplicationService
{
string Name {get; set;}
object Deactivating();
void Activating(object state);
}
public class AuthenticationService : IPhoneApplicationService
{
public static AuthenticationService Current {get; private set; }
public void StartService(ApplicationServiceContext context)
{
Current = this;
}
public void StopService()
{
Current = null;
}
public string Name {get; set;}
public object Deactivating()
{
// Return an serialisable object such as a Dictionary if necessary.
return UserID;
}
public void Activating(object state)
{
UserID = (int)state;
}
public int UserID { get; private set; }
public void Logon(string username, string password)
{
// Code here that eventually assigns to UserID.
}
}
You place an instance of this in your App.xaml:-
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
<local:AuthenticationService Name="AuthServ" />
</Application.ApplicationLifetimeObjects>
Now you do need to tweak the App.xaml.cs:-
private void Application_Activated(object sender, ActivatedEventArgs e)
{
var state = PhoneApplicationService.Current.State;
foreach (var service in ApplicationLifetimeObjects.OfType<IPhoneApplicationService>())
{
if (state.ContainsKey(service.Name))
{
service.Activating(state[service.Name]);
}
}
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
var state = PhoneApplicationService.Current.State;
foreach (var service in ApplicationLifetimeObjects.OfType<IPhoneApplicationService>())
{
if (state.ContainsKey(service.Name))
{
state[service.Name] = service.Deactivating();
}
else
{
state.Add(service.Name, service.Deactivating());
}
}
}
You can now access you UserID anywhere in your app with:-
AuthenticationService.Current.UserID
This general pattern can be used to maintain seperation of key application wide services (you don't load a whole bunch of incohesive properties into your App class). It also provides the hooks for maintaining state between activations which is essential.

'Invalid attempt to read when no data is present' - exception happens "sometimes" in Entity Framework

I get the above error sometimes during the read. The exception originates from ASP.NET SqlDataReader whenever you try to read data before calling the Read() method. Since EF does all these internally, I am wondering what else can cause this error. could it be network (or) db connectivity?
thanks
Additional Bounty Info (GenericTypeTea):
I've got the same error after upgrading to EF Code First RC (4.1):
"Invalid attempt to read when no data
is present"
This is the code in question:
using (var context = GetContext())
{
var query = from item in context.Preferences
where item.UserName == userName
where item.PrefName == "TreeState"
select item;
// Error on this line
Preference entity = query.FirstOrDefault();
return entity == null ? null : entity.Value;
}
The table structure is as follows:
Preference
{
Username [varchar(50)]
PrefName [varchar(50)]
Value [varchar(max)] Nullable
}
The table is standalone and has no relationships. This is the DbModelBuilder code:
private void ConfigurePreference(DbModelBuilder builder)
{
builder.Entity<Preference>().HasKey(x => new { x.UserName, x.PrefName });
builder.Entity<Preference>().ToTable("RP_Preference");
}
Exactly the same code works perfectly in CTP5. I'm guessing this is an RC bug, but any ideas of how to fix it would be appreciated.
This error occurs when there is a large amount of data in the RC release. The difference between the RC and CTP5 is that you need to specify the [MaxLength] property that contains a large amount of data.
Are you re-using contexts? I would guess this is happening as a result of something you are doing within GetContext
If GetContext() provides a stale context, in which the DataReader is closed/corrupted, I could see the above happening.
I cannot reproduce your problem on EF4.1 RC1.
POCO:
public class Preference
{
public string UserName { get; set; }
public string PrefName { get; set; }
public string Value { get; set; }
}
Context:
public class PreferenceContext : DbContext
{
public DbSet<Preference> Preferences {get;set;}
public PreferenceContext()
: base("Data Source=localhost;Initial Catalog=_so_question_ef41_rc;Integrated Security=SSPI;") {
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
ConfigurePreference(modelBuilder);
base.OnModelCreating(modelBuilder);
}
private void ConfigurePreference(DbModelBuilder builder)
{
builder.Entity<Preference>().HasKey(x => new { x.UserName, x.PrefName });
builder.Entity<Preference>().ToTable("RP_Preference");
}
}
My little Console App:
class Program
{
static void Main(string[] args)
{
string userName = "Anon";
for (int i = 0; i < 10000; i++)
{
var p = GetPreference(userName);
}
}
private static string GetPreference(string userName)
{
using (var context = new PreferenceContext())
{
var query = from item in context.Preferences
where item.UserName == userName
where item.PrefName == "TreeState"
select item;
// Error on this line
Preference entity = query.FirstOrDefault();
return entity == null ? null : entity.Value;
}
}
}
I do 10,000 reads, and no error. You will need to post more complete code to continue.
Increase the CommandTimeout on the context.
I had the same issue with EF4 - In my case I was (trying to) return the list of entities within the using{} section. This is the same as you are doing in your question:
return entity == null ? null : entity.Value;
} // end using
I moved the return to after the } and it worked.
I think I had the problem because the code was in a function which had already queried the database in another using block, I suspect the table was locking but not reporting the error, ending the using block before the return released the database lock.
Steve

Resources