Xamarin Plugin.Permission. Error on requesting permission - xamarin.forms

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.

Related

Java.Lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.zza

I'm trying to implement Authenticate with Firebase on Android using a Phone Number by following the Google official documentation on Xamarin Android. But I am getting this error:
Java.Lang.NullPointerException: 'Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.zza(java.lang.String, long, java.util.concurrent.TimeUnit, com.google.firebase.auth.PhoneAuthProvider$OnVerificationStateChangedCallbacks, android.app.Activity, java.util.concurrent.Executor, boolean)' on a null object reference'
I created an Android studio project And I got no error sending sms. I was supposed to publish the app yesterday but I'm stuck here.
Note: I have already a reference to Xamarin.GooglePlayServices.Base, Xamarin.Firebase.Auth:71.1605.0 and I have a code with push notification FCM which is working fine.
Here is my MainActivity.OnCreate code:
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());
Xamarin.FormsMaps.Init(this, savedInstanceState);
FirebaseApp firebaseApp = FirebaseApp.InitializeApp(this);
var firebaseAuthInstance = FirebaseAuth.GetInstance(firebaseApp);
if(firebaseAuthInstance == null)
{
firebaseAuthInstance = new FirebaseAuth(firebaseApp);
}
verificationStateChangedCallbacks = new VerificationStateChangedCallbacks(); //This class is below.
PhoneAuthProvider.Instance.VerifyPhoneNumber("+16505559999", 60, TimeUnit.Seconds, this //The activity, verificationStateChangedCallbacks); // I got the error here
Class VerificationStateChangedCallbacks:
public class VerificationStateChangedCallbacks : OnVerificationStateChangedCallbacks
{
public override void OnVerificationCompleted(PhoneAuthCredential p0)
{
}
public override void OnVerificationFailed(FirebaseException p0)
{
}
public override void OnCodeSent(string p0, ForceResendingToken p1)
{
base.OnCodeSent(p0, p1);
}
}
I just fixed it by changing
PhoneAuthProvider.Instance.VerifyPhoneNumber("+16505559999", 60, TimeUnit.Seconds, this, verificationStateChangedCallbacks);
to
PhoneAuthProvider.GetInstance(firebaseAuthInstance).VerifyPhoneNumber("+16505559999", 60, TimeUnit.Seconds, this, verificationStateChangedCallbacks);
2 days and I didn't think about changing it.
can you check whether "PhoneAuthProvider.Instance" a null object. If yes then please check your file "google-services.json". Normally "FirebaseAuth.GetInstance(firebaseApp)" will not return a null.

Xamarin Android, app crashes after selecting account (ADAL/broker)

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

MessagingCenter is working on WPF but not working on Android

I created this app to answer some questions regarding MessagingCenter, but I am not able to continue the code due to a problem running the application specifically on the Android platform, if you know what may be wrong please help me. Thanks for the support.
I've tried to change some things how Result page to new Result view in messagingcenter subscribe, but i have no idea about what is happen, to me it's like not finding the message in subscribe.
App Link(GitHub)
In ResultView:
public void Registro()
{
MessagingCenter.Subscribe<ResultView>(this, "DisplayAlert", message =>
{
this.DisplayAlert("Alerta de Registro", "Mensagem DisplayAlert com registro Enviada", "Ok");
});
}
In MainPage:
ResultView ResultPage = new ResultView();
private void GoPaginaResultComRegistro(object sender, EventArgs e)
{
ResultPage.Registro();
MessagingCenter.Send<ResultView>(ResultPage, "DisplayAlert");
MessagingCenter.Unsubscribe<ResultView>(ResultPage, "DisplayAlert");
this.Navigation.PushAsync(ResultPage);
}
I wait for DisplayAlert on the other screen when sending the message, but the App simply skips the code inside subscribe.
First in your GoPaginaResultComRegistro() method ,you should send message after PushAsync
private void GoPaginaResultComRegistro(object sender, EventArgs e)
{
ResultPage.Registro();
this.Navigation.PushAsync(ResultPage);
MessagingCenter.Send<ResultView>(ResultPage, "DisplayAlert");
MessagingCenter.Unsubscribe<ResultView>(ResultPage, "DisplayAlert");
}
Second in your ResultView page, call DisplayAlert in the MainThread :
public void Registro()
{
MessagingCenter.Subscribe<ResultView>(this, "DisplayAlert", message =>
{
Device.BeginInvokeOnMainThread( async() =>
{
await DisplayAlert("Alerta de Registro", "Mensage DisplayAlert com registro Enviada", "Ok");
});
});
}
Try this
public void Registro()
{
MessagingCenter.Subscribe<ResultView,string>(this, "DisplayAlert", async (sender,message) =>
{
await DisplayAlert("Alerta de Registro", message, "Ok");
});
}
var mensagem = "teste";
MessagingCenter.Send<ResultView,string>(ResultPage, "DisplayAlert",mensagem);
Here is some example i use in my project
in my PCL MainPage.cs
public MainPage()
{
InitializeComponent();
MessagingCenter.Send<string>("ok", "showBar");
}
in my Native android project MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
MessagingCenter.Subscribe<string>(this, "showBar", (sender) =>
{
this.Window.ClearFlags(WindowManagerFlags.Fullscreen);
});
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
this.Window.AddFlags(WindowManagerFlags.Fullscreen);
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
you don't need to create new instance of your page to send as parameter.

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.

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