How to get 50 big numbers (ascending order) in Realm database? - android

I'm using Realm database for my android project. I'm having a field called invoice number (Integer). The invoice number is stored in sequential order. But in this series, some numbers may not be there. For example[1,5,11,20,55,.......].
Now I want to retrieve first 50 big numbers in ascending order in Realm database.

RealmResults<MyObject> results = realm.where(MyObject.class).findAllSorted("invoiceNumber");
List<Integer> list = new LinkedList<>();
int first = Math.max(results.size()-50, 0);
for(int i = first; i < first + 50 && i < results.size(); i++) {
list.add(results.get(i).getInvoiceNumber());
}
return new ArrayList<>(list);

Related

records inserted in a sqlite table are the same for each row

I have a JSONArray which contains many records. I want to compare a string inside those object with a similar(I know it has the same value) record in my SQLite db. but when I loop the table each row value has the first row value.
INSERT A RECORD TO DB >> it returns different value
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
JSONObject row = pagamenti.getJSONObject(i); /** LOOP OGGETTI */
String fattura = row.getString("Fattura");
String descrizione = row.getString("Descrizione");
String scadenza = row.getString("Data Scadenza");
String importo = row.getString("Importo");
String stato = row.getString("Stato Pagamento");
// FATURA SHOW ALL DIFFRERENtS VALUE CORRECTLY
fieldsNameTasse.add("fattura");
fieldsValueTasse.add(fattura);
Toast.makeText(getContext(), fattura.toString(), Toast.LENGTH_LONG).show();
fieldsNameTasse.add("descrizione");
fieldsValueTasse.add(descrizione);
fieldsNameTasse.add("scadenza");
fieldsValueTasse.add(scadenza);
fieldsNameTasse.add("importo");
fieldsValueTasse.add(importo);
fieldsNameTasse.add("stato");
fieldsValueTasse.add(stato);
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
CHECK DB ROW VALUE << it returns always the first value
/** SHOW ALWAYS THE SAME VALUE*/
int counter = 0;
Cursor cursor = DBmanager.readAll("TasseIncoming");
while(cursor.moveToNext()) {
String ffattura = cursor.getString(cursor.getColumnIndex("fattura"));
counter++;
Toast.makeText(getContext(), ffattura+" - "+counter, Toast.LENGTH_LONG).show();
}
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
Every time you loop, you're just adding values to the end of what's already in those ArrayLists. So there's lots of duplicate column names with different values for each. Some quick testing:
sqlite> create table foo(a, b);
sqlite> insert into foo(a,b,a,b) values(1,2,3,4);
sqlite> select * from foo;
a b
---------- ----------
1 2
indicates that when a column is included multiple times in an INSERT, only the first corresponding value is used. Hence only ever getting the values from the first iteration of the loop.
The easy fix is to move those variable definitions inside the loop, so each insert is done with a fresh set of columns and values:
for (int i = 0; i < pagamenti.length(); i++) {
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}

getStringArrayList get only the last list without consider the name

I try to send several lists to other activity so I wrote the following code:
ArrayList<String> sections = new ArrayList<String>();
for(int i=1; i<=last; i++)
{
sections.clear();
for(j = 0; j < size; j++)
{
sections.add(someText);
}
ourIntent.putStringArrayListExtra("sections_"+i, sections);
}
As you can see for every loop cycle of i, the name I give to the sent list is different (sections_1, sections_2, ...).
The sections list is cleared in each loop cycle. And in debug mode I can see that in every loop cycle the sections have the right list.
The problem is in the next activity. When I take the list, with the following code:
sections1 = extras.getStringArrayList("sections_1");
sections2 = extras.getStringArrayList("sections_2");
sections1 and sections2 get the same list, which is the last list that was inserted in putStringArrayListExtra.
Anyone can explain this behavior?
I believe this is because it's storing a reference to your ArrayList, and not a copy of the current "state" of the list on each iteration of your loop.
For example, you first insert a reference to your ArrayList when it contains 1 item. Next, you insert a reference to your ArrayList when it contains 2 items. Both are just references, so when you actually transition to the next Activity, it copies the full ArrayList.
To fix this, you could actually make a local copy of the ArrayList each time you loop.
ArrayList<String> sections = new ArrayList<String>();
for(int i=1; i<=last; i++) {
sections.clear();
for(j = 0; j < size; j++){
sections.add(someText);
}
// Creating a new local copy of the current list.
ArrayList<String> newList = newArrayList<>(sections);
// Inserting the local copy instead.
ourIntent.putStringArrayListExtra("sections_"+i, newList);
}

Updating realm object by increments

I have a realm object that contains list of items with IDs
#SerializedName("products")
RealmList<ProductDialItem> products;
#SerializedName("previous_suppliers")
RealmList<SuppliersDialItem> previousSuppliers;
#SerializedName("tariffs")
RealmList<TariffsDialItem> tariffs;
#SerializedName("deposit_frequencies")
RealmList<SimpleDialItem> depositFrequencies;
#SerializedName("bank_codes")
RealmList<SimpleDialItem> bankCodes;
#SerializedName("gas_usages")
RealmList<SimpleDialItem> gasUsages;
And so on, each item in list has ID. The server sends a json response with values to be filled in the object.
But we also use Last-Modified header, so that server only sends items that changed. I want only to update items, not to delete any of them.
Tl;dr how do I only update/add items to realm, but not delete them
let the object contain:
class MyClass{
int x = 0;
int y = 0;
int z = 0;
}
then if you need to increment the variables from the web:
MyClass finalObject = new MyClass();
MyClass tempObject = new Gson().fromJson(response,MyClass.class);
incrementObjects(tempObject,finalObject);
and now create the method incrementObjects() :
private void incrementObjects(MyClass obj1, MyClass obj2){
obj2.x += obj1.x;
obj2.y += obj1.y;
obj2.z += obj1.z;
}
You can Query on Realm when you get updated data response like,
//Create RealmList when you get updated Data in your api response.
RealmList<YourModel> updatedData = yourResponseData.getData();
//Get data from localDatabase and Query on
RealmQuery<YourModel> where = mRealm.where(YourModel.class);
for (int i = 0; i < updatedData.size(); i++) {
//put condition to match data based on your database.
where = where.notEqualTo(YourModel.NAME,updatedData.get(i).getName());
}
//Now this where.findAll(); , will return list of data which is notEqual To updatedData
//perform update operation with this or deleteFrom local Data and insert new/updated Data.
where.findAll();

Android: Uploading multiple string records to Parse.com

I am working on a app where I would like to upload a string array. Code as follows:
Code:
upload_list = getResources().getStringArray(R.array.upload_list);
Utilities.custom_toast(this, ""+upload_list.length, "");
ParseObject database = new ParseObject("table_name");
for (int m = 0; m < upload_list.length; m++)
{
database.put("name_full", upload_list[m]);
database.saveInBackground();
}
Question:
The above string array has 90 items. After going through the above code, 1 new row is added to the table, and keep refreshing the table in Parse, different strings picked from the above string array is reflected in the row.
I would like instead inserting 90 new rows to the table.
How could that be fixed? Many thanks in advance!
if you want NEW ROW in the loop, move the new ParseObject :
ParseObject database;
...
for (int m = 0; m < upload_list.length; m++)
{
database = new ParseObject("table_name");
database.put("name_full", upload_list[m]);
database.saveInBackground();
}

Populate listview according to distance

I am using gooleplaces API. I have a response in json, but the problem is I want to populate listview according to distance. I make the sorted distance arraylist in ascending order using collections.sort(), but how do I sort other lists based on this sorted list to populate my listview correctly?
If you are creating separate lists, then you need to your define method, and if you are using list of single collection, or data structure, you can define your comparator, then call sort on this, list.
Finally I resolve my problem using bubble sort.
if (distanceList.size()>1) // check if the number of orders is larger than 1
{
for (int i=0; i<distanceList.size()-1; i++) // bubble sort outer loop
{
for (int j=0; j < distanceList.size()-1-i; j++) {
if (distanceList.get(j)>(distanceList.get(j+1)) )
{
int temp = distanceList.get(j);
distanceList.set(j,distanceList.get(j+1) );
distanceList.set(j+1, temp);
String temp1 = nameList.get(j);
nameList.set(j,nameList.get(j+1) );
nameList.set(j+1, temp1);
String temp2 = vicinityList.get(j);
vicinityList.set(j,vicinityList.get(j+1) );
vicinityList.set(j+1, temp2);
String temp3 = latList.get(j);
latList.set(j,latList.get(j+1) );
latList.set(j+1, temp3);
String temp4 = longList.get(j);
longList.set(j,longList.get(j+1) );
longList.set(j+1, temp4);
}
}
}
}

Categories

Resources