Xamarin Android Google Places Api AutoComplete broken - xamarin

I'm trying to get the basic autocomplete functionality from Google's Places Api working with Xamarin Android.
I'm using version 25.0.0.0 of Xamarin's Google Play Services - Location lib.
I've managed to get to the point of returning results of a query while following this example code
This is the Fragment I'm using to test the code
public class PlaceAutocomplete: BaseFragment, IGoogleApiClientOnConnectionFailedListener {
IGoogleApiClient client;
public override void OnCreate( Bundle savedInstanceState ) {
base.OnCreate( savedInstanceState );
client = new GoogleApiClientBuilder( Activity )
.EnableAutoManage( Activity as BaseFragmentActivity, 0, this )
.AddOnConnectionFailedListener( OnConnectionFailed )
.AddApi( Places.GEO_DATA_API )
.Build();
}
public override View OnCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
Places.GeoDataApi.GetAutocompletePredictions( client, "cul",
new LatLngBounds( new LatLng( 33.515071, -118.796427 ), new LatLng( 34.435985, -117.127371 ) ), null )
.SetResultCallback<AutocompletePredictionBuffer>( AutocompleteResult );
return base.OnCreateView( inflater, container, savedInstanceState );
}
public void AutocompleteResult( AutocompletePredictionBuffer buffer ) {
if( !buffer.Status.IsSuccess ) {
Toast.MakeText( Activity, buffer.Status.StatusMessage, ToastLength.Long ).Show();
return;
}
var a = new List<IAutocompletePrediction>();
for( var i = 0; i < buffer.Count; i++ ) {
var item = buffer.Get( i );
if( item is IAutocompletePrediction ) {
a.Add( (IAutocompletePrediction) item );
} else {
//all the results go in here
}
}
Toast.MakeText( Activity, a.Count.ToString(), ToastLength.Long ).Show();
}
public void OnConnectionFailed( ConnectionResult result ) {
}
}
There are 5 returned results from GetAutocompletePredictions method but all of them of type named com.google.android.gms.location.places.internal.zzb, cannot be cast to IAutocompletePrediction and I did not find any way to use them.
Did I do something wrong or this part of Xamarin's Google Play library is not fully implemented?

Edit - New Information
This is not a bug. The IAutocompletePrediction is not currently implemented by Xamarin so you must cast it like this
item.JavaCast<IAutocompletePrediction>()
in order to use it.
Older informaton
I've talked to Xamarin Support and they've confirmed that this is a bug.
More info on the bug fix can be found here https://bugzilla.xamarin.com/show_bug.cgi?id=31878

As of
Xamarin 4.0.0.1717 /
Xamarin.Android 6.0.0.35 /
Xamarin Google Play Services Location component v 27.0.0.0
, it seems there's been a bit of work in this space.
The IEnumerable interface now provides a way to get a typed response, and the following snippet (replacing part of AutocompleteResult) works:
var a = new List<IAutocompletePrediction>();
String t = "";
foreach (IAutocompletePrediction x in buffer)
{
a.Add(x);
t += "\n" + x.GetFullTextFormatted(new StyleSpan(TypefaceStyle.Normal)).ToString();
}
Toast.MakeText(Activity, t /* a.Count.ToString() */, ToastLength.Long).Show();

Related

Broadcast Extension with ReplayKit Xamarin iOS not displaying device screen

I created a Xamarin forms project and added Broadcast Upload Extension and Extension UI and reference them into IOS Project also I followed the instructions in the doc here
https://learn.microsoft.com/en-us/xamarin/ios/platform/extensions#container-app-project-requirements
I uses agora for screen sharing but the result is the device share the camera instead of it's screen
I followed this sample
https://github.com/DreamTeamMobile/Xamarin.Agora.Samples/tree/master/ScreenSharing
and added a Dependency service Interface to invoke it from Xamarin forms all is working expect device share it's camera not it's screen
public class AgoraServiceImplementation : IAgoraService
{
private void JoiningCompleted(Foundation.NSString arg1, nuint arg2, nint arg3)
{
_myId = arg2;
_agoraEngine.SetEnableSpeakerphone(true);
JoinChannelSuccess((uint)_myId);
var bundle = NSBundle.MainBundle.GetUrlForResource("ScreenSharingIOSExtension", "appex", "PlugIns");
var frame = new CGRect(100, 100, 60, 60);
var broadcastPicker = new RPSystemBroadcastPickerView(frame);
var bundle2 = new NSBundle(bundle);
broadcastPicker.PreferredExtension = bundle2.BundleIdentifier;
var vc = Platform.GetCurrentUIViewController();
vc.Add(broadcastPicker);
}
public void StartShareScreen(string sessionId, string agoraAPI, string token, VideoAgoraProfile profile = VideoAgoraProfile.Portrait360P, bool swapWidthAndHeight = false, bool webSdkInteroperability = false)
{
_agoraDelegate = new AgoraRtcDelegate(this);
_agoraEngine = AgoraRtcEngineKit.SharedEngineWithAppIdAndDelegate(agoraAPI, _agoraDelegate);
_agoraEngine.EnableWebSdkInteroperability(webSdkInteroperability);
_agoraEngine.SetChannelProfile(ChannelProfile.LiveBroadcasting);
_agoraEngine.SetClientRole(ClientRole.Broadcaster);
//
_agoraEngine.EnableVideo();
if (!string.IsNullOrEmpty(AgoraSettings.Current.EncryptionPhrase))
{
_agoraEngine.SetEncryptionMode(AgoraSettings.Current.EncryptionType.GetModeString());
_agoraEngine.SetEncryptionSecret(helper.AgoraSettings.Current.EncryptionPhrase);
}
_agoraEngine.StartPreview();
Join();
}
private async void Join()
{
var token = await AgoraTokenService.GetRtcToken(helper.AgoraSettings.Current.RoomName);
if (string.IsNullOrEmpty(token))
{
//smth went wrong
}
else
{
_agoraEngine.JoinChannelByToken(token, AgoraSettings.Current.RoomName, null, 0, JoiningCompleted);
}
}
}
any help ?

Sharing targeted xamarin forms

I use the following command to share a link, but with this command opens a box with apps for me to share. I want when I share it already go straight to facebook, without going through this box
void OnTapped4(object sender, EventArgs args)
{
CrossShare.Current.ShareLink(link, "teste", titulo);
}
Need to do direct shares to facebook, whatsapp, twitter and email
I have this command plus it works only on xamarin android, in xamarin forms it would no work
Intent sendIntent = new Intent();
sendIntent.SetAction(Intent.ActionSend);
sendIntent.PutExtra(Intent.ExtraText,"titulo");
sendIntent.SetType("text/plain");
sendIntent.SetPackage("com.facebook.orca");
StartActivity(sendIntent);
I found the following example where I did on android and it worked, now I want to do this in IOS how can I get it to go to whatsapp
Android
public class ShareService : IShareService
{
public void SharePageLink(string url)
{
var context = Forms.Context;
Activity activity = context as Activity;
Intent share = new Intent(Intent.ActionSend);
share.SetType("text/plain");
share.AddFlags(ActivityFlags.ClearWhenTaskReset);
share.PutExtra(Intent.ExtraSubject, "Brusselslife");
share.SetPackage("com.whatsapp");
share.PutExtra(Intent.ExtraText, url);
activity.StartActivity(Intent.CreateChooser(share, "Share link!"));
}
}
In IOS where to put this 'com.whatsapp'
public class ShareService : IShareService
{
public void SharePageLink(string url)
{
var window = UIApplication.SharedApplication.KeyWindow;
var rootViewController = window.RootViewController;
//SetPackage
var activityViewController = new UIActivityViewController(new NSString[] { new NSString(url) }, null);
activityViewController.ExcludedActivityTypes = new NSString[] {
UIActivityType.AirDrop,
UIActivityType.Print,
UIActivityType.Message,
UIActivityType.AssignToContact,
UIActivityType.SaveToCameraRoll,
UIActivityType.AddToReadingList,
UIActivityType.PostToFlickr,
UIActivityType.PostToVimeo,
UIActivityType.PostToTencentWeibo,
UIActivityType.PostToWeibo
};
rootViewController.PresentViewController(activityViewController, true, null);
}
}

How do you allow users to copy and paste from an Xamarin.Forms label

How do you allow users to copy and paste from an Xamarin.Forms Label?
Click on the text on any platform the default settings don't allow highlighting and therefore copying and pasting.
Any help would be appreciated.
What you could do is wrap your label in a gesture recogniser:
<Label Text="Test">
<Label.GestureRecognizers>
<TapGestureRecognizer
Tapped="YourFunctionToHandleMadTaps"
NumberOfTapsRequired="1"
/>
</Label.GestureRecognizers>
</Label>
This will trigger your function and in that function you can get to the clipboard and copy and paste. However I haven't been able to find an easy way to access the clipboard in Xamarin.Forms so you have to use the dependency service.
Xamarin.Forms Dependency service documentation
Here is how I did my clipboard data access. Please note that in my project I only needed to nab data from the clipboard so this code just shows you how to access the clipboard data:
Create an interface in you X.F project eg:
public interface IClipBoard
{
String GetTextFromClipBoard();
}
Implement the interface in your mobile projects:
Android:
public string GetTextFromClipBoard ()
{
var clipboardmanager = (ClipboardManager)Forms.Context.GetSystemService (Context.ClipboardService);
var item = clipboardmanager.PrimaryClip.GetItemAt(0);
var text = item.Text;
return text;
}
iOs:
public string GetTextFromClipBoard ()
{
var pb = UIPasteboard.General.GetValue ("public.utf8-plain-text");
return pb.ToString ();
}
Don't forget to add the Assembly bits at the top:
iOs: [assembly: Dependency (typeof (ClipBoard_iOs))]
Android: [assembly: Dependency (typeof (ClipBoard_Droid))]
Call the dependency service from you X.F function
public void YourFunctionToHandleMadTaps(Object sender, EventArgs ea)
{
var clipboardText = DependencyService.Get<IClipBoard> ().GetTextFromClipBoard ();
YourFunctionToHandleMadTaps.Text = clipboardText;
}
Since I_Khanage provided only a half solution, I will post the full solution.
IClipboardService should be implemented for all the targeting platforms, in my case it is Android and iOS:
public interface IClipboardService
{
string GetTextFromClipboard();
void SendTextToClipboard(string text);
}
// iOS
public class ClipboardService : IClipboardService
{
public string GetTextFromClipboard() => UIPasteboard.General.String;
public void SendTextToClipboard(string text) => UIPasteboard.General.String = text;
}
// Android
public class ClipboardService : IClipboardService
{
public string GetTextFromClipboard()
{
var clipboardmanager = (ClipboardManager)Forms.Context.GetSystemService(Context.ClipboardService);
var item = clipboardmanager.PrimaryClip.GetItemAt(0);
var text = item.Text;
return text;
}
public void SendTextToClipboard(string text)
{
// Get the Clipboard Manager
var clipboardManager = (ClipboardManager)Forms.Context.GetSystemService(Context.ClipboardService);
// Create a new Clip
var clip = ClipData.NewPlainText("YOUR_TITLE_HERE", text);
// Copy the text
clipboardManager.PrimaryClip = clip;
}
}
The code is available on github.
Now just add a GestureRecognizer in order to trigger the tap event.
P.S.: Clipboard service is now available as a part of Xamarin.Essentials package, so there is no need to write one yourself.

Image processing for windows phone

im searching for a good imaging SDK for windows phone ...
i tried to use Nokia SDK but it didn't work for me, it keeps showing as exception:
"Operation Is Not Valid Due To The Current State Of The Object."
here is my test code:
The processImage method is used to apply the filter on the image.
private async void processImage()
{
WriteableBitmap writeableBitmap = new WriteableBitmap((int)bitmapImage.PixelWidth, (int)bitmapImage.PixelHeight);
try
{
using (var imageStream = new StreamImageSource(photoStream))
{
// Applying the custom filter effect to the image stream
using (var customEffect = new NegateFilter(imageStream))
{
// Rendering the resulting image to a WriteableBitmap
using (var renderer = new WriteableBitmapRenderer(customEffect, writeableBitmap))
{
// Applying the WriteableBitmap to our xaml image control
await renderer.RenderAsync();
imageGrid.Source = writeableBitmap;
}
}
}
}
catch (Exception exc) { MessageBox.Show(exc.Message + exc.StackTrace, exc.Source, MessageBoxButton.OK); }
}
This is the NegateFilter class:
namespace ImagingTest
{
class NegateFilter : CustomEffectBase
{
public NegateFilter(IImageProvider source) : base(source){}
protected override void OnProcess(PixelRegion sourcePixelRegion, PixelRegion targetPixelRegion)
{
sourcePixelRegion.ForEachRow((index, width, pos) =>
{
for (int x = 0; x < width; ++x, ++index)
{
targetPixelRegion.ImagePixels[index] = 255 - sourcePixelRegion.ImagePixels[index];
}
});
}
}
}
any ideas for a good imaging SDK? like ImageJ on java for example, or OpenCV ..
i will be better to use Nokia SDK ..
thx :)
I looked in to you code and did a quick test.
The code worked fine when I just made sure that the bitmapImage.PixelWidth and bitmapImage.PixelHeight > 0.
I did not get and image on the screen but when I remove your custom filter the image is show.
I hope you will continue to use the SDK since it is a great product.
What about emguCV?
I am not try it yet but looks like it's possible with phone's camera.

Silently use Microsoft XPS Document Writer printer to create XPS

For some days now I've been battling with printing XPS to file without the dialog.
I've read posts on the matter in CodeGuru and by Feng Yuan (MSDN), along with many discussion topics here and I am still lost.
Specifically my scenario is that I have a 3rd party API that I must use, and it prints to the default printer (say Microsoft XPS Document Writer). I want to be able to "apply" a filename prior to the printing procedure, and of course not to have dialog.
I've tried working with WinDDK - XPSDRV and LOCALMON samples but wasn't able to figure out exactly how to manipulate the code to achieve my goals. (or even fully understand if I need a new printer driver or a new port type)
I ran into the same need. Following is some of the logic that provides the desired functionality for me:
//
// PrintDocument_inst
//
this.PrintDocument_inst.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.k_line_PrintPage);
private void Print( string align_file_name )
{
if ( plot_metafile == null )
{
MessageBox.Show( "you need to load offset data before printing a plot" );
return;
}
try
{
PrintDocument_inst.DefaultPageSettings = PageSettings_inst;
PrintDialog_inst = new PrintDialog( );
PrintDialog_inst.Document = PrintDocument_inst;
PrintDialog_inst.UseEXDialog = true; // this must be set true or dialog won't show on 64 bit Vista
PrintDialog_inst.PrinterSettings.PrinterName = "Microsoft XPS Document Writer";
PrintDialog_inst.PrinterSettings.PrintToFile = true;
PrintDialog_inst.PrinterSettings.PrintFileName = align_file_name;
i_page_to_print_next = 1;
n_pages_still_to_print = 1;
PrintDocument_inst.Print( );
}
catch ( Exception e )
{
MessageBox.Show( e.ToString( ) );
}
finally
{
}
} // end of function Print( string align_file_name )
//PrintPage event handler
private void k_line_PrintPage(object sender,PrintPageEventArgs ppea)
{
int leftMargin = ppea.MarginBounds.Left;
int topMargin = ppea.MarginBounds.Top ;
try
{
float _scale_f;
if ( PrintDialog_inst != null )
{
string str_printer_name = PrintDialog_inst.PrinterSettings.PrinterName.ToString ( );
if ( str_printer_name.CompareTo ( "Adobe PDF" ) == 0 )
{
_scale_f = 0.61F; // 0.85F;
}
else
{
_scale_f = 0.59F; // 0.82F;
}
}
else // case of print preview
{
_scale_f = 0.59F; // 0.82F;
}
if ( _scale_f != 1.0F ) ppea.Graphics.ScaleTransform ( _scale_f, _scale_f );
ppea.Graphics.DrawImage ( plot_metafile, leftMargin, topMargin );
ppea.HasMorePages = ( --n_pages_still_to_print > 0 ? true : false );
}
finally
{
}
} // end of private void k_line_PrintPage(object sender,PrintPageEventArgs ppea)
You will delete filters in pipeline xml and also related dll's in inf file. But yet, as I did, i guess you will face problem of printing canvas (graphics). I wasn't able to convert / transform this canvas to glyphs to get the contents of it.
If you had further issues, let me know
Kind Regards

Resources