Flutter: GeoFire library search queryAtLocation not working - firebase

I am testing the Flutter Library https://github.com/bramvbilsen/Flutter-GeoFire.
When I load the example/main.dart file from the library (pointing it to my Firebase) the setLocation() method works (the entry writes to my FirebaseDB) but not the read location or query At Location methods.
// Methods from library example not working..
void getAndPrintLocation() {
geofire.getLocation("Mechelen", new LocationCallBack(
(String key, List<double> location) {
print("Successfully received location!");
print(key + ": " + location.toString());
},
(DatabaseError error) {
print("Error receiving location!");
print(error.toString());
}
));
}
void createQuery(List<double> location, double radius) {
this.query = geofire.queryAtLocation(location, radius);
print(this.query.toString());
}
The return message from queryAtLocaion
I/flutter (18068): GeoQuery
I/flutter (18068): --- Center: [51.0259, 4.4775]
I/flutter (18068): --- Radius: 450.0
What am I missing. I am simply trying to get the keys from the queryAtLocaion(location, radius)

Related

Invalid Credential - Unity Firebase

I've been developing an app in Unity for the past two years and only now realized that my phone authentication didn't work correctly. This is because I'm developing on Android and therefore I've always only seen the results of "verificationCompleted" and not codeSent.
In other words, putting the SMS code in manually doesn't work. It says that the credential is invalid. IT ISN'T! The code is right. The thing is, that I copied my code over to another project, and then it worked perfectly. Therefore it's probably nothing wrong with my code. What could've happened here? Also, everything worked fine, until I was supposed to verify the code itself. I got the SMS etc.
When can you get the error, invalid credential, when the code isn't wrong?
Feels like I've tried everything!
Thanks in advance for any help!
Here's some pictures of my code as well. Some stuff has nothing to do with the authentication, but yeah...
public void VerifyPhoneNumber(string _phoneNumber)
{
Debug.Log(String.Format("Auth is {0}, AuthenticationController is {1} and GameController is {2}.", auth, authenticationController, null));
var phoneAuthProvider = Firebase.Auth.PhoneAuthProvider.GetInstance(auth);
phoneAuthProvider.VerifyPhoneNumber(_phoneNumber, phoneAuthTimeoutMs, null,
verificationCompleted: (cred) =>
{
Debug.Log("Verification Completed");
MutualUiController.mutualUI.loadingPanel.gameObject.SetActive(false);
auth.SignInWithCredentialAsync(cred).ContinueWith(HandleSignInResult);
},
verificationFailed: (error) =>
{
Debug.Log("Verification Failed" + error);
},
codeSent: (id, token) =>
{
Debug.Log("Verification Code Sent");
phoneAuthVerificationId = id;
Debug.Log("ID: " + id + ", Token: " + token.ToString());
if (SceneController.currentScene == Scene.AuthenticationPage)
{
MutualUiController.mutualUI.loadingPanel.gameObject.SetActive(false);
Transform panel = GameObject.Find("AuthPageUI").GetComponent<AuthPageUI>().verificationPanel;
panel.gameObject.SetActive(true);
}
},
codeAutoRetrievalTimeOut: (id) =>
{
Debug.Log("Code Auto Timeout");
});
}
//verificationCompleted: (cred) =>
// {
// //Debug.Log("Verification Completed");
// //MutualUiController.mutualUI.loadingPanel.gameObject.SetActive(false);
// //auth.SignInWithCredentialAsync(cred).ContinueWith(HandleSignInResult);
// },
public void VerifyRecievedPhoneCode(string recievedCodeInput)
{
var phoneAuthProvider = Firebase.Auth.PhoneAuthProvider.GetInstance(auth);
var cred = phoneAuthProvider.GetCredential(phoneAuthVerificationId, recievedCodeInput);
auth.SignInWithCredentialAsync(cred).ContinueWith(HandleSignInResult);
}

'Unable to fetch remote config. Cached or default values will be 'used' flutter

I have setup firebase config for flutter
According to documentation https://pub.dev/packages/firebase_remote_config#-readme-tab-
My key is
then I have Published also then i tried following code and it will return
'Unable to fetch remote config. Cached or default values will be ''used'
could you please point issue
I have tried those also
Firebase Remote Config - Initial fetch return local default values
Remote config in Flutter app throws exception on fetch
try {
remoteConfig.getString('welcome')[![enter image description here][1]][1]
// Using default duration to force fetching from remote server.
await remoteConfig.fetch(expiration: const Duration(seconds: 0));
await remoteConfig.activateFetched();
} on FetchThrottledException catch (exception) {
// Fetch throttled.
print(exception);
} catch (exception) {
print(
'Unable to fetch remote config. Cached or default values will be '
'used');
}
This worked fine for me,
await remoteConfig.ensureInitialized();
it's work for me
FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.instance;
initializeRemote() async {
// remoteConfig = await setupRemoteConfig();
//!- must be active firebase remote config
bool updated = await remoteConfig.fetchAndActivate();
if (updated) {
print("found");
// the config has been updated, new parameter values are available.
} else {
print("not print");
// the config values were previously updated.
}
await remoteConfig.ensureInitialized().then((value) async {
print("remote value -> ${await remoteConfig.getString("app_version")}");
});
}
Usually when you fight these problems, in the end, everything gets mixed up. I think after the post you could already see the configured value, but the error occurs when querying another parameter name. Add the following line to see the actual error you are getting.
print('EXCEPTION: $exception');
try {
await remoteConfig.fetch(expiration: const Duration(seconds: 0));
await remoteConfig.activateFetched();
String forceUpdateCurrentVersion =
remoteConfig.getString('force_update_current_version');
double newVersion =
double.parse(forceUpdateCurrentVersion.trim().replaceAll(".", ""));
if (newVersion > currentVersion) {
_showVersionDialog(context);
}
} on FetchThrottledException catch (exception) {
// Fetch throttled.
print(exception);
} catch (exception) {
print('EXCEPTION: $exception');
print('Unable to fetch remote config. Cached or default values will be '
'used');
}
Just put value don't put braces for Default value
For Example
Then use below code in flutter
remoteConfig.getString('IT_');
If you are using Android emulator, ensure it has Google play services enabled.

ClientException, and i can't print the returned value (the request body)

Alright i'm losing my mind here,
in my flutter app, i'm using this function to perform post requests :
Future<Map> postRequest(String serviceName, Map<String, dynamic> data) async {
var responseBody = json.decode('{"data": "", "status": "NOK"}');
try {
http.Response response = await http.post(
_urlBase + '$_serverApi$serviceName',
body: jsonEncode(data),
);
if (response.statusCode == 200) {
responseBody = jsonDecode(response.body);
//
// If we receive a new token, let's save it
//
if (responseBody["status"] == "TOKEN") {
await _setMobileToken(responseBody["data"]);
// TODO: rerun the Post request
}
}
} catch (e) {
// An error was received
throw new Exception("POST ERROR");
}
return responseBody;
}
The problems are :
I get a ClientException (Not every time)
In another class, I stored the result of this function in a variable, it's supposed to return a Future<Map<dynamic, dynamic>>, when i printed it it shows :
I/flutter ( 9001): Instance of 'Future<Map<dynamic, dynamic>>'
But when i run the same post request directly (without using a function) it worked, and it shows the message that i was waiting for.
note: in both cases (function or not), in the server side it was the same thing.
this is the function where i used the post request:
void _confirm() {
if (_formKey.currentState.saveAndValidate()) {
print(_formKey.currentState.value);
var v = auth.postRequest("se_connecter", _formKey.currentState.value);
print(v);
} else {
print(_formKey.currentState.value);
print("validation failed");
}
}
Well for the second problem, i just did these changes:
void _confirm() async {
and
var v = await auth.postRequest('se_connecter', _formKey.currentState.value);
and yes it is stupid.
For the exception, it was the ssl encryption that caused it, so i removed it from my backend.

React Native AsyncStorage | Row too big to fit into CursorWindow

I'm using AsyncStorage in ReactNative to store some data (large size >2MB) on device, and then read it with the following code
try {
const value = await AsyncStorage.getItem('date_stored_copy');
} catch (e) {
console.log(e);
}
I'm getting the following error:
Row too big to fit into CursorWindow requiredPos=0, totalRows=1...
Is there any way to increase CursorWindow size, or another alternative to AsyncStorage ?
An alternative solution would be to split the data into chunks and then writing it.
I write a wrapper that uses AsyncStorage that does exactly that: https://gist.github.com/bureyburey/2345dfa88a31e00a514479be37848d42
Be aware that it was originally written for using with apollo-cache-persist (a persistence lib for apollo-client).
And since graphql store the data in a very flat structure this solution works pretty well out of the box.
For your case, if your stored object looks like this:
{
data: { a lot of data here }
}
Then it wouldn't matter much and the wrapper won't work
But if your object looks like this:
{
someData: { partial data },
someMoreData: { more partial data },
....
}
Then in theory it should work.
Full disclosure: i haven't tested it thoroughly yet and only used it with apollo-cache-persist
I ran into this problem too, here is how I solved this issue :
Basic description of the algorithm :
The "key" holds the number of parts your data will be divided by. (Example : key is "MyElementToStore", its value is 7 for the number of parts your data needs to be split by to fit each part in a row of the AsyncStorage)
Each part will then be stored as an individual row in the AsyncStorage by having the name of the key followed by the index of the part. (Example : ["MyElementToStore0", "MyElementToStore1", ...]
Retrieving data works the other way around, each row is retrieved and aggregated to the result to return
Final note for clearing the store, it's important to remove each part before removing the key (use the last function "clearStore" to make sure you release memory correctly)
AsyncStorage documentation
import AsyncStorage from "#react-native-async-storage/async-storage";
const getStore = async (key) =>
{
try
{
let store = "";
let numberOfParts = await AsyncStorage.getItem(key);
if(typeof(numberOfParts) === 'undefined' || numberOfParts === null)
return null;
else
numberOfParts = parseInt(numberOfParts);
for (let i = 0; i < numberOfParts; i++) { store += await AsyncStorage.getItem(key + i); }
if(store === "")
return null;
return JSON.parse(store);
}
catch (error)
{
console.log("Could not get [" + key + "] from store.");
console.log(error);
return null;
}
};
const saveStore = async (key, data) =>
{
try
{
const store = JSON.stringify(data).match(/.{1,1000000}/g);
store.forEach((part, index) => { AsyncStorage.setItem((key + index), part); });
AsyncStorage.setItem(key, ("" + store.length));
}
catch (error)
{
console.log("Could not save store : ");
console.log(error.message);
}
};
const clearStore = async (key) =>
{
try
{
console.log("Clearing store for [" + key + "]");
let numberOfParts = await AsyncStorage.getItem(key);
if(typeof(numberOfParts) !== 'undefined' && numberOfParts !== null)
{
numberOfParts = parseInt(numberOfParts);
for (let i = 0; i < numberOfParts; i++) { AsyncStorage.removeItem(key + i); }
AsyncStorage.removeItem(key);
}
}
catch (error)
{
console.log("Could not clear store : ");
console.log(error.message);
}
};
I found another alternative mentioned here
Just install react-native-fs-store
npm i react-native-fs react-native-fs-store
react-native link react-native-fs
And use it like this:
import Store from "react-native-fs-store";
const AsyncStorage = new Store('store1');
it has has exactly same API as that of AsyncStorage, so no code changes are required
** Please notice that react-native-fs-store is slower than AsyncStorage, as each operation is synced to file. So you may notice lag (unresponsive screen) while reading/writing data
android/app/src/main/java/com/tamotam/mainApp/MainApplication.java
import android.database.CursorWindow;
import java.lang.reflect.Field;
...
#Override
public void onCreate() {
...
try {
Field field = CursorWindow.class.getDeclaredField("sCursorWindowSize");
field.setAccessible(true);
field.set(null, 100 * 1024 * 1024); // the 100MB is the new size
} catch (Exception e) {
e.printStackTrace();
}
}
Fixed the issue for me, remember to include the 2 imports!
As per https://github.com/andpor/react-native-sqlite-storage/issues/364#issuecomment-665800433 there might be an addition check if (DEBUG_MODE)... in some solutions, but it caused Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0. in my case.

Get near Users in Meteor using $near query

I have a mobile app that wants to show near users. Each 30 seconds, I want to update the near users list. In this case, for this feature, I am not using the Meteor real-time sync since I think it's too heavy. I think it's better to ask the list each 30 seconds.
For each User, I have his _id and his mapPosition [lng, lat].
My idea was to perform the $near query on the client side, since the Users list should be already in sync with the server. However I read that geo-query are not supported on the client side by minimongo. So I've created a new method on server side. (I am still not using publish/subscribe technique).
The problem is that I still not get it working.
Example of User document
var user =
{ _id : "000000",
userName : "Daniele",
mapPosition : { type: "Point",
coordinates: [lng, lat] // float
}
}
This is the code on my server side
// collections.js
Users = new Mongo.Collection('users');
Users._ensureIndex({'mapPosition.coordinates':'2dsphere'});
// methods.js
nearUsers(data){
check(data,
{
mapPosition: [Number], // [lng, lat]
userId:String // who is asking
});
return Users.find({
mapPosition: { $near: { $geometry: { type: "Point",
coordinates: data.mapPosition
},
$maxDistance: 5 *1609.34 // 5 miles in meters
}
},
'_id' : {$ne: data.userId}
}
).fetch();
}
this is the code on my client side
var getNearUsers = function()
{
var deferred = $q.defer();
var mapPosition = [parseFloat(GeolocatorService.getAppPosition().lng),
parseFloat(GeolocatorService.getAppPosition().lat)
];
Meteor.call('nearUsers',
{
userId : me.id,
mapPosition : mapPosition
},
function (err, result)
{
if (err)
{
console.error('[getNearUsers] '+err);
deferred.reject(err);
}
else
{
console.log('[getNearUsers] '+JSON.stringify(result.fetch()));
deferred.resolve(result);
}
});
return deferred.promise;
}
// call it each 30 seconds
setInterval ( function() { getNearUsers(); }, 30000);
On the server, I get this error
Exception while invoking method 'nearUsers' MongoError: Unable to execute query: error processing que$
at Object.Future.wait (/home/utente/.meteor/packages/meteor-tool/.1.3.2_2.x9uas0++os.linux.x86_32$
at SynchronousCursor._nextObject (packages/mongo/mongo_driver.js:986:47)
at SynchronousCursor.forEach (packages/mongo/mongo_driver.js:1020:22)
at SynchronousCursor.map (packages/mongo/mongo_driver.js:1030:10)
at SynchronousCursor.fetch (packages/mongo/mongo_driver.js:1054:17)
at Cursor.(anonymous function) [as fetch] (packages/mongo/mongo_driver.js:869:44)
at [object Object].nearUsers (server/methods.js:38:47)
at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1704:12)
at packages/ddp-server/livedata_server.js:711:19
at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
- - - - -
Tree: $and
$not
_id == "570a6aae4bd648880834e621"
lastUpdate $gt 1469447224302.0
GEONEAR field=mapPosition maxdist=8046.7 isNearSphere=0
Sort: {}
Proj: {}
planner returned error: unable to find index for $geoNear query
On the client, I get this error
[Error] Error: [filter:notarray] Expected array but received: {}
http://errors.angularjs.org/1.4.3/filter/notarray?p0=%7B%7D
http://localhost:8100/lib/ionic/js/ionic.bundle.js:13380:32
http://localhost:8100/lib/ionic/js/ionic.bundle.js:31563:31
fn
regularInterceptedExpression#http://localhost:8100/lib/ionic/js/ionic.bundle.js:27539:37
$digest#http://localhost:8100/lib/ionic/js/ionic.bundle.js:28987:43
$apply#http://localhost:8100/lib/ionic/js/ionic.bundle.js:29263:31
tick#http://localhost:8100/lib/ionic/js/ionic.bundle.js:24396:42
(funzione anonima) (ionic.bundle.js:25642)
(funzione anonima) (ionic.bundle.js:22421)
$digest (ionic.bundle.js:29013)
$apply (ionic.bundle.js:29263)
tick (ionic.bundle.js:24396)
I solved deleting the folder myAppDir/.meteor/local/db
and restarting meteor

Resources