fl_chart touch response issue in LineChart - android

I have displayed a Line chart using fl_chart ^0.10.1 (Tested on Flutter ver 52.2.1 & 53.0.1).
I am updating the FlSpots from a csv file.
I am trying to get the index or Spot object if I touch somewhere in the plot.
But I am getting an empty list from the touchResponse if I touch (both tap or long-press) somewhere.
But I am getting the value in the plot itself. I am assuming it's there because of the built-in touch handler.
The code I am trying it:
lineTouchData: LineTouchData(
touchCallback: (LineTouchResponse touchResponse) {
if (touchResponse.touchInput is FlPanEnd ||
touchResponse.touchInput is FlLongPressEnd) {
var spots = touchResponse.lineBarSpots;
setState(() {
var lengthList = spots.length;
print(
'touched spot---> ${spots.toString()},,,len--->$lengthList');
});
} else {
print('wait');
}
}),
My end goal is to use and pass the touched index to open a new screen/widget.

touchCallback: (LineTouchResponse? lineTouch) {
final value = lineTouch.lineBarSpots![0].x;
// set state...
});
It's in the demo by fl_chart in github.
https://github.com/imaNNeoFighT/fl_chart/blob/master/example/lib/line_chart/samples/line_chart_sample3.dart

Related

Xamarin Forms Android: map.Pins.Clear() issue

my development team and I have run into an issue on our Android distribution of our Xamarin project. The issue is as such: The application uses an observable collection of objects and represents these objects in the form of a list view and a map view with pins representing the objects. In the map view, our code is designed to subscribe to a messaging center call that periodically updates the observable collection of objects from our API (other part of project). The issue we are having is that when we call PlotPins method in the messaging center code block, the application should first retrieve the updated list and then access that list to plot pins on the map. Every time an update is received, the application will clear all pins from the map and then replot the pins based on the updated list (inefficient we know, but this is a temporary solution). However, the pins are never updated. Through the use of the debugger we have discovered that once map.Pins.Clear() within PlotPins() is called, the application jumps to the end of the RequestUpdatedListAsync method (which occurs periodically to retrieve the updated list and which triggers the Messaging Center) and then halts.
Our solution works for our GTK build, with the pins being cleared and redrawn on the map as intended, so this seems to be an Android specific issue.
Any help would be appreciated, thank you.
Relevant code located below:
MESSAGING CENTER:
MessagingCenter.Subscribe<object, ObservableCollection<MyObject>>(Application.Current, Constants.ListUpdateContract, (sender, newList) =>
{
//update list
listUpdater.UpdateList(newList);
//call method to plot pins again
PlotPins(map);
});
PLOTPINS:
private void PlotPins(Map map)
{
map.Pins.Clear();
foreach (MyObject in MyObjects)
{
var pin = new Pin
{
Label = MyObject.ID,
Address = "Latitude: " + MyObject.Latitude + " " + "Longitude: " + MyObject.Longitude,
Type = PinType.Place,
Position = new Position(Convert.ToDouble(MyObject.Latitude), Convert.ToDouble(MyObject.Longitude))
};
//event handler for when user clicks on pin's info window
pin.InfoWindowClicked += async (s, args) =>
{
//opens up detail page for pin associated with myObject
await Navigation.PushAsync(new DetailPage(MyObject));
};
map.Pins.Add(pin);
}
}
REQUEST UPDATED LIST ASYNC:
public static async System.Threading.Tasks.Task<bool> RequestUpdatedListAsync()
{
if (!_tokenIsGood)
return false;
var success = false;
var response = new HttpResponseMessage();
try
{
response = await _client.GetAsync(Constants. MyObjectDisplayUrl);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Error requesting updated list.");
System.Diagnostics.Debug.WriteLine(e.Message);
System.Diagnostics.Debug.WriteLine(e.StackTrace);
return success;
}
response.EnsureSuccessStatusCode();
success = true;
var responseBody = await response.Content.ReadAsStringAsync();
// Update list
MyObjects.Clear();
MyObjects = JsonConvert.DeserializeObject<ObservableCollection< MyObject >>(responseBody);
//Alert subscribed ViewModels to update list
MessagingCenter.Send<object, ObservableCollection< MyObject >>(Application.Current, Constants.ListUpdateContract, units);
return success;
}
Since maps.Pins is UI related it has to be run in main UI thread.
MessagingCenter doesnt always publish/subscribe in main threads .
So to fix this issue call the maps.Pins.Clear() in main thread.
Device.BeginInvokeOnMainThread(()=> maps.Pins.Clear());
Credits: #shanranm for mentioning limitation of MessagingCenter for using main threads.

Not able to update Picker.SelectedIndex

I have an odd issue I can't explain the reason for it - maybe someone here can shed some light on it
I have a ticket scanning app in Xamarin Forms currently testing it on android
the interface allows you to:
type an order number and click the check order Button
use the camera scanner to scan which automatically triggers check order
use the barcode scanner to scan which automatically triggers check order
after the check order validation, user has to select the number of tickets from a drop down list and press confrim entry button
what I'm trying to do, is if the seats available on that ticket is just 1 - then automatically trigger confirm entry button functionality
problem that I have is that - some of my logic depends on setting the drop down index in code - for some reason it doesn't update - as seen in the debugger shot here
and this is the second tme I've noticed this today, earlier it was a var I was trying to assign a string and it kept coming up as null - eventually I replaced that code
is this a bug in xamarin ?
code has been simplified:
async void OnCheckOrderButtonClicked(object sender, EventArgs e)
{
await ValidateOrderEntry();
}
private async void scanCameraButton_Clicked(object sender, EventArgs e)
{
messageLabel.Text = string.Empty;
var options = new ZXing.Mobile.MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.QR_CODE,ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13
};
var scanPage = new ZXingScannerPage(options);
scanPage.OnScanResult += (result) =>
{
//stop scan
scanPage.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
//pop the page and get the result
await Navigation.PopAsync();
orderNoEntry.Text = result.Text;
//automatically trigger update
await ValidateOrderEntry();
});
};
await Navigation.PushAsync(scanPage);
}
private async Task ValidateOrderEntry()
{
//...other code....
checkInPicker.Items.Clear();
if (availablTickets == 1)
{
checkInPickerStack.IsVisible = true;
checkInPicker.SelectedIndex = 0;
messageLabel.Text = "Ticket OK! - " + orderNoEntry.Text;
messageLabel.TextColor = Color.Green;
//select the only element
checkInPicker.SelectedIndex = 0;
await PostDoorEntry();
}
//...other code....
}
private async Task PostDoorEntry()
{
int entryCount = checkInPicker.SelectedIndex + 1;
//... more code...
//...post api code..
}
Maybe I'm overlooking something, but you clear all the items a few lines above the one you are pointing out. That means there are no items in your Picker and thus you can't set the SelectedIndex to anything other than -1, simply because there are no items.

Social.localuser.image is always returning null

I am using Unity along with the Google Play Services Plugin for Unity found over here: https://github.com/playgameservices/play-games-plugin-for-unity
I am trying to access the players avatar to be included in a profile pic ingame. The problem is when I try accessing the Texture2D Social.localuser.image, it always returns null. Upon more research it seems that the code uses some kind of AvatarURL to find the image and that is the thing that is null. I used string.IsNullOrEmpty(AvatarURL) to check this. Does anyone know why AvatarURL is null, and/or how I can fix it. If not that, is there any alternative way to accessing the players avatar to use for a profile picture in my game.
Here is the code I used to test this:
PlayGamesPlatform.Activate();
//Authenticate User
Social.localUser.Authenticate((bool success) => {
if(success) {
Debug.Log("Successfully Authenticated");
Textures.profilePic = Sprite.Create(Social.localUser.image, new Rect(0, 0, Social.localUser.image.width, Social.localUser.image.height), new Vector2(0.5f, 0.5f));
SceneManager.LoadScene("Main Menu");
} else {
Debug.Log("Failed to Authenticate User");
SceneManager.LoadScene("ErrorCanNotSignIn");
}
});
The error happens when setting Textures.profilePic (Textures is another class I created that stores textures, and profilePic is a static Sprite variable in it). It says there is a NullReferenceException: Object reference not set to an instance of the object.
Again based on what I've seen, I think the source of the error seems to be the AvatarURL being null, as it causes this code, which I am pretty sure is what loads the image, not to run:
if (!mImageLoading && mImage == null && !string.IsNullOrEmpty(AvatarURL))
{
Debug.Log("Starting to load image: " + AvatarURL);
mImageLoading = true;
PlayGamesHelperObject.RunCoroutine(LoadImage());
}
Also if it's important, I am testing this on an android device.
Question answered by JeanLuc on this SO question
The implementation for Social.localUser.image of the Play Games Unity
Plugin returns always null.
The reason why the image returns null is because it's loaded asynchronously, so you'll need to wait for it.
Furthermore there's a bug where you first need to access Social.localUser.userName.
This code should be working:
Debug.Log(Social.localUser.userName); // you need to access Social.localUser.userName, otherwise the image will always return null
StartCoroutine(KeepCheckingAvatar());
// ...
private IEnumerator KeepCheckingAvatar()
{
float secondsOfTrying = 20;
float secondsPerAttempt = 0.2f;
while (secondsOfTrying > 0)
{
if (Social.localUser.image != null)
{
// Do something with freshly loaded image
break;
}
secondsOfTrying -= secondsPerAttempt;
yield return new WaitForSeconds(secondsPerAttempt);
}
}
Credits:
https://github.com/playgameservices/play-games-plugin-for-unity/issues/1056#issuecomment-212257972

Is calling a script in unityscript slow?

My enemy script is linked to a prefab and being instantiated by my main script.
It kills enemies in a random order (I am jumping on them and some are not dying, not what I want).
(what I am trying to achieve is an enemy to die when I jump on its head and play a death animation.
So from this enemy script I call the other script jump <-- which is linked to my player script and get the jump Boolean value. Could the processing of jump be to slow? I need help
I tried everything)
it works but only on certain enemies any ideas why? Thanks community.
Can anyone help me find a better method?
Could someone help me maybe find if the Players y => an amount to change jump var on the enemy
Just had a perfect run, whats wrong with this its working then not then it is partly working
If I add audio, it doesn't work.
#pragma strict
var enemy : GameObject;
var speed : float = 1.0;
var enemanim : Animator;
var isdying : boolean = false;
private var other : main;
var playerhit: boolean = false;
function Start () {
other = GameObject.FindWithTag("Player").GetComponent("main");
this.transform.position.x = 8.325;
this.transform.position.y = -1.3;
enemanim = GetComponent(Animator);
enemanim.SetFloat("isdead",0);
}
function OnCollisionEnter2D(coll: Collision2D) {
if(coll.gameObject.CompareTag("distroy")){
Destroy(enemy.gameObject);
}
if(coll.gameObject.CompareTag("Player")){
playerhit=true;
}
}
function Update () {
if(other.jumped === true && playerhit==true){ *****the jumped i need
enemanim.SetFloat("isdead",1);
}
}
function FixedUpdate(){
this.transform.Translate(Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0));
this.rigidbody2D.velocity = Vector2(-5,0);
}
if(other.jumped === true && playerhit==true)
Is wrong.
It should be:
if(other.jumped == true && playerhit==true)
All 3 languages used by Unity, C#, UnityScript, and Boo, are compiled into the same IL byte code at the end. However, there are cases where UnityScript has some overhead as Unity does things in the background. One of these is that it does wrapping of access to members of built-in struct-properties like transform.position.
I prefer C#, I think it is better.

iscroll is not working properly for dynamic form in phonegap

I have developed android phonegap app.I have a appended the dynamic form contains 'input' and 'select' in the div.I need to get scrollbar for that div.So i used iScroll.js but its not working properly.While typing in the textbox suddenly scrollbar disappears.This problem occurring often.
Here is my code:
function loaded()
{
var myScroll = new iScroll('wrapper',
{
scrollbarClass: 'myScrollbar',
useTransform: false,
vScroll: true,
onBeforeScrollStart: function (e)
{
var target = e.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
e.preventDefault();
}
});
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', loaded, false);
Please kindly guide me.Thanks in Advance
so a couple of things that will be helpful -
define your myScroll variable outside of your loaded function that way you can access it anywhere.
also after your content has loaded call myScroll.refresh() and have at least a 1ms delay on it. little hack that goes a long way.

Categories

Resources