Xamarin Android, app crashes after selecting account (ADAL/broker) - xamarin.forms

I have been using the ADAL library to authenticate users in my Xamarin Android app for a while and this all works fine. But after enabling Conditional Access in Azure for the backend API, I have to make use of a broker to make this work. I followed all instructions on the ADAL Wiki (https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/leveraging-brokers-on-Android-and-iOS), but still without getting a working situation.
Xamarin Forms
ADAL version: 5.2.4
Below the code I used to authenticate the users:
public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
{
var context = new AuthenticationContext(authority);
var param = new PlatformParameters(CrossCurrentActivity.Current.Activity, true, PromptBehavior.SelectAccount);
if (context.TokenCache.ReadItems().Count() > 0)
context = new AuthenticationContext(context.TokenCache.ReadItems().First().Authority);
try
{
authResult = await context.AcquireTokenAsync(resource, clientId, new Uri(returnUri), param, userId).ConfigureAwait(false);
return authResult;
}
catch
{
return null;
}
}
In the MainActivity I added the following:
protected override void OnResume()
{
base.OnResume();
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.GetAccounts) == (int)Android.Content.PM.Permission.Granted)
{
enablingBrokerSupport();
}
}
private void enablingBrokerSupport()
{
const string WORK_AND_SCHOOL_TYPE = "com.microsoft.workaccount";
var accManager = AccountManager.Get(Application.Context);
Account[] accounts = accManager.GetAccountsByType(WORK_AND_SCHOOL_TYPE);
Intent intent = AccountManager.NewChooseAccountIntent(null, null, new[] { WORK_AND_SCHOOL_TYPE }, null, null, null, null);
CrossCurrentActivity.Current.Activity.StartActivityForResult(intent, 999);
accManager.GetAccountsByType(WORK_AND_SCHOOL_TYPE);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}
After launching the app, it first prompts for the GetAccunts permissions (as expected). After granting the permissions it will show the account picker in which my account is shown. Assuming it is getting the account from the broker, all the necessary code has to be correctly implemented to my understanding.
I can see the following error in the debug console:
[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] System.NullReferenceException: Object reference not set to an instance of an object
[MonoDroid] at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs (System.Int32 requestCode, Android.App.Result resultCode, Android.Content.Intent data) [0x0001c] in <41e5a54c101e43dca8a2f462dab041fa>:0
[MonoDroid] at ADALTest.Droid.MainActivity.OnActivityResult (System.Int32 requestCode, Android.App.Result resultCode, Android.Content.Intent data) [0x00009] in :0
[MonoDroid] at Android.App.Activity.n_OnActivityResult_IILandroid_content_Intent_ (System.IntPtr jnienv, System.IntPtr native__this, System.Int32 requestCode, System.Int32 native_resultCode, System.IntPtr native_data) [0x00014] in :0
[MonoDroid] at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.6(intptr,intptr,int,int,intptr)
[DALTes] JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable
[AndroidRuntime] Shutting down VM
[AndroidRuntime] FATAL EXCEPTION: main
[AndroidRuntime] Process: <my_packageid>, PID: 23545
[AndroidRuntime] android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
[AndroidRuntime] at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs (System.Int32 requestCode, Android.App.Result resultCode, Android.Content.Intent data) [0x0001c] in <41e5a54c101e43dca8a2f462dab041fa>:0
[AndroidRuntime] at ADALTest.Droid.MainActivity.OnActivityResult (System.Int32 requestCode, Android.App.Result resultCode, Android.Content.Intent data) [0x00009] in :0
[AndroidRuntime] at Android.App.Activity.n_OnActivityResult_IILandroid_content_Intent_ (System.IntPtr jnienv, System.IntPtr native__this, System.Int32 requestCode, System.Int32 native_resultCode, System.IntPtr native_data) [0x00014] in :0
[AndroidRuntime] at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.6(intptr,intptr,int,int,intptr)
[AndroidRuntime] at md5b4882cfeb0ca027f9661a63d1a4e24bc.MainActivity.n_onActivityResult(Native Method)
[AndroidRuntime] at md5b4882cfeb0ca027f9661a63d1a4e24bc.MainActivity.onActivityResult(MainActivity.java:65)
[AndroidRuntime] at android.app.Activity.dispatchActivityResult(Activity.java:7762)
[AndroidRuntime] at android.app.ActivityThread.deliverResults(ActivityThread.java:4603)
[AndroidRuntime] at android.app.ActivityThread.handleSendResult(ActivityThread.java:4652)
[AndroidRuntime] at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
[AndroidRuntime] at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
[AndroidRuntime] at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
[AndroidRuntime] at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
[AndroidRuntime] at android.os.Handler.dispatchMessage(Handler.java:106)
[AndroidRuntime] at android.os.Looper.loop(Looper.java:214)
[AndroidRuntime] at android.app.ActivityThread.main(ActivityThread.java:7050)
[AndroidRuntime] at java.lang.reflect.Method.invoke(Native Method)
[AndroidRuntime] at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
[AndroidRuntime] at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Any help is appreciated.

You need to add try[}catch{} to the OnActivityResult and check witch param is null. Because from your logs i see
System.NullReferenceException: Object reference not set to an instance of an object [AndroidRuntime] at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs (System.Int32 requestCode, Android.App.Result resultCode, Android.Content.Intent data)
apparently a mistake in this method
And maybe this will help https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/1000

Related

Xamarin Plugin.Permission. Error on requesting permission

I'm trying to grand permissions to my android application using Plugin.Permissions and Xamarin.Forms
I'm following the provided sample, but I'm getting the following error:
04-10 17:42:09.234 I/MonoDroid(15633): UNHANDLED EXCEPTION:
04-10 17:42:09.234 I/MonoDroid(15633): System.MissingMethodException: Method not found: Android.App.Activity Xamarin.Essentials.Platform.get_CurrentActivity()
04-10 17:42:09.234 I/MonoDroid(15633): at TestApp.Views.MainPage.OnButtonClicked (System.Object sender, System.EventArgs e) [0x000c3] in C:\projects\my\android-projects\TestXamarin\TestXamarinProject\TestApp\TestApp\Views\MainPage.xaml.cs:31
04-10 17:42:09.234 I/MonoDroid(15633): at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
04-10 17:42:09.234 I/MonoDroid(15633): at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in <4ccdb3137d974856b786e1aeebbfbab6>:0
04-10 17:42:09.234 I/MonoDroid(15633): at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <4ccdb3137d974856b786e1aeebbfbab6>:0
04-10 17:42:09.235 I/MonoDroid(15633): at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <4ccdb3137d974856b786e1aeebbfbab6>:0
04-10 17:42:09.235 I/MonoDroid(15633): at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.44(intptr,intptr)
Here is my MainActivity:
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using Plugin.Permissions;
namespace ExoPlayerVU.Droid
{
[Activity(Label = "TestApp", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
I'm requesting the permission on button click from MainPage.xaml.cs:
public async void OnButtonClicked(object sender, EventArgs e)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync<StoragePermission>();
if (status != PermissionStatus.Granted)
{
// The error occurs here
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
{
await DisplayAlert("Access needed", "This application uses storage", "OK");
}
status = await CrossPermissions.Current.RequestPermissionAsync<StoragePermission>();
}
if (status == PermissionStatus.Granted)
{
// my logic
}
else
{
await DisplayAlert("Storage access denied", "Can not continue, try again.", "OK");
}
}
The Plugin.Permissions and Xamarin.Essentials version are the latest. What I'm doing wrong?
Thanks in advance
UPDATE
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.testapp" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="29" />
<application android:label="TestApp.Android"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.WRITE_PROFILE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
UPDATE 2
Also I have the application class:
[Application]
public class DemoApplication : Application
{
// ...
public PlayerApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public PlayerApplication()
{
}
public override void OnCreate()
{
base.OnCreate();
userAgent = Util.GetUserAgent(this, "TestApp");
// Tried to initialize here, but also doesn't work
//CrossCurrentActivity.Current.Init(this);
//Xamarin.Essentials.Platform.Init(this);
}
// ...
}
Xamarin Version: 16.5
Xamarin.Android SDK: 10.2
Nugets:
Xamarin.Forms: 4.4
Xamarin.Essentials: 1.5.2
Please make sure that the version of Xamarin.Essentials is 1.5.2 in all your projects, here is a screenshot:
I use a lower version in xxx.Android project before and get the same exception with you.
I also uploaded a sample project here and you can check it.

Exception while registering to notification hub with userId in Xamarin Forms Android

I am working on a application in while i need to register the user to notification when he is logged in.When I call the registration while logging in I am getting an exception.Below is my code and exception.
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class PushNotificationServiceAndroid : FirebaseInstanceIdService, IPushNotificationService
{
const string TAG = "MyFirebaseIIDService";
NotificationHub hub;
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
NotificationHubConstants.Hub = new NotificationHub(AppConstants.NotificationHubName,
AppConstants.ListenConnectionString, this);
}
public void RegisterToNotificationHub()
{
try
{
LoggingManager.Enter("RegisterToNotificationHub");
var tags = new List<string>() { };
if (Helpers.ApplicationContext.CurrentLoggedInUserId != 0)
{
tags.Add(Helpers.ApplicationContext.CurrentLoggedInUserId.ToString());
}
//NotificationHubConstants.Hub.UnregisterAll(FirebaseInstanceId.Instance.Token);
var regID = NotificationHubConstants.Hub.Register(FirebaseInstanceId.Instance.Token, tags.ToArray());
LoggingManager.Exit("RegisterToNotificationHub");
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
public void UnRegisterFromNotificationHub()
{
try
{
LoggingManager.Enter("UnRegisterFromNotificationHub");
hub = new NotificationHub(AppConstants.NotificationHubName,
AppConstants.ListenConnectionString, this);
hub.UnregisterAll(FirebaseInstanceId.Instance.Token);
LoggingManager.Exit("UnRegisterFromNotificationHub");
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
}
when the app opens OnTokenRefresh() is called.Once the user logged into the app i am calling RegisterToNotificationHub() through dependency service.But while registering into notification hub i.e, at
var regID = NotificationHubConstants.Hub.Register(FirebaseInstanceId.Instance.Token, tags.ToArray());
i am getting the following exception.
Java.Lang.RuntimeException: Exception of type 'Java.Lang.RuntimeException' was thrown.
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <7f42d9b804da4869b3155f4a330679c7>:0
at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <2648c88210c943a888f6191db8d679d6>:0
at Android.Runtime.JNIEnv.CallObjectMethod (System.IntPtr jobject, System.IntPtr jmethod, Android.Runtime.JValue* parms) [0x0000e] in <871a122d80384347bfb5f33e1dee9682>:0
at WindowsAzure.Messaging.NotificationHub.Register (System.String pnsHandle, System.String[] tags) [0x00081] in <15e1a3139a484a5a85c0680e5d11bb86>:0
at BusinessViewChat.Droid.Dependencies.PushNotificationServiceAndroid.RegisterToNotificationHub () [0x00035] in E:\SourceTree\BusinessView\sourcecode\BusinessView\BusinessViewChat\BusinessViewChat.Android\Dependencies\PushNotificationServiceAndroid.cs:46
--- End of managed Java.Lang.RuntimeException stack trace ---
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at android.net.http.AndroidHttpClient.execute(AndroidHttpClient.java:252)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:219)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:178)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:134)
at com.microsoft.windowsazure.messaging.NotificationHub.refreshRegistrationInformation(NotificationHub.java:296)
at com.microsoft.windowsazure.messaging.NotificationHub.registerInternal(NotificationHub.java:390)
at com.microsoft.windowsazure.messaging.NotificationHub.register(NotificationHub.java:143)
at mono.java.lang.RunnableImplementor.n_run(Native Method)
at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Can any one please help me in solving the issue.Thanks in advance.
It must be added to your manifest file under the application tag.
The next:
<uses-library android: name = "org.apache.http.legacy" android: required = "false" />
For more information visit the official documentation
I hope I helped you, Regards
I got this error message because of a space in tags. After removing the space it worked.
Example:
I was using:
tags.Add("mill_id: 1313");
After changing for:
tags.Add("mill_id:1313");
It worked.
Check your tags to see if any character is causing the error.

Akavache or Sqlite is crashing When Calling in OnStart method

When I use the code below in my xamarin.forms project to check if User object exist in akavache cache, I am getting the exception below. the same code or any akavache query works somewhere else but crashes in onStart method only. I believe that I am initializing akavache in constructor already. I tried exact same code using mobile center to query locally (local sqlite) user data and I get the same exception. I think that this should be something to do with the sqlite as both akavache and mobile center uses similar sqlite libraries. Does anybody know why it doesnt work in OnStart method?
public App()
{
Microsoft.Azure.Mobile.MobileCenter.Start("android=key" +
"uwp=key",
typeof(Microsoft.Azure.Mobile.Analytics.Analytics), typeof(Microsoft.Azure.Mobile.Crashes.Crashes));
Akavache.BlobCache.ApplicationName = "myApp";
Akavache.BlobCache.EnsureInitialized();
ServiceLocator.Add<ICloudService, AzureCloudService>();
InitializeComponent();
}
protected async override void OnStart()
{
try
{
var User= await BlobCache.UserAccount.GetObject<User>("User");
if (User != null)
Helpers.Settings.IsLoggedIn = true;
else
Helpers.Settings.IsLoggedIn = false;
}
catch (Exception)
{
Helpers.Settings.IsLoggedIn = false;
}
ShowMainPageOrLoginPage();
}
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): Unhandled Exception:
11-13 02:08:14.761 E/MobileCenterCrashes( 6308):
System.NullReferenceException: Object reference not set to an instance
of an object. 11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Xamarin.Forms.Platform.Android.AppCompat.Platform.LayoutRootPage
(Xamarin.Forms.Page page, System.Int32 width, System.Int32 height)
[0x0000c] in
D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:291
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Xamarin.Forms.Platform.Android.AppCompat.Platform.Xamarin.Forms.Platform.Android.IPlatformLayout.OnLayout
(System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
r, System.Int32 b) [0x00003] in
D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:199
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Xamarin.Forms.Platform.Android.PlatformRenderer.OnLayout
(System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
r, System.Int32 b) [0x0000e] in
D:\agent_work\1\s\Xamarin.Forms.Platform.Android\PlatformRenderer.cs:73
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Android.Views.ViewGroup.n_OnLayout_ZIIII (System.IntPtr jnienv,
System.IntPtr native__this, System.Boolean changed, System.Int32 l,
System.Int32 t, System.Int32 r, System.Int32 b) [0x00008] in
:0
EDIT:
This issue is definetly caused by akavache. Message is really strange. it looks like that akavache has some relation with LayoutRootPage.
See my code above, I get User object from akavache cache and user object defines if I should show Login Page or Main Page. If I move ShowMainPageOrLoginPage();function above akavache call, it works just fine. So it seems that you cant make any query with akavache before the rootlayoutpage - Main page is set or loaded.
I had the same problem once before, for some reason if you initialize using the static method it doesn't work all the time.
Doesn't work
IBlobCache _cache = BlobCache.LocalMachine;
Does Work
IBlobCache _cache = new SQLitePersistentBlobCache(systemPath + "/CacheUtils.db");
If you want to find the systemPath you can use this in either your Android or iOS
systemPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

Xamarin Forms - Sqlite android Oreo runtime.JavaProxyThrowable

I am using Sqlite in a Xamarin Forms Portable project and I successfully run my application on iOS and UWP. On Android, I can run my application on a Android 6.0 emulator but in Android Oreo although app is installed, it crashes on startup. I am facing the following issue.
Issue:
android.runtime.JavaProxyThrowable: at (wrapper managed-to-native)
SQLite.Net.Platform.XamarinAndroid.SQLiteApiAndroidInternal:sqlite3_open_v2
(byte[],intptr&,int,intptr) at
SQLite.Net.Platform.XamarinAndroid.SQLiteApiAndroid.Open
(System.Byte[] filename, SQLite.Net.Interop.IDbHandle& db,
System.Int32 flags, System.IntPtr zvfs) [0x00000] in
<8dbf6ff85082469fb9d4dfaa9eae6b69>:0 at
SQLite.Net.SQLiteConnection..ctor (SQLite.Net.Interop.ISQLitePlatform
sqlitePlatform, System.String databasePath,
SQLite.Net.Interop.SQLiteOpenFlags openFlags, System.Boolean
storeDateTimeAsTicks, SQLite.Net.IBlobSerializer serializer,
System.Collections.Generic.IDictionary2[TKey,TValue] tableMappings,
System.Collections.Generic.IDictionary2[TKey,TValue]
extraTypeMappings, SQLite.Net.IContractResolver resolver) [0x000a2] in
<8f2bb39aeff94a30a8628064be9c7efe>:0 at
SQLite.Net.SQLiteConnectionWithLock..ctor
(SQLite.Net.Interop.ISQLitePlatform sqlitePlatform,
SQLite.Net.SQLiteConnectionString connectionString,
System.Collections.Generic.IDictionary2[TKey,TValue] tableMappings,
System.Collections.Generic.IDictionary2[TKey,TValue]
extraTypeMappings) [0x0002e] in <8f2bb39aeff94a30a8628064be9c7efe>:0
at project.Models.Database+<>c__DisplayClass1_0.<.ctor>b__0 ()
[0x0001d] in <7df232f34ab8474d9153e3809af4eda8>:0 at
SQLite.Net.Async.SQLiteAsyncConnection.GetConnection () [0x00000] in
<563d605f9f014eeeb32fd4a27b4d142e>:0 at
SQLite.Net.Async.SQLiteAsyncConnection+<>c__DisplayClass11_0.b__0
() [0x00006] in <563d605f9f014eeeb32fd4a27b4d142e>:0 at
System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in
:0 at
System.Threading.Tasks.Task.Execute () [0x00010] in
:0 at
mono.java.lang.RunnableImplementor.n_run (Native Method) at
mono.java.lang.RunnableImplementor.run (RunnableImplementor.java:30)
at android.os.Handler.handleCallback (Handler.java:789) at
android.os.Handler.dispatchMessage (Handler.java:98) at
android.os.Looper.loop (Looper.java:164) at
android.app.ActivityThread.main (ActivityThread.java:6541) at
java.lang.reflect.Method.invoke (Native Method) at
com.android.internal.os.Zygote$MethodAndArgsCaller.run
(Zygote.java:240) at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:767)
In order to create the connection:
public Database(string databaseName)
{
var pathToDatabaseFile = DependencyService.Get<Interfaces.ISQLite>().GetLocalPathToFile(databaseName);
var platform = DependencyService.Get<Interfaces.IPlatformProvider>().GetPlatform();
_connection = new SQLiteAsyncConnection(() =>
new SQLiteConnectionWithLock(platform, new SQLiteConnectionString(pathToDatabaseFile, false)));
_connection.CreateTableAsync<SqlitePage>().Wait();
}
In every project GetPlatform and GetLocalPathToFile are implemented:
return new SQLitePlatformAndroid();
and
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), fileName);
The packages I use for Sqlite are:
SQLite.Net.Async-PCL
SQLite.Net.Core-PCL
SQLite.Net-PCL
Any ideas?
You should change to sqlite-net-pcl, since Android 6+, some permission have changed.
https://www.nuget.org/packages/sqlite-net-pcl/
I switched to this PCL, and everything works like a charm.

New Activity from FloatingActionButton

i would launch an activity with a click in a floating action button, but when i click this, I get "Unfortunately, ... has stopped.". please help me!
questo è il codice del bottone di default, and this works
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
When change the code of a snackbar with the code of a new activity, this does not work
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent launchactivity=new Intent (getApplicationContext(),add.class);
startActivity(launchactivity);
}
});
This is my logcat
09-24 21:22:29.009 6353-6353/com.example.fra31.tradebooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fra31.tradebooks, PID: 6353
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fra31.tradebooks/com.example.fra31.tradebooks.add}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2356)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.fra31.tradebooks.add.onCreate(add.java:47)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5289) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115) 
you should try this.
Intent launchactivity = new Intent(MainActivity.this, add.class);
startActivity(launchactivity);
Intent launchactivity=new Intent (MainActivity.this,add.class);
startActivity(launchactivity);
and you should go to androidmanifest.xml and define your activity as this :
<activity android:name=".MainActivity">
</activity>

Resources