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.
Related
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.
I have created a multi list in GUI Designer. I am setting the model as below
#Override
protected boolean initListModelMultiIssueList(List cmp) {
fetchIssues(cmp);
if (issueVector != null ) {
cmp.setModel(new DefaultListModel(issueVector));
System.out.println(cmp);
}
return true;
}
void fetchIssues( List c){
//fetch issues based on the searchquery hash
//first thing is to create the query from the hash
System.out.println("Starting to fetch results");
try{
java.util.List<ServiceRequest> serviceRequests = ServiceRequest.getServiceRequests(formQuery(searchQuery),true);
//we need to now populate the issueVector
//with the data
System.out.println(serviceRequests.toString());
if (issueVector != null ) {
issueVector.clear();
} else {
issueVector = new Vector();
}
int index = 0;
for (ServiceRequest serviceRequest : serviceRequests) {
Hashtable hIssue = new Hashtable();
hIssue.put("id",serviceRequest.getHref());
//System.out.println(hIssue);
ImageDownloadService.createImageToStorage(serviceRequest.getRequestPictureURL().toString(),
c, index, "icon",
"service-icon-"+ index ,null);
//hIssue.put("icon", serviceRequest.getRequestPictureURL().toString());
//System.out.println(hIssue);
//reverse geocode the location
Double x = new Double(0.0);
x=new Double(serviceRequest.getRequestLocationLatitude());
Double y = new Double(serviceRequest.getRequestLocationLongitude());
String location=reverseGeocode(x, y);
hIssue.put("location", location);
//System.out.println(hIssue);
Service service = serviceRequest.loadService();
hIssue.put("service", serviceRequest.loadService().getName().toString());
hIssue.put("reportedOn",serviceRequest.getCreatedAt().toString());
//System.out.println("Final hIssue" + hIssue.toString());
issueVector.add(hIssue);
index=index+1;
System.out.println(issueVector);
}
}catch (Exception e){
System.out.println("Error loading search results");
System.out.println(e);
}
}
The icon in the multi list GUI design has been set to the appropriate property. ImageDownloadService does download the image files but then it does not display in the list as expected. What am I doing wrong?
Its possible that the image is downloaded before the entry is available. Although its hard to tell with the code and without a clear explanation of the symptoms.
You need to first create the model and set it to the list (ideally with a blank placeholder image so the list doesn't "jump"). Then you need to loop over the list and invoke the image download service, otherwise it might return before the data is in the list and fail! This can happen if the image is already in cache so its very likely to fail fast in that case.
I have a wcf which retrieves information from a database.
I also have a Silverlight client application which references that service and uses it to retrieve the data.
public void init(ref Cluster cluster)
{
_SelectedCluster = cluster;
MyEntities svc = new MyEntities(new Uri("http://localhost:49672/MyDataService.svc/"));
docs = new DataServiceCollection<EC_Documents>();
var query = from c in svc.EC_Documents
where c.clusterID == _SelectedNode.ID
orderby c.clusterID
select c;
docs.LoadCompleted += docs_LoadCompleted;
docs.LoadAsync(query);
}
private void docs_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (e.Error == null)
{
if (docs.Continuation != null)
{
docs.LoadNextPartialSetAsync();
}
else
{
_SelectedCluster.Value = docs.Count;
}
}
}
Because the call is asynchronous, I had to make docs a member of the class and check its count at the docs_LoadCompleted method.
I also have a _SelectedCluster which is an object of type Cluster as a member in the class,which holds the current cluster object in the iteration.
I have a problem assigning the result to the currently selected node _SelectedCluster.Value member.
Because the call is asynchronous, I cannot iterate on all my clusters objects and assign the result synchronously, If I do that, the assignment is always on the last cluster in the iteration.
Any suggestions?
Re-arrange your code to benefit from closures:-
public void init(Cluster cluster)
{
MyEntities svc = new MyEntities(new Uri("http://localhost:49672/MyDataService.svc/"));
var docs = new DataServiceCollection<EC_Documents>();
var query = from c in svc.EC_Documents
where c.clusterID == _SelectedNode.ID
orderby c.clusterID
select c;
docs.LoadCompleted += (s, e) =>
{
if (e.Error == null)
{
if (docs.Continuation != null)
{
docs.LoadNextPartialSetAsync();
}
else
{
cluster.Value = docs.Count;
}
}
};
docs.LoadAsync(query);
}
Now multiple calls to init can be made each using its own instance DataServiceCollection<EC_Documents>. I'm not sure what you want to do about the _SelectedNode.ID value that looks wrong to me, you ought to be passing that value in as a parameter on the init. Of course with docs now being local you will need to decide what to with it once all the docs for a cluster ID is loaded.
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
Im hoping that someone has used the very excellent PagedList from Troy Goode? Im actually using it in a Winforms app, and while it does work, I have lost the ability to sort it.
Returning a PagedList, controlling the Page and Size, and binding to a DataGridView is no issue, but my biggest concern is Sorting. Now I have also come across the SortedPageList by Muhammad Mosa, but I really am confused with one of the parameter requirements. I am using a private method to return a SortedPageList, but my code below does not seem to work:
private SortedPagedList<Location, Location> GetInactiveLocationData(int Index, int Size) {
sysDataContext ctx = new sysDataContext();
try {
var query = ctx.Location.Where(x => x.Active == false).AsQueryable();
return query.ToPagedList(Index, Size, i => i, false);
//return new SortedPagedList<Location, Location>(query, Index, Size, i => i , true);
}
catch (Exception) {
throw;
}
}
This throws an error "Cannot order by type: Location". Obvously, I would like to handle the case where the user clciks a column header to sort on that column.
I know that the solution involves Lambda Expressions above a level of knowledge I have (embarrassing as it is to admit) and I am completely clueless on this front! I would really value your advice on the abovementioned!
Thank u!
Well, you can start by learning some basic LINQ operations (scroll down to the "ordering" portion. Or here: LINQ Part 1 - Filtering & Sorting Object Lists .
Once you discover the magic, you'll fly :P
OK, I feel like an idiot!...well, somewhat! I got the following to work:
using (sysContext ctx = new sysDataContext()) {
try {
var data = ctx.Location.Where(x => x.Active == false).AsQueryable();
var query = data.ToPagedList(PageIndex, PageSize, o => o.DueDate, true);
dgv.DataSource = query;
}
catch (Exception) {
throw;
}
}
Now, the sort expression is described here as o => o.DueDate. This is great, and while this does work, Im trying to now find a way to create a generic function that will allow me:
Detect which column header was clicked (with a switch statement perhaps)
Convert its type into the appropriate Linq Entity property
Pass that property into a generic method
A mehod that looks something like the following:
private void RefreshData([type] SortExpression, bool Ascending, int PageIndex, int PageSize) {
using (sysDataContext ctx = new sysDataContext()) {
try {
var data = ctx.Location.AsQueryable();
var query = data.ToPagedList(PageIndex, PageSize, o => o.[SortExpression], Ascending);
dgv.DataSource = query;
}
catch (Exception) {
throw;
}
}
}
Is this possible?
One thing additionally (if it will help you help me) the SortedPageList method looks like so:
public static SortedPagedList<T, TResult> ToPagedList<T, TResult>(this IQueryable<T> source, int index, int pageSize, System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, bool asc) {
return new SortedPagedList<T, TResult>(source, index, pageSize, keySelector, asc);
}
How do I express System.Linq.Expressions.Expression<Func<T, TResult>> as a type that can be passed as a parameter?