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
}
Related
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.
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);
}
I want to iterate on an ArrayList called localWifiList that contains the wifi networks detected by a wifi scan.
For every element of the ArrayList I want to run a query to get all tuples in the database with that specific mac address, create a new object and add this object into a new arrayList called wifiFromDatabase.
I wrote this code:`
ArrayList<wifiList> wifiFromDatabase = new ArrayList<wifiList>();
ArrayList<wifiList> localWifiList = ScanService.wifiArraList;
//field to read the values of wifi query results
String mac;
String ssid;
String cid;
String signalLevel;
String capabilities;
String rssi;
String lat, lng;
String date;
String frequency;
int flagInt;
Cursor cursor;
Iterator<wifiList> iterator = localWifiList.iterator();
while(iterator.hasNext()){
wifiList element = (wifiList) iterator.next();
cursor = MainActivity.getDBOperationHelper().getWifiTupleByMac
(MainActivity.getDBOperationHelper().getReadableDatabase(), element.getMacAddress());
if(cursor.getCount()>0){
if (cursor .moveToFirst()) {
while (cursor.isAfterLast() == false) {
mac = cursor.getString(cursor.getColumnIndex(DBOperationHelper.MAC));//
ssid = cursor.getString(cursor.getColumnIndex(DBOperationHelper.SSID));//
capabilities = cursor.getString(cursor.getColumnIndex(DBOperationHelper.CAPABILITIES));//
frequency = cursor.getString(cursor.getColumnIndex(DBOperationHelper.FREQUENCY));//
cid = cursor.getString(cursor.getColumnIndex(DBOperationHelper.CELL_ID_UMTS));//
signalLevel = cursor.getString(cursor.getColumnIndex(DBOperationHelper.SIGNAL_LEVEL_WIFI));//
rssi = cursor.getString(cursor.getColumnIndex(DBOperationHelper.RSSI));
lat = cursor.getString(cursor.getColumnIndex(DBOperationHelper.GPS_LATITUDE_WIFI));//
lng = cursor.getString(cursor.getColumnIndex(DBOperationHelper.GPS_LONGITUDE_WIFI));//
date = cursor.getString(cursor.getColumnIndex(DBOperationHelper.DATE_WIFI));//
flagInt = cursor.getInt(cursor.getColumnIndex(DBOperationHelper.FLAG));
wifiList objectFromDb = WifiPhoneConfiguredNetworkHandler.CreateProperlyWifiListObject(ssid, capabilities, frequency, signalLevel, ConnectionPointAnalyzer.INVALID_ID_WIFI, signalLevel,
mac, rssi, date, cid, lat, lng, flagInt, false);
wifiFromDatabase.add(objectFromDb);
cursor.moveToNext();
}
}
}else{ //the database has not tuples with this mac
Log.d(ConnectionPointAnalyzer.LOG_TAG, "OracoloBrain.java/AllInterfacesActived: no tuples found in the db with mac = "+element.getMacAddress()+
" ssid = "+element.getSsid());
}
} `
where the method CreateProperlyWifiListObject create an wifiList object given the fields passed as arguments.
I read many thread about this issues, but nothing to do. I try also with synchronized on the arrayList.
The exception is thrown by iterator.next() command.
Try to create a copy:
ArrayList<wifiList> localWifiList = new ArrayList<wifiList>(ScanService.wifiArraList);
I have this requirement to show the amount with thousand separator. I have this POJO class with these two methods which I call according to my requirements
public Integer getTotalAmount() {
return totalAmount;
}
public String getTotalAmountWithSeparator() {
return String.format("%,d", totalAmount);
}
public void setTotalAmount(Integer totalAmount) {
this.totalAmount = totalAmount;
}
now when I use this method getTotalAmountWithSeparator() in my another class which looks like this and I do a println to see if the amount is being shown properly(which it does).
List<SupplierOrderDetails> list = SupplierOrderDetailBussinessLogic.getInstance().getSupplierOrderDetailsFromsupplierOrder(supplierOrder);
DataProviderBuilder dpb = new DataProviderBuilder();
// add heading data
dpb.add("so", supplierOrder.getSupplierOrderNo());
dpb.add("sn", supplierOrder.getSupplier().getPerName());
dpb.add("sec", supplierOrder.getSection().getAlternateName());
dpb.add("od", supplierOrder.getSupplierOrderCreated().toString());
// add table data
dpb.addJavaObject(list, "data");
here is the actual method getSupplierOrderDetailsFromsupplierOrder(supplierOrder); which gets the data from the db.
#SuppressWarnings("unchecked")
public List<SupplierOrderDetails> getSupplierOrderDetailsFromsupplierOrder(SupplierOrder supplierOrderDetails){
Session hibernateSession = HibernateUtills.getInstance().getHibernateSession();
Criteria criteria = hibernateSession.createCriteria(SupplierOrderDetails.class);
criteria.add(Restrictions.eq("supplierOrderID", supplierOrderDetails));
List<SupplierOrderDetails> models = criteria.list();
System.out.println(" models.size() " + models.size());
for (int i = 0; i < models.size(); i++)
{
if (models.get(i).getId() != null)
{
models.get(i).getProductID().getProductCode();
models.get(i).getProductID().getBrandName();
models.get(i).getPurchasePrice();
models.get(i).getOrderQty();
models.get(i).getTotalAmountWithSeparator();
System.out.println(models.get(i).getProductID().getBrandName() + " TotalAmount " + models.get(i).getTotalAmountWithSeparator());
}
// System.out.println(models.get(i).getPurchasePrice());
}
return models;
}
but when I do a println of the list data here,it does not show the separator in the amount why?????what am I doing wrong
dp = getSupplierOrderData(Long.parseLong(supplierOrderId));
System.out.println("DATA "+dp.getString("data"));
because dp.toString() method uses getTotalAmount() and not getTotalAmountWithSeparator()
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);
}