Phonegap takes too long time to read contact on android 4.3 - android

I created an app using phonegap to read and list all contact detail
to read contact here is the code
var field=["displayName"];
var options = new ContactFindOptions();
options.filter=""; // empty search string returns all contacts
options.multiple=true;
var contat=navigator.contacts.find(field, contactSucc, contactError,options);
function contactSucc(contacts) {
alert("loading contact");
var str="";
for (var i=0; i<contacts.length; i++) {
if(contacts[i].displayName)
str="Name = " +(contacts[i].displayName) + " <br/>";
$('#contactId').append(str);
}
}
This code work almost instant on android 2.3/4.1 (1 second) but it take too long on android 4.3 (25 second)
Most time is take by quering database
Please note:- all device loaded with same amount of contact info (around 1k contact detail)
Is there any workaround.. Or is there anyone who face the same problem

You can follow below steps:
Ask for the required information using 'desiredFields' filter.
Identify whether you want all contacts or contacts which has at least one contact number
Store fetched contacts in sql lite
Search new or updated contacts using date time stored when you last time fetched the contacts.

Related

Flutter-Dart Firebase Get a Summe from Docs

I wanna get a Summe from Firebase with Flutter-Dart, i can with Stream Builder all Datas receiving but i wanna get a Summe-Total from Orders. For Example how much money did i earn for this month ? or How much money i have to Pay to my Owner ? My Firebase Database look like this,
[Firebase Struktur][1]
[1]: https://i.stack.imgur.com/E5zsM.png
I wanna get the Grand Total for all "betrag", i tried this like it , but its coming a null, how can i all Documents as List with choosed Feld with For Loop Grand total Calculating and show in the Text ?
var rechnungider = 0;
firestoreInstance.collection("rechnungen").doc().get().then((value) {
for (int i = value.data()!.length; i > value.data()!.length; i++) {
print(value.data());
rechnungider += int.parse(value.data()!["betrag"]);
}
box.write("rechnunggider", rechnungider.toString());
print("Rechnunggider Yenilendi:${box.read("rechnunggider")}");
//print(value.data.toString());
});
}
I wanna show without Document name, i mean all betrag data from all Documents.Total Value, Summe.
Thanks
Please do not calculate the sum of collections on the frontend. I can't warn you enough!
I would recommend to create a cloud function that saves the sum on another place in your database. It is the recommended approach for getting the sum for a value from a collection.
Let me know if you need an example for the functions to write.

Using the google sheets api after completing quickstart tutorial

I'm pretty new to Android app development so please forgive my naivety.
I'm currently trying to develop an app that can pull data from a google spreadsheet and write data to it.
I've completed the quickstart tutorial so my code is the same as that right now. It all works correctly.
My issue is I need to be able to read from my own spreadsheet and I don't really understand the code used so I'm struggling to know where to start.
I've looked at this to try and implement the authorisation in fewer steps which I thought might make the code easier to understand - but again my lack of knowledge means I don't know how this fits into all the methods I currently have.
I've looked at the developer documentation and tried to replace the code from the quickstart which retrieves data from the app with this:
ValueRange result = service.spreadsheets().values().get(spreadsheetId, range).execute();
int numRows = result.getValues() != null ? result.getValues().size() : 0;
System.out.printf("%d rows retrieved.", numRows);
But again this is different to the code I already have so doesn't fit in as the getDataFromApi() method requires a return statement. I've tried just changing the spreadsheetId to that of my own spreadsheet and changing the range value to the cells I need,
/**
* Fetch a list of names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
* #return List of names and majors
* #throws IOException
*/
private List<String> getDataFromApi() throws IOException {
String spreadsheetId = "1-hL78Jm9-HijPx9UHthFxcXatkIhA2FR-AQ1lrCUbEg";
String range = "Go Mix 12 0506!B6:D";
List<String> results = new ArrayList<String>();
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
results.add("Name, Major");
for (List row : values) {
results.add(row.get(1) + ", " + row.get(3));
}
}
return results;
}
but I'm clearly going about it wrong because I get this error:
Invalid index 3, size is 3
I've also followed up to video 15 on this tutorial but it bypasses the need for any authorisation so didn't help.
Basically I've hit a brick wall and need someone to explain to me in simple terms how I can either work with the code from the quickstart tutorial to work with my own spreadsheet and fix that error! OR (more preferable to myself) explain how to do it myself from scratch. NB the spreadsheet cannot be public so I will need authorisation.
I hope that all makes sense!
You are asking to retrieve three columns of data (B through D), but then attempting to read a fourth column (rows.get(3)). In Java (and in most programming languages), lists and arrays are 0-based. So if you want the first item, you call list.get(0), and if you want the third you call list.get(2). This is evident based on the fact that the error message tells you your index of 3 is invalid since the list is size 3 -- you're attempting to read something beyond the end of the list.

How to know how many people are connected to Firebase in Android studio?

pretty straightforward question. im making an android app that uses firebase authentication for users to connect with email and password an also the firebase realtime database service.
i wanted to know if i can check through android studio how many people are currently connected to my database(through Firebase Authentication)
thanks in advance!
This is an old question but in case someone is searching for a solution, I've found some info on Firebase docs:
https://firebase.google.com/docs/firestore/solutions/presence
It's very simple. Every time a user is connecting to your app, add him in a Firebase category, named users. Then you can query on that category to see the exact number of users using the following line of code:
int numberOfUsers = dataSnapshot.getChildrenCount();
var database = firebase.database();
// connecting users
var connectionsRef = database.ref("/connections");
var connectedRef = database.ref(".info/connected");
// Number of online users is the number of objects in the presence list.
// When the client's connection state changes...
connectedRef.on("value", function(snap) {
// If they are connected..
if (snap.val()) {
// Add user to the connections list.
var con = connectionsRef.push(true);
// Remove user from the connection list when they disconnect.
con.onDisconnect().remove();
}
});
// When first loaded or when the connections list changes...
connectionsRef.on("value", function(snapshot) {
// Display the viewer count in the html.
// The number of online users is the number of children in the connections list.
console.log("numers of players are:"+ snapshot.numChildren());
$(".displayDiv").text(snapshot.numChildren());

android - getting all rows from external database - good idea?

I have an application in android, a database on the server and I wrote api in django. I want for my application to work online and offline. So far I did local database in android and api returns query results in json. (database is very simply, just one table with 7 fields). But I don't know nothing about databases performance. I wonder if a good strategy is to getting all rows from table (from server), delete all rows from local database, and save all new rows to local database? Or update all fields in existing rows? Or maybe online/offline app is not a good idea? How long can take downloading 1000 rows from database on server?
Maybe this is silly question, but really, I'm looking for a solution ;)
my model in Django looks like that:
class Quote(models.Model):
user = models.ForeignKey(User)
quote = models.TextField(verbose_name="Quotation")
accepted = models.BooleanField(default=False, verbose_name="Accepted")
deleted = models.BooleanField(default=False, verbose_name="Deleted")
date = models.DateTimeField(verbose_name="Date", auto_now=True)
good = models.PositiveIntegerField(default=0, verbose_name="Rate good")
bad = models.PositiveIntegerField(default=0, verbose_name="Rate bad")
class Favourite(models.Model):
user = models.ForeignKey(User)
quote = models.ForeignKey(Quote)
And I send by json only table Quote (username, quote, accepted, deleted, date, good, bad).
An api function:
#csrf_exempt
def api(request):
if request.method == 'POST':
operation = request.POST['operation']
print 'operation', operation
response_data = {}
response_data['result'] = 'FAILED'
if operation == 'getFive':
itemsList = []
ID = int(request.POST['id'])
if ID == -1:
querySet = Quote.objects.filter(deleted=False).order_by('-id')[:5]
else:
querySet = Quote.objects.filter(id__lt=ID, deleted=False).order_by('-id')[:5]
maxID = Quote.objects.filter(deleted=False).order_by('-id')[0].id
minID = Quote.objects.filter(deleted=False).order_by('id')[0].id
for item in querySet:
tmp = {}
tmp['id'] = item.id
tmp['username'] = item.user.username
tmp['quote'] = item.quote
tmp['accepted'] = item.accepted
tmp['deleted'] = item.deleted
tmp['date'] = dateformat.format(item.date, "Y-m-d H:i:s")
tmp['good'] = item.good
tmp['bad'] = item.bad
itemsList.append(tmp)
print item.id, item.quote
response_data['result'] = 'SUCCESS'
response_data['items'] = itemsList
response_data['maxID'] = maxID
response_data['minID'] = minID
response_data['items'] = itemsList
return HttpResponse(json.dumps(response_data), content_type="application/json")
return redirect("/")
My problem is that I don't want to user wait very long time to run the application and I don't how long data can be downloaded by smartphone with HSDPA/3G/LTE etc. where are ~1000 rows in table. Let's say there is ~1500 characters by one row. If I counted good it's 1500 B * 1000 rows = 1500000 Bytes = 1464 KB = ~1,42 MB... So I think it's much, but I'm not an expert.
I forgot add, that when row have 'deleted'=True, I don't send it to smartphone.
And my question again: Sending all rows from server to android app, every time when app starts, is a good idea?
Thanks, and sorry for my english ;).
I can explain a solution for ya, but I cannot really show you how to do it.
You only want to get all rows if its the first time the user is opening your app. So youll do an update if not exist to your local DB.
When you are doing this, you will want it to be in the background so the user can go ahead and start poking around your application. Maybe do a toast to display that the background thread is downloading the records and it might take a while.
Break up the download with a cursor to only download x records at a time. Download 50 and return, download 50 and return. That way the user can see the records being downloaded and they do not have to wait until ALL records are returned.

PhoneGap contact picker

Now that PhoneGap is version 2.0, is there a (potentially undocumented) way to have a contact picker?
The docs make it seem like I'd have to write my own in JavaScript by requesting ALL the user's contacts, then building my own in-app contact picker.
http://docs.phonegap.com/en/2.0.0/cordova_contacts_contacts.md.html#Contacts
I've found a one-off plug-in for Android, but that's not helpful if there's no plug-in for iPhone, cause then I'd still have to write my own. I'm looking for a device agnostic method that says "let the user go pick a contact, then send them back here with that contact info"
I don't know whether you can use this solution for Android as well but for iPhone you can use the .chooseContact() method.
Example:
Choose a contact
function contactChooser(){
//The chooseContact method will open a new window with all you contacts
navigator.contacts.chooseContact(
//After picking a name you will receive the id of the chosen contact
function(id){
//In an options variable you can set some filter parameters
//In this example we will use the Id to receive the data of the chosen contact
var options = {
filter: ""+id
}
//In the fields variable we're going to set the fields we want to receive
//'*' = every data. More field values are explained
// here: http://bit.ly/T8YyuE
var fields = ['*'];
navigator.contacts.find(fields, onPickContactSuccess, onPickContactError, options);
}, null);
}
function onPickContactSuccess(contacts){
//contacts contains all data you've requested
var _name = contacts[0].name
alert('Last: '+_name.familyName+' First: '+_name.givenName);
}

Categories

Resources