Iterating data from firebase into ArrayList - java

ArrayList<Site> siteList = new ArrayList<>();
String UID = user.getUid();
database = FirebaseDatabase.getInstance().getReference("/Users").child(UID);
storage = FirebaseStorage.getInstance().getReference("/Users").child(UID);
Getting no. of sites
database.child("Site No").get().addOnSuccessListener(dataSnapshot -> site_no = Integer.parseInt(dataSnapshot.getValue().toString()));
Trying to iterate
for(int i = 1; i<site_no; i++){
database.child("Sites").orderByChild("Site "+ i).get().addOnSuccessListener(dataSnapshot -> {
Site site = dataSnapshot.getValue(Site.class);
storage.child("Site " + i).getDownloadUrl().addOnSuccessListener(uri -> {
assert site != null;
site.setSiteImage(uri);
siteList.add(site);
System.out.println(siteList);
});
});
}
I want the data to be added into siteList arraylist, as I want to display it in a recycler view.

Related

List DataModel reads just the last element

I have a database created with location updates and in the database there is a bunch of locations x and y. and in the second method readFirestore() reads the location data and compares the favorite locations which came from sqlite database and if the favorite location is near the data from firestore it writes the campaign name which is on the same location to another database. But when I want to compare the favorite location in the firestore methot, there is just the last item of the database. I looked with the Log.
Code 1:
public List<DataModel> listFavoriteLocation(){
db = new DatabaseHelper(this);
SQLiteDatabase mydb = db.getWritableDatabase();
List<DataModel> data=new ArrayList<>();
Cursor csr = mydb.rawQuery("select * from "+TABLE+" ;",null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (csr.moveToNext()) {
dataModel= new DataModel();
String FAVCurrentLocationLAT = csr.getString(csr.getColumnIndexOrThrow("FAVCurrentLocationLAT"));
String FAVCurrentLocationLONG = csr.getString(csr.getColumnIndexOrThrow("FAVCurrentLocationLONG"));
dataModel.setFAVCurrentLocationLAT(FAVCurrentLocationLAT);
dataModel.setFAVCurrentLocationLONG(FAVCurrentLocationLONG);
stringBuffer.append(dataModel);
data.add(dataModel);
}
for (DataModel mo:data ) {
this.List_FAVCurrentLocationLAT = mo.getFAVCurrentLocationLAT();
this.List_FAVCurrentLocationLONG = mo.getFAVCurrentLocationLONG();
Log.i("helloLAT",""+List_FAVCurrentLocationLAT); //OK
Log.i("helloLONG",""+List_FAVCurrentLocationLONG); //OK
// This section writes the favorite locations seperately to the log.
}
return data;
}
Code 2:
public void readFirestore() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("campaigns")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
private String FSname,FScityLAT,FScityLONG,FScampaignStartDate,FScampaignEndDate;
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
for (QueryDocumentSnapshot document : task.getResult()) {
String name = document.getString("name");
String cityLAT = document.getString("cityLAT");
String cityLONG = document.getString("cityLONG");
String campaignStartDate = document.getString("campaignStartDate");
String campaignEndDate = document.getString("campaignEndDate");
this.FSname = name;
this.FScityLAT = cityLAT;
this.FScityLONG = cityLONG;
this.FScampaignStartDate = campaignStartDate;
this.FScampaignEndDate = campaignEndDate;
listFavoriteLocation();
String FS_FAVCurrentLocationLAT = List_FAVCurrentLocationLAT;
String FS_FAVCurrentLocationLONG = List_FAVCurrentLocationLONG;
Log.i("hellolist",""+List_FAVCurrentLocationLAT); // just writes the last loc item from sqlite
double FS_FAVCurrentLocationLAT_double = Double.parseDouble(FS_FAVCurrentLocationLAT); // Fav Loc DB
double FS_FAVCurrentLocationLONG_double = Double.parseDouble(FS_FAVCurrentLocationLONG); double FScityLAT_double = Double.parseDouble(FScityLAT); // Campaign Loc Firestore LAT
double FScityLONG_double = Double.parseDouble(FScityLONG);
double theta = FScityLONG_double - FS_FAVCurrentLocationLONG_double;
double dist = Math.sin(Math.toRadians(FS_FAVCurrentLocationLAT_double)) * Math.sin(Math.toRadians(FScityLAT_double)) + Math.cos(Math.toRadians(FS_FAVCurrentLocationLAT_double)) * Math.cos(Math.toRadians(FScityLAT_double)) * Math.cos(Math.toRadians(theta));
dist = Math.acos(dist);
dist = Math.toDegrees(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
if (dist <= 0.5) // 500 meter
{
SQLiteQueryFavCampaign = "INSERT OR REPLACE INTO myTable3(FAVCampaignName, FAVCampaigncampaignStartDate, FAVCampaigncampaignEndDate)" + " VALUES('"+FSname+"','"+FScampaignStartDate+"','"+FScampaignEndDate+"');";
SQLITEDATABASEFavCampaign.execSQL(SQLiteQueryFavCampaign);
Log.i("helloname",""+FSname);
}
}
} else {
}
}
});
Toast.makeText(CampaignActivity.this,"Creating", Toast.LENGTH_SHORT).show();
}
If I understand correctly: the listFavoriteLocation method properly retrieves the data you're expecting from the database. If you take a look at the rest of your code, you'll see that you are iterating over the list of data and overwriting your instance variables with them, one-by-one, until the list has been fully iterated over, meaning you will only preserve the last element in your instance once you've left the method.
So, to be clear, the following block will properly log every element, but only the values of the last element will be preserved in the two instance variables you're using (FAVCurrentLocationLAT and FavCurrentLocationLong):
for (DataModel mo:data ) {
this.List_FAVCurrentLocationLAT = mo.getFAVCurrentLocationLAT();
this.List_FAVCurrentLocationLONG = mo.getFAVCurrentLocationLONG();
Log.i("helloLAT",""+List_FAVCurrentLocationLAT); //OK
Log.i("helloLONG",""+List_FAVCurrentLocationLONG); //OK
// This section writes the favorite locations seperately to the log.
}
What you need to do is use the returned data list being loaded in the listFavoriteLocation method, and then manipulate it in the following code as you wish.
So, for example:
List<DataModel> data = listFavoriteLocation();
for (int i = 0; i < data.size(); i++) {
DataModel dataModel = data.get(i);
log.i("Data model "+i+": "+dataModel);
// Do work on each data model element here
}

TFS JAVA SDK - How to run shared query

I have a application which useds TFS JAVA SDK 14.0.3 .
I have a shared query  on my tfs , how can i run the shared query and get the response back using TFS SDK 14.0.3
Also I could see that the query url will expire in every 90 days , so any better way to execute the shared query?
Now I  have a method to run a query , i want method  to  run shared query also.
public void getWorkItem(TFSTeamProjectCollection tpc, Project project){
WorkItemClient workItemClient = project.getWorkItemClient();
// Define the WIQL query.
String wiqlQuery = "Select ID, Title,Assigned from WorkItems where (State = 'Active') order by Title";
// Run the query and get the results.
WorkItemCollection workItems = workItemClient.query(wiqlQuery);
System.out.println("Found " + workItems.size() + " work items.");
System.out.println();
// Write out the heading.
System.out.println("ID\tTitle");
// Output the first 20 results of the query, allowing the TFS SDK to
// page
// in data as required
final int maxToPrint = 5;
for (int i = 0; i < workItems.size(); i++) {
if (i >= maxToPrint) {
System.out.println("[...]");
break;
}
WorkItem workItem = workItems.getWorkItem(i);
System.out.println(workItem.getID() + "\t" + workItem.getTitle());
}
}
Shared query is a query which has been run and saved, so what you need should be getting a a shared query, not run a shared query. You could refer to case Access TFS Team Query from Client Object API:
///Handles nested query folders
private static Guid FindQuery(QueryFolder folder, string queryName)
{
foreach (var item in folder)
{
if (item.Name.Equals(queryName, StringComparison.InvariantCultureIgnoreCase))
{
return item.Id;
}
var itemFolder = item as QueryFolder;
if (itemFolder != null)
{
var result = FindQuery(itemFolder, queryName);
if (!result.Equals(Guid.Empty))
{
return result;
}
}
}
return Guid.Empty;
}
static void Main(string[] args)
{
var collectionUri = new Uri("http://TFS/tfs/DefaultCollection");
var server = new TfsTeamProjectCollection(collectionUri);
var workItemStore = server.GetService<WorkItemStore>();
var teamProject = workItemStore.Projects["TeamProjectName"];
var x = teamProject.QueryHierarchy;
var queryId = FindQuery(x, "QueryNameHere");
var queryDefinition = workItemStore.GetQueryDefinition(queryId);
var variables = new Dictionary<string, string>() {{"project", "TeamProjectName"}};
var result = workItemStore.Query(queryDefinition.QueryText,variables);
}
By the way, you could also check the REST API in the following link:
https://learn.microsoft.com/en-us/rest/api/vsts/wit/queries/get

Insert Multiple Rows realm android

Hello ive been trying to insert multiple rows to my realm database using values from arraylists , whenever i try to insert through a for loop it only adds the last one, if you need something else (code, xml) pls let me know
here is my code:
realm.executeTransactionAsync(new Realm.Transaction() { //ASYNCHRONOUS TRANSACCION TO EXECUTE THE QUERY ON A DIFFERENT THREAD
#Override
public void execute(Realm bgRealm) {
// increment index
Invoices inv = bgRealm.createObject(Invoices.class, RealmController.autoincrement(bgRealm, Invoices.class)); //METHOD THAT GIVES US THE AUTONINCREMENTE FUNCTION
//inv.id = nextId; //THE 2ND PARAMETER IN CREATE OBJECTE DEFINES THE PK
//...
//realm.insertOrUpdate(user); // using insert API
inv.number = n;
inv.serial = s;
inv.client = c;
inv.subtotal = sub;
inv.tax = tax;
inv.total = tot;
Invoice_lines invl = bgRealm.createObject(Invoice_lines.class, RealmController.autoincrement(bgRealm, Invoice_lines.class));//ID FROM ANOHTER TABLE (ROW)
for(int i=0; i<price.size(); i++) {
invl.description = description.get(i);
invl.price = price.get(i);
invl.quantity = quantity.get(i);
invl.invoice = inv;
bgRealm.insert(invl);
}
}
}
I'm not sure. You create only one realm object in this line:
Invoice_lines invl = bgRealm.createObject(Invoice_lines.class, RealmController.autoincrement(bgRealm, Invoice_lines.class));//ID FROM ANOHTER TABLE (ROW)
And in cycle you change invl fields, but don't insert new objects.
Try to create objects inside cycle.
Because what you wanted to do is
Invoice_lines invl = new Invoice_lines(); // unmanaged object
for(int i = 0; i < price.size(); i++) {
inv1.setId(RealmController.autoincrement(bgRealm, Invoice_lines.class));//ID FROM ANOHTER TABLE (ROW)
invl.description = description.get(i);
invl.price = price.get(i);
invl.quantity = quantity.get(i);
invl.invoice = inv;
bgRealm.insert(invl);
}

Retrieve multiple accounts from Microsoft CRM 2011 Online

With Microsoft CRM 2011 online and using webservices, I am using below method in my Main.java using the OrganizationServiceStub class created by webservices call. The output retrieved no of records is -1 can someone help where I am going wrong. I want to retrieve the accounts where name begins with "Tel" without giving the accountid. I can see the data exists in CRM.
Thanks
public static void getAccountDetails(OrganizationServiceStub service, ArrayOfstring fields)
{
try{
ArrayOfanyType aa = new ArrayOfanyType();
aa.setAnyType(new String[] {"Tel"});
ConditionExpression condition1 = new ConditionExpression();
condition1.setAttributeName("name");
condition1.setOperator(ConditionOperator.BeginsWith);
condition1.setValues(aa);
ArrayOfConditionExpression ss = new ArrayOfConditionExpression();
ss.setConditionExpression(new ConditionExpression[] {condition1});
FilterExpression filter1 = new FilterExpression();
filter1.setConditions(ss);
QueryExpression query = new QueryExpression();
query.setEntityName("account");
ColumnSet cols = new ColumnSet();
cols.setColumns(fields);
query.setColumnSet(cols);
query.setCriteria(filter1);
RetrieveMultiple ll = new RetrieveMultiple();
ll.setQuery(query);
RetrieveMultipleResponse result1 = service.retrieveMultiple(ll);
EntityCollection accounts = result1.getRetrieveMultipleResult();
System.out.println(accounts.getTotalRecordCount());
}
catch (IOrganizationService_RetrieveMultiple_OrganizationServiceFaultFault_FaultMessage e) {
logger.error(e.getMessage());
e.printStackTrace();
}
catch (RemoteException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
For Java, include this code snippet works for the above issue
ArrayOfanyType aa = new ArrayOfanyType();
aa.setAnyType(new String[] {"555"});
ConditionExpression condition1 = new ConditionExpression();
condition1.setAttributeName("telephone1");
condition1.setOperator(ConditionOperator.BeginsWith);
condition1.setValues(aa);
ArrayOfConditionExpression ss = new ArrayOfConditionExpression();
ss.setConditionExpression(new ConditionExpression[] {condition1});
FilterExpression filter1 = new FilterExpression();
filter1.setConditions(ss);
QueryExpression query = new QueryExpression();
query.setEntityName("account");
PagingInfo pagingInfo = new PagingInfo();
pagingInfo.setReturnTotalRecordCount(true);
query.setPageInfo(pagingInfo);
OrganizationServiceStub.ColumnSet colSet = new OrganizationServiceStub.ColumnSet();
OrganizationServiceStub.ArrayOfstring cols = new OrganizationServiceStub.ArrayOfstring();
cols.setString(new String[]{"name", "telephone1", "address1_city"});
colSet.setColumns(cols);
query.setColumnSet(colSet);
query.setCriteria(filter1);
RetrieveMultiple ll = new RetrieveMultiple();
ll.setQuery(query);
OrganizationServiceStub.RetrieveMultipleResponse response = serviceStub.retrieveMultiple(ll);
EntityCollection result = response.getRetrieveMultipleResult();
ArrayOfEntity attributes = result.getEntities();
Entity[] keyValuePairs = attributes.getEntity();
for (int i = 0; i < keyValuePairs.length; i++) {
OrganizationServiceStub.KeyValuePairOfstringanyType[] keyValuePairss = keyValuePairs[i].getAttributes().getKeyValuePairOfstringanyType();
for (int j = 0; j < keyValuePairss.length; j++) {
System.out.print(keyValuePairss[j].getKey() + ": ");
System.out.println(keyValuePairss[j].getValue());
}
}
Not sure how similar your EntityCollection object is to the .Net version in the SDK, however you need to specify ReturnTotalRecordCount in the query's PagingInfo in .Net for the TotalRecordCount property to have a value. Could you not instead check accounts.Entities.Count?
Note: I'm not a Java guy either...

Getting data from a HashMap into SQLite database

In my app I am retrieving records from a server. The records are in an xml file. I'm able to get the file down and parse it without any trouble. I'm storing the results in a HashMap and I'd like to be able to put those results into my app's SQLite database.
Here's the code for the HashMap
ArrayList<HashMap<String, String>> StudentDownloads = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML(target);
Document doc = XMLfunctions.XMLfromString(xml);
if(XMLfunctions.XMLfromString(xml)==null){
Toast.makeText(this, "Badly Formed File", Toast.LENGTH_LONG).show();
finish();
}
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(this, "There Were No Student Results To Show", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("Students");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("Student Id", "Student Id " + XMLfunctions.getValue(e, "StudentId"));
map.put("Student Type", "Student Type" + XMLfunctions.getValue(e, "StudentType"));
map.put("Student Location", "Student Location" + XMLfunctions.getValue(e, "StudentLocation"));
map.put("Student Mother", "Student Mother" + XMLfunctions.getValue(e, "StudentMother"));
StudentDownloads.add(map);}
};
Now in my app, I have already created a data entry form that uses a class called StudentRecord, in my entry form I use this function to update the file
private void addStudent(StudentRecord newRecord){
mDB.beginTransaction();
try {
ContentValues StudentRecordToAdd = new ContentValues();
StudentRecordToAdd.put(Students.STUDENT_ID, newRecord.getStudentName());
StudentRecordToAdd.put(Student.STUDENT_TYPE, newRecord.getStudentType());
StudentRecordToAdd.put(Student.STUDENT_LOCATION, newRecord.getStudentLocation());
StudentRecordToAdd.put(Student.STUDENT_MOTHER, newRecord.getStudentMother());
mDB.insert(Student.STUDENT_TABLE_NAME,Student.STUDENT_ANIMALID, StudentRecordToAdd);
mDB.setTransactionSuccessful();
Toast.makeText(this,"Recorded Added ",0).show();
} finally {
mDB.endTransaction();
}
What's the best way to get my values from the HashMap to my NewRecord function? I've been looking at so long I think I've gone brain dead.
Thank you
If i'm reading you right, it sounds like you need to move your addStudent function from the form/activity where it lives right now into some kind of "helper" class:
private class dbHelper {
Database mDB; // set this up however you are doing it already
private void addStudent(StudentRecord newRecord){
mDB.beginTransaction();
try {
ContentValues StudentRecordToAdd = new ContentValues();
StudentRecordToAdd.put(Students.STUDENT_ID, newRecord.getStudentName());
StudentRecordToAdd.put(Student.STUDENT_TYPE, newRecord.getStudentType());
StudentRecordToAdd.put(Student.STUDENT_LOCATION, newRecord.getStudentLocation());
StudentRecordToAdd.put(Student.STUDENT_MOTHER, newRecord.getStudentMother());
mDB.insert(Student.STUDENT_TABLE_NAME,Student.STUDENT_ANIMALID, StudentRecordToAdd);
mDB.setTransactionSuccessful();
Toast.makeText(this,"Recorded Added ",0).show();
} finally {
mDB.endTransaction();
}
}
}
And then just make calls to that helper when you've parsed your XML
ArrayList<StudentRecord> StudentDownloads = new ArrayList<StudentRecord>();
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element)nodes.item(i);
int id = Integer.valueOf(XMLfunctions.getValue(e, "StudentId")));
int type = Integer.valueOf(XMLfunctions.getValue(e, "StudentType")));
String location = XMLfunctions.getValue(e, "StudentLocation"));
String mother = XMLfunctions.getValue(e, "StudentMother"));
StudentRecord newRecord = new StudentRecord(id, type, location, mother);
StudentDownloads.add(newRecord);
}
And then when you're done processing:
for (StudentRecord s : StudentDownloads) {
mDBHelper.addStudent(s);
}

Categories

Resources