AuthorizationCodeInstalledApp - Android Alternative - java

I'm trying to Authenticate into Google Oauth with Android, I successfully authenticate, store my credentials and auth token but then there's one particular piece of code that I am falling over at; returning an instance of AuthorizationCodeInstalledApp. The problem seems to be that this API is made for Java desktop applications and is trying to load a browser instance. Here is my GoogleCredentialsUtilityModule, a slightly refactored version of the code that is shown in the Android developer docs:
import android.content.Context
import android.os.AsyncTask
import com.example.bluelightlite.constants.CREDENTIALS_FILE_PATH
import com.example.bluelightlite.constants.JSON_FACTORY
import com.example.bluelightlite.constants.SCOPES
import com.example.bluelightlite.constants.TOKENS_DIRECTORY_PATH
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.util.store.FileDataStoreFactory
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.InputStreamReader
class GoogleCredentialsUtilityModule constructor(private val context: Context): AsyncTask<NetHttpTransport, Void, Credential>() {
/**
* Starts getting credentials on a different thread by implementing
* AsyncTask<>()
* #param params: a list of parameters
* #return Google Credentials that come from this.getCredentials()
*/
override fun doInBackground(vararg params: NetHttpTransport): Credential {
return this.getCredentials(params[0])
}
/**
* Creates an authorized Credential object.
* #param HTTP_TRANSPORT The network HTTP Transport.
* #return An authorized Credential object.
* #throws java.io.IOException If the credentials.json file cannot be found.
*/
private fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential {
val inputStream: InputStream = getCredentialsAsInputStream()
val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))
createTokenFolderIfMissing()
val authorisationFlow: GoogleAuthorizationCodeFlow = getAuthorisationFlow(HTTP_TRANSPORT, clientSecrets)
val receiver: LocalServerReceiver = LocalServerReceiver.Builder()
.setPort(8888)
.build()
return AuthorizationCodeInstalledApp(authorisationFlow, receiver).authorize("user") //falls over here
}
/**
* Gets the /credentials.json file
* #return InputStream
*/
private fun getCredentialsAsInputStream(): InputStream {
return this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")
}
/**
* Creates the Tokens Folder for Google Authentication
* Uses the current context for the folder path from
* Context.getExternalFilesDir()
*/
private fun createTokenFolderIfMissing() {
val tokenFolder = getTokenFolder()
if (!tokenFolder.exists()) {
tokenFolder.mkdir()
}
}
/**
* gets External storage directory from the
* current context
* #return File
*/
private fun getTokenFolder(): File {
return File(this.context.getExternalFilesDir("")?.absolutePath + TOKENS_DIRECTORY_PATH)
}
/**
* Gets authorisation flow so that the application can authenticate into Google Calendars
* #param HTTP_TRANSPORT allows the app to use HTTP connections
* #param clientSecrets secrets for authentication into Google
* #return GoogleAuthorizationCodeFlow
*/
private fun getAuthorisationFlow(HTTP_TRANSPORT: NetHttpTransport, clientSecrets: GoogleClientSecrets): GoogleAuthorizationCodeFlow {
return GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(FileDataStoreFactory(getTokenFolder()))
.setAccessType("offline")
.build()
}
}
Here is my error message:
02/21 20:04:33: Launching 'app' on Pixel 3 XL API 29.
$ adb shell am start -n "com.example.bluelightlite/com.example.bluelightlite.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 9795 on device 'Pixel_3_XL_API_29 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/RenderThread: type=1400 audit(0.0:48): avc: denied { write } for name="property_service" dev="tmpfs" ino=6831 scontext=u:r:untrusted_app:s0:c133,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 app=com.example.bluelightlite
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/System.err: 2020-02-21 20:04:39.683:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2020-02-21 20:04:39.684:INFO::jetty-0.0
W/System.err: 2020-02-21 20:04:39.805:INFO::Started SocketConnector#localhost:8888
I/System.out: Please open the following address in your browser:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=475059597551-bugt3i0nnfe7unsoqt8ghu2ovm7dfrqg.apps.googleusercontent.com&redirect_uri=http://localhost:8888/Callback&response_type=code&scope=https://www.googleapis.com/auth/calendar.readonly
W/System.err: 2020-02-21 20:04:39.823:INFO::Stopped SocketConnector#localhost:8888
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluelightlite, PID: 9795
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bluelightlite/com.example.bluelightlite.MainActivity}: java.util.concurrent.ExecutionException: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Desktop;
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.util.concurrent.ExecutionException: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Desktop;
at java.util.concurrent.FutureTask.report(FutureTask.java:123)
at java.util.concurrent.FutureTask.get(FutureTask.java:193)
at android.os.AsyncTask.get(AsyncTask.java:602)
at com.example.bluelightlite.models.GoogleCalenderCredentials.<init>(GoogleCalanderCredentials.kt:15)
at com.example.bluelightlite.modules.GoogleCalendarsServiceModule.<init>(GoogleCalendarsServiceModule.kt:11)
at com.example.bluelightlite.MainActivity.onCreate(MainActivity.kt:25)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Desktop;
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.browse(AuthorizationCodeInstalledApp.java:129)
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.onAuthorization(AuthorizationCodeInstalledApp.java:113)
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:81)
at com.example.bluelightlite.modules.GoogleCredentialsUtilityModule.getCredentials(GoogleCredentialsUtilityModule.kt:52)
at com.example.bluelightlite.modules.GoogleCredentialsUtilityModule.doInBackground(GoogleCredentialsUtilityModule.kt:31)
at com.example.bluelightlite.modules.GoogleCredentialsUtilityModule.doInBackground(GoogleCredentialsUtilityModule.kt:22)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.Desktop" on path: DexPathList[[zip file "/data/app/com.example.bluelightlite-6neG3BDx7D1LEKBl_6YMYg==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.bluelightlite-6neG3BDx7D1LEKBl_6YMYg==/lib/x86, /system/lib, /system/product/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.browse(AuthorizationCodeInstalledApp.java:129) 
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.onAuthorization(AuthorizationCodeInstalledApp.java:113) 
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:81) 
at com.example.bluelightlite.modules.GoogleCredentialsUtilityModule.getCredentials(GoogleCredentialsUtilityModule.kt:52) 
at com.example.bluelightlite.modules.GoogleCredentialsUtilityModule.doInBackground(GoogleCredentialsUtilityModule.kt:31) 
at com.example.bluelightlite.modules.GoogleCredentialsUtilityModule.doInBackground(GoogleCredentialsUtilityModule.kt:22) 
at android.os.AsyncTask$3.call(AsyncTask.java:378) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:919) 
I/Process: Sending signal. PID: 9795 SIG: 9
I can't seem to find any alternative to AuthorizationCodeInstalledApp. Any advice? Should I write my own Authentication code? Is there an Android version of AuthorizationCodeInstalledApp that I can use? I'm finding the documentation so vague and hard to read.
Developing on API 29 using a Google Pixel 3 XL.

I copied dnsiv's answer and overridden AuthorizationCodeInstalledApp and I now have the following code:
private fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential {
val inputStream: InputStream = getCredentialsAsInputStream()
val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))
createTokenFolderIfMissing()
val authorisationFlow: GoogleAuthorizationCodeFlow = getAuthorisationFlow(HTTP_TRANSPORT, clientSecrets)
val ab: AuthorizationCodeInstalledApp =
object : AuthorizationCodeInstalledApp(authorisationFlow, LocalServerReceiver()) {
#Throws(IOException::class)
override fun onAuthorization(authorizationUrl: AuthorizationCodeRequestUrl) {
val url = authorizationUrl.build()
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context.startActivity(browserIntent)
}
}
return ab.authorize("user").setAccessToken("user")

Hmm - looks like you are running a loopback web server on port 8888, which is more of a desktop solution than a mobile one.
You are likely to get a more user friendly and reliable solution by logging in via a Chrome Custom Tab and using Google AppAuth libraries. It is not easy though.
Maybe have a look at my Tutorial + Code Sample which may at least give you something to compare against.

Related

Illegal ArgumentException: "No available camera can be found" in CameraProcessProvider.bindToLifecycle for Nexus 6

Issue:
I am getting the following error:
java.lang.IllegalArgumentException: No available camera can be found.
when calling and instance method ProcessCameraProvider.bindToLifecycle(). See this in the context of the code below by searching for "------ Code Crashes Here --------------".
Question:
How do I prevent this error and subsequent crashing of the app? More specifically, how do I ensure the CameraSelector can return a camera instance for the Nexus 6?
Hypothesis
It appears there is something wrong with the CameraSelector used in this call. If I set a breakpoint on the bindToLifecycle line, and debug up to that point and add a watch for `cameraProvider.hasCamera(cameraSelector) it returns false. Maybe this is not intended to return true until the bindToLifecycle method has been called. If so, how can I verify the cameraSelector object has been created sucessfully (successfully meaning it points to an actual camera object)?
In the creation of the cameraSelector object, I use the requireLensFacing method in the builder, so it appears the Nexus 6 hardware does not tag anything with these LENS_FACING_BACK or LENS_FACING_FRONT and therefore does not return any camera instance? Do I understand this correctly?
I should note that this error did not occur when the exact same code was run on a Nexus 5, which is why I am inclined to think it is a hardware issue.
I also tried the LENS_FACING_FRONT int, but had the same error. If I remove the requireLensFacing build component altogether I get a different error:
java.util.NoSuchElementException
Code
package jp.oist.cameraxapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private ExecutorService executor;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
executor = Executors.newSingleThreadExecutor();
PreviewView previewView = findViewById(R.id.previewView);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
// Camera provider is now guaranteed to be available
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
// Set up the view finder use case to display camera preview
Preview preview = new Preview.Builder().build();
// Choose the camera by requiring a lens facing
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
// Connect the preview use case to the previewView
preview.setSurfaceProvider(
previewView.createSurfaceProvider());
// Set up the capture use case to allow users to take photos
ImageCapture imageCapture = new ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.build();
ImageAnalysis imageAnalysis =
new ImageAnalysis.Builder()
.build();
imageAnalysis.setAnalyzer(executor, new ImageAnalysis.Analyzer() {
#Override
public void analyze(#NonNull ImageProxy image) {
int rotationDegrees = image.getImageInfo().getRotationDegrees();
Log.i("CameraXApp3", "Image Analyzed");
image.close();
}
});
// Attach use cases to the camera with the same lifecycle owner
// ------ Code Crashes Here --------------
Camera camera = cameraProvider.bindToLifecycle(
((LifecycleOwner) this),
cameraSelector,
preview,
imageCapture);
} catch (InterruptedException | ExecutionException e) {
// Currently no exceptions thrown. cameraProviderFuture.get() should
// not block since the listener is being called, so no need to
// handle InterruptedException.
}
}, ContextCompat.getMainExecutor(this));
}
}
Full logcat surrounding the IllegalArgumentException
2020-07-29 13:31:57.954 7345-7345/? E/Finsky: [2] VerifyPerSourceInstallationConsentInstallTask.b(2): Package name null is not an installed package
2020-07-29 13:31:59.660 462-877/? E/cutils: Failed to open(/data/misc/profiles/cur/0/jp.oist.cameraxapp/primary.prof): No such file or directory
2020-07-29 13:31:59.660 462-877/? E/installed: Failed to prepare /data/misc/profiles/cur/0/jp.oist.cameraxapp/primary.prof: No such file or directory
2020-07-29 13:31:59.661 729-756/? E/ArtManagerService: Failed to prepare profile for jp.oist.cameraxapp:/data/app/jp.oist.cameraxapp-HSYslGAf7kOyD4tEcVKEkw==/base.apk
2020-07-29 13:32:00.305 462-877/? E/installd: Failed to delete /data/app/vmdl841803495.tmp: No such file or directory
2020-07-29 13:32:00.846 729-729/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/lib/arm, /data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/base.apk!/lib/armeabi-v7a, /system/lib, /system/vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:226)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:338)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5441)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1740)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.server.SystemServer.run(SystemServer.java:500)
at com.android.server.SystemServer.main(SystemServer.java:322)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:839)
2020-07-29 13:32:00.847 729-729/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/lib/arm, /data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/base.apk!/lib/armeabi-v7a, /system/lib, /system/vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:226)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:338)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5441)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1740)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.server.SystemServer.run(SystemServer.java:500)
at com.android.server.SystemServer.main(SystemServer.java:322)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:839)
2020-07-29 13:32:02.251 11105-11105/jp.oist.cameraxapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: jp.oist.cameraxapp, PID: 11105
java.lang.IllegalArgumentException: No available camera can be found.
at androidx.camera.core.CameraSelector.filter(CameraSelector.java:100)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:389)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:275)
at jp.oist.cameraxapp.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:80)
at jp.oist.cameraxapp.-$$Lambda$MainActivity$N0aObN0KVyRMowRsss_pmN8BZ44.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6698)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:859)
2020-07-29 13:32:02.367 2459-9800/ch.deletescape.lawnchair.ci E/pe.lawnchair.c: Failed to open APK '/data/app/jp.oist.cameraxapp-bhz9WJnVll-cJYJKM51yGg==/base.apk' I/O error
2020-07-29 13:32:02.368 2459-9800/ch.deletescape.lawnchair.ci E/ResourcesManager: failed to add asset path /data/app/jp.oist.cameraxapp-bhz9WJnVll-cJYJKM51yGg==/base.apk
Full logcat surrounding the NoSuchElementException
2020-07-29 13:31:22.712 10962-10962/jp.oist.cameraxapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: jp.oist.cameraxapp, PID: 10962
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:759)
at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:780)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:415)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:275)
at jp.oist.cameraxapp.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:79)
at jp.oist.cameraxapp.-$$Lambda$MainActivity$N0aObN0KVyRMowRsss_pmN8BZ44.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6698)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:859)
2020-07-29 13:31:22.758 382-382/? E/lowmemorykiller: Error writing /proc/10962/oom_score_adj; errno=22
Edit1:
Tested standard camera app on the Nexus 6 and found that it also crashed. This pointed to a HAL issue presented by a commenter. Restarted the Nexus 6 in an effort to fix the HAL. Now logcat presents a whole new set of errors, but I will save that for a seperate question if I cannot resolve them on my own.
With both LENS_FACING_FRONT and LENS_FACING_BACK resulting in a no available camera can be found, it seems as though no cameras on the device are available for use, this may be caused at times by a HAL crash, and might require a device reboot for the HAL to function correctly again.
You should check the native camera app (or any other camera app for that matter) to see if they are working on the nexus 6 device. If they aren't, then you'll know the issue is in the camera HAL.

App crashes while parsing data from google sheet

I) Below is code for parsing data async from google sheet and works fine as long as the internet speed is good but crashes on slow speed. How to address this? I have fixed for no internet.
II) If the google sheet is opened for update ( one a row at a time), the system crashes on trying to open. How can I skip the rows which are not assessible ( or updating) ?
III) Is there any way to find time when the google sheet was last updated ?
IV) How to tell google maps not to open the map till the parsing is done?
protected void ReadGoogleSheetAsync(){
new DownloadWebpageTask(new AsyncResult() {
#Override
public void onResult(JSONObject object) {
processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?key=mykey");
}
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
UserData ud = new UserData();
ud.setId(columns.getJSONObject(0).getString("f"));
ud.setName(columns.getJSONObject(1).getString("v"));
ud.setState(columns.getJSONObject(2).getString("v"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
This is based on DownloadWebpageTask.java from git.
Stacktrace:
08/03 06:41:06: Launching 'MapsActivity' on vivo vivo 1902.
$ adb shell am start -n "com.example.fmtxstatus/com.example.fmtxstatus.MapsActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Waiting for process to come online... Connected to process 6659 on device 'vivo-vivo_1902-CIEMU8KRPFLFHEBU'. Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page. D/VivoTheme: load old package name start I/mple.fmtxstatu: The ClassLoaderContext is a special shared library. W/mple.fmtxstatu: JIT profile information will not be recorded: profile file does not exits.
JIT profile information will not be recorded: profile file does not exits. D/NightModeController: com.example.fmtxstatus = true
disable nightmode package:com.example.fmtxstatus I/FtBuild: getRomVersion mRomVer=9.0 D/VivoPhoneWindow: DEBUG_ALIENSCREEN:getRotation mRotation=0 I/PhoneWindow: initSystemUIColor I/zzbz: Making Creator dynamically W/mple.fmtxstatu: Unsupported class loader W/mple.fmtxstatu: Skipping duplicate class check due to unsupported classloader I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:202614000 I/DynamiteModule: Selected remote version of com.google.android.gms.maps_dynamite, version >= 202614000 V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils I/DynamiteLoaderV2: [71] Mapsdynamite W/mple.fmtxstatu: Unsupported class loader W/mple.fmtxstatu: Skipping duplicate class check due to unsupported classloader I/Google Maps Android API: Google Play services client version: 12451000 I/Google Maps Android API: Google Play services package version: 202614029 W/mple.fmtxstatu: Accessing hidden field Ljava/nio/Buffer;->address:J (light greylist, reflection) I/mple.fmtxstatu: The ClassLoaderContext is a special shared library. E/libc: Access denied finding property "persist.vendor.log.tel_dbg" W/com.example.fmtxstatus: type=1400 audit(0.0:118917): avc: denied { read } for comm=4173796E635461736B202332 name="u:object_r:mtk_em_tel_log_prop:s0" dev="tmpfs" ino=6814 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:mtk_em_tel_log_prop:s0 tclass=file permissive=0 D/NetworkSecurityConfig: No Network Security Config specified, using platform default D/OpenGLRenderer: Dumper init 4 threads <0x7a04d12b40> D/OpenGLRenderer: <com.example.fmtxstatus> is running.
Skia GL Pipeline I/SurfaceFactory: [static] sSurfaceFactory = com.mediatek.view.impl.SurfaceFactoryImpl#5b77117 D/ViewRootImpl[MapsActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl#ff0122, this = DecorView#13807b3[MapsActivity] V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl#ff0122, this = DecorView#13807b3[MapsActivity] I/CatcherGestureDetector: DecorView onAttached D/yuan: onVisibilityChanged----com.google.maps.api.android.lib6.impl.ci{2c1c49c G.ED..C.. ......I. 0,0-0,0} D/Surface: Surface::allocateBuffers(this=0x79f461d000) I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0 I/OpenGLRenderer: Initialized EGL, version 1.4 D/OpenGLRenderer: Swap behavior 2 D/Surface: Surface::connect(this=0x79f461d000,api=1) D/TextureView: getHardwareLayer, createNewSurface:true I/BufferQueue: [unnamed-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:-1) BufferQueue core=(6659:com.example.fmtxstatus) W/mple.fmtxstatus: type=1400 audit(0.0:118918): avc: denied { read } for name="u:object_r:graphics_debug_prop:s0" dev="tmpfs" ino=6754 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:graphics_debug_prop:s0 tclass=file permissive=0 E/libc: Access denied finding property "vendor.debug.sf.stc_interval" W/mple.fmtxstatus: type=1400 audit(0.0:118919): avc: denied { read } for name="u:object_r:debug_bq_dump_prop:s0" dev="tmpfs" ino=6713 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:debug_bq_dump_prop:s0 tclass=file permissive=0 E/libc: Access denied finding property "vendor.debug.bq.dump" W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar I/BufferQueueConsumer: [unnamed-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) connect(C): consumer=(6659:com.example.fmtxstatus) controlledByApp=true E/libc: Access denied finding property "vendor.debug.bq.dump" W/mple.fmtxstatus: type=1400 audit(0.0:118920): avc: denied { read } for name="u:object_r:debug_bq_dump_prop:s0" dev="tmpfs" ino=6713 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:debug_bq_dump_prop:s0 tclass=file permissive=0 I/BufferQueueConsumer: [unnamed-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) setConsumerName: unnamed-6659-0 E/libc: Access denied finding property "vendor.debug.bq.line" W/mple.fmtxstatus: type=1400 audit(0.0:118921): avc: denied { read } for name="u:object_r:graphics_debug_prop:s0" dev="tmpfs" ino=6754 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:graphics_debug_prop:s0 tclass=file permissive=0 E/libc: Access denied finding property "vendor.debug.bq.dump" I/BufferQueueConsumer: [SurfaceTexture-0-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) setConsumerName: SurfaceTexture-0-6659-0 W/mple.fmtxstatus: type=1400 audit(0.0:118922): avc: denied { read } for name="u:object_r:debug_bq_dump_prop:s0" dev="tmpfs" ino=6713 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:debug_bq_dump_prop:s0 tclass=file permissive=0 I/System.out: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp I/BufferQueueConsumer: [SurfaceTexture-0-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) setDefaultBufferSize: width=720 height=1404 D/OpenGLRenderer: 0x7a032fb740 setSurfaceTexture: 0x0 to 0x7a032d1800 D/Linux: [Posix_connect Debug]Process com.example.fmtxstatus :443 E/ion: ioctl c0044901 failed with code -1: Invalid argument I/GLConsumer: [SurfaceTexture-0-6659-0] attachToContext D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map. E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
com.example.fmtxstatus W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar I/System.out: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp D/Linux: [Posix_connect Debug]Process com.example.fmtxstatus :443 D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found. I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:5
Selected remote version of com.google.android.gms.googlecertificates, version >= 5 I/DynamiteLoaderV2: [71] Googlecertificates W/mple.fmtxstatu: Unsupported class loader W/mple.fmtxstatu: Skipping duplicate class check due to unsupported classloader I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.
The issue seems to be related to poor handling of HttpURLConnection object. There are issues in the downloadUrl() method implementation in the class DownloadWebpageTask, which may be relevant to the queries 1-3, the variable responseCode is never used.
If the response is not HttpURLConnection.HTTP_OK , try reconnecting ( or till a custom timeout) or return a null string. On slow internet or bad connection, the response will not be HttpURLConnection.HTTP_OK, hence trying to reference the json-object may lead to undefined behavior.
private String downloadUrl(String urlString) throws IOException {
/*...*/
conn.connect();
responseCode = conn.getResponseCode();
if( responseCode == HttpURLConnection.HTTP_OK)
{
// do something
}
else
{
// retry or return null string
}
}
The function processJson(object) in the snippet should be called only if json-object is not null. Issues under queries 1 to 3 should be taken care of with these modifications.
protected void ReadGoogleSheetAsync(){
new DownloadWebpageTask(new AsyncResult() {
#Override
public void onResult(JSONObject object) {
if(object) processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?key=mykey");
}
For query 4 related to google maps api, OnMapReadyCallback is called when the map is ready to be used. Override onMapReady() method to find if the map is ready or not.

Can we use Truecaller SDK if truecaller isnt installed in device

If I try to use the following code, I am able to use Truecaller's SDK and fetch the user's profile if he has truecaller installed.
//has_truecaller = TrueSDK.getInstance().isUsable(); //doesnt work before init() methof
TrueSdkScope trueScope;
TrueSdkScope.Builder sdkBuilder = new TrueSdkScope.Builder(this, sdkCallback)
.consentMode(TrueSdkScope.CONSENT_MODE_POPUP )
.consentTitleOption( TrueSdkScope.SDK_CONSENT_TITLE_VERIFY )
.footerType( TrueSdkScope.FOOTER_TYPE_SKIP );
if(has_truecaller) {
trueScope = sdkBuilder.sdkOptions( TrueSdkScope.SDK_OPTION_WITH_OTP ).build();
}else{
//TODO get mobile number
BaseActivity.USER_MOBILE_NUMBER = "12345677";
trueScope = sdkBuilder.sdkOptions( TrueSdkScope.SDK_OPTION_WITH_OTP ).build();
}
TrueSDK.init(trueScope);
However If i remove Truecaller from the device i get the following error:
2-06 10:38:45.437 25694-25694/com.project.xyz.userclientapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.project.xyz.userclientapp, PID: 25694 java.lang.NoClassDefFoundError:
Failed resolution of: Lretrofit2/converter/gson/GsonConverterFactory;
at com.truecaller.android.sdk.b.c.a(Unknown Source:9)
at com.truecaller.android.sdk.clients.a.<init>(Unknown Source:10)
at com.truecaller.android.sdk.a.<init>(Unknown Source:46)
at com.truecaller.android.sdk.a.a(Unknown Source:2)
at com.truecaller.android.sdk.TrueSDK.init(Unknown Source:5)
at com.project.xyz.userclientapp.login.LoginActivity.setupTrueSdk(LoginActivity.java:49)
at com.project.xyz.userclientapp.login.LoginActivity.onCreate(LoginActivity.java:30)
at android.app.Activity.performCreate(Activity.java:7149)
at android.app.Activity.performCreate(Activity.java:7140)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1288)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3172)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
You can check if the Truecaller app is present on the device or not by using the following line -
TrueSDK.getInstance().isUsable()
You do need to initialize the SDK using the init() method before checking for this. It will return a boolean true / false depending on wether Truecaller is installed or not.
Also, the logs what you shared are because of missing a library dependency in your android project. Can you try add the following dependency in your gradle. This should help solve the error -
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'

AWS SignInProviderResultAdapter.onCognitoError() can create account but crashes on login

I am very new to AWS. I finally got it to work. I used this as my main code:
package elthran.testingaws;
import android.app.Activity;
import android.os.Bundle;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobile.auth.ui.SignInUI;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.mobile.client.AWSStartupHandler;
import com.amazonaws.mobile.client.AWSStartupResult;
import com.amazonaws.regions.Regions;
public class AuthenticatorActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authenticator);
// Add a call to initialize AWSMobileClient
AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
#Override
public void onComplete(AWSStartupResult awsStartupResult) {
SignInUI signin = (SignInUI) AWSMobileClient.getInstance().getClient(
AuthenticatorActivity.this,
SignInUI.class);
signin.login(
AuthenticatorActivity.this,
MainActivity.class).execute();
}
}).execute();
}
}
It opened a basic login window and let me create an account. It registered in the AWS Federated Identities. Then I tried to log in to the app using my new account and I keep getting this error. Can anyone help explain why?
D/AWSRefreshingCognitoIdentityProvider: Storing the Refresh token in the loginsMap.
D/CognitoCachingCredentialsProvider: Identity id is changed
Saving identity id to SharedPreferences
Clearing credentials from SharedPreferences
D/AWSRefreshingCognitoIdentityProvider: Storing the Refresh token in the loginsMap.
D/IdentityManager: SignInProviderResultAdapter.onCognitoError()
com.amazonaws.services.cognitoidentity.model.InvalidIdentityPoolConfigurationException: Invalid identity pool configuration. Check assigned IAM roles for this pool. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidIdentityPoolConfigurationException; Request ID: 4d08f70c-b844-11e8-84be-85774fe09fa3)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:730)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:405)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:566)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getCredentialsForIdentity(AmazonCognitoIdentityClient.java:389)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:782)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:694)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:631)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:514)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getIdentityId(CognitoCachingCredentialsProvider.java:457)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:776)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:694)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:631)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:514)
at com.amazonaws.mobile.auth.core.IdentityManager.refreshCredentialWithLogins(IdentityManager.java:523)
at com.amazonaws.mobile.auth.core.IdentityManager.access$800(IdentityManager.java:77)
at com.amazonaws.mobile.auth.core.IdentityManager$3.run(IdentityManager.java:563)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Signing out...
D/CognitoCachingCredentialsProvider: Clearing credentials from SharedPreferences
E/SignInActivity: Sign-in with Amazon Cognito Your User Pools caused an error.
com.amazonaws.mobile.auth.core.signin.CognitoAuthException: com.amazonaws.services.cognitoidentity.model.InvalidIdentityPoolConfigurationException: Invalid identity pool configuration. Check assigned IAM roles for this pool. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidIdentityPoolConfigurationException; Request ID: 4d08f70c-b844-11e8-84be-85774fe09fa3)
at com.amazonaws.mobile.auth.core.IdentityManager$SignInProviderResultAdapter.onCognitoError(IdentityManager.java:426)
at com.amazonaws.mobile.auth.core.IdentityManager$SignInProviderResultAdapter.access$1000(IdentityManager.java:400)
at com.amazonaws.mobile.auth.core.IdentityManager$3.run(IdentityManager.java:565)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: com.amazonaws.services.cognitoidentity.model.InvalidIdentityPoolConfigurationException: Invalid identity pool configuration. Check assigned IAM roles for this pool. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidIdentityPoolConfigurationException; Request ID: 4d08f70c-b844-11e8-84be-85774fe09fa3)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:730)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:405)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:566)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getCredentialsForIdentity(AmazonCognitoIdentityClient.java:389)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:782)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:694)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:631)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:514)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getIdentityId(CognitoCachingCredentialsProvider.java:457)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:776)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:694)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:631)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:514)
at com.amazonaws.mobile.auth.core.IdentityManager.refreshCredentialWithLogins(IdentityManager.java:523)
at com.amazonaws.mobile.auth.core.IdentityManager.access$800(IdentityManager.java:77)
at com.amazonaws.mobile.auth.core.IdentityManager$3.run(IdentityManager.java:563)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
D/CognitoCachingCredentialsProvider: Identity id is changed
Saving identity id to SharedPreferences
Clearing credentials from SharedPreferences
E/DefaultSignInResultHandler: Sign-in with Amazon Cognito Your User Pools failed.
com.amazonaws.services.cognitoidentity.model.InvalidIdentityPoolConfigurationException: Invalid identity pool configuration. Check assigned IAM roles for this pool. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidIdentityPoolConfigurationException; Request ID: 4d08f70c-b844-11e8-84be-85774fe09fa3)
com.amazonaws.mobile.auth.core.signin.CognitoAuthException: com.amazonaws.services.cognitoidentity.model.InvalidIdentityPoolConfigurationException: Invalid identity pool configuration. Check assigned IAM roles for this pool. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidIdentityPoolConfigurationException; Request ID: 4d08f70c-b844-11e8-84be-85774fe09fa3)
at com.amazonaws.mobile.auth.core.IdentityManager$SignInProviderResultAdapter.onCognitoError(IdentityManager.java:426)
at com.amazonaws.mobile.auth.core.IdentityManager$SignInProviderResultAdapter.access$1000(IdentityManager.java:400)
at com.amazonaws.mobile.auth.core.IdentityManager$3.run(IdentityManager.java:565)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: com.amazonaws.services.cognitoidentity.model.InvalidIdentityPoolConfigurationException: Invalid identity pool configuration. Check assigned IAM roles for this pool. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidIdentityPoolConfigurationException; Request ID: 4d08f70c-b844-11e8-84be-85774fe09fa3)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:730)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:405)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:566)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getCredentialsForIdentity(AmazonCognitoIdentityClient.java:389)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:782)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:694)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:631)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:514)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getIdentityId(CognitoCachingCredentialsProvider.java:457)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:776)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:694)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:631)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:514)
at com.amazonaws.mobile.auth.core.IdentityManager.refreshCredentialWithLogins(IdentityManager.java:523)
at com.amazonaws.mobile.auth.core.IdentityManager.access$800(IdentityManager.java:77)
at com.amazonaws.mobile.auth.core.IdentityManager$3.run(IdentityManager.java:563)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
I have been having nothing but trouble with this. I want login to redirect to my MainActivity which is a simple "hello world" text page, just to make sure I have a working create user and login page. It seems there are so many possible issues and it's very hard for a beginner to read these error logs. Any help would be greatly appreciated.

Android Studio: connecting to MongoDB server with Mongo Java Driver

There's a lot of posts about this problem, but noone seems to work, so maby some things have changed.
I am trying to connect my android application to a MongoDB server located on mLab. I'm using Mongo Java Drived and have off course added the library to android studio.
It is possible to start the app, but when I click on the register button the application craches.
Here's my code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username = (EditText)findViewById(R.id.username);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stringUsername = username.toString();
try {
addToDatabase(stringUsername);
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
private static void addToDatabase(String username){
MongoClientURI uri = new MongoClientURI("mongodb:///*mLab database URL */");
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase(uri.getDatabase());
MongoCollection<Document> coll = db.getCollection("newDB");
Document doc = new Document("username", username);
coll.insertOne(doc);
client.close();
}
}
I also have permision.INTERNET in the manifest file.
Any help would be very appreciated!
//Edit
Stacktrace:
03/10 02:43:09: Launching app
Cold swapped changes.
$ adb shell am start -n "com.newhdc.pedergb.mongodb_servertester/com.newhdc.pedergb.mongodb_servertester.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 4752 on device emulator-5554
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/org.bson.ObjectId: Failed to get process identifier from JMX, using random number instead
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:533)
at org.bson.types.ObjectId.<clinit>(ObjectId.java:491)
at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:105)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory" on path: DexPathList[[dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-support-annotations-25.1.0_11ac1b6ae4b8623fca16868c12f685674e962f99-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_7-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_6-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_5-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_3-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_2-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_1-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_0-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-mongodb-driver-core-3.4.2_cf1ecbf321a58b8bf97e118b2c0ff7614ac982a5-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-mongodb-driver-3.4.2_cfefe7ed281d321e57736b38e1e68fc6160680ac-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-vector-drawable-25.1.0_3dbe341ffa762dac2cc1137bc6aae1731f3bc1c0-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-v4-25.1.0_c534a46cb17b55c593319a94e0d90e0b75103a24-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-media-compat-25.1.0_b58e3876df91b49420cb0766dd6edfdbff0dedbc-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-fragment-25.1.0_d616629f11d994c207dfc4b5d01648e3194bccbc-classes.dex", dex f
I/cluster: Cluster created with settings {hosts=[ds123080.mlab.com:23080], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: **FATAL EXCEPTION**: main
Process: com.newhdc.pedergb.mongodb_servertester, PID: 4752
java.lang.ExceptionInInitializerError
at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41)
at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68)
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:54)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:114)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.security.CodeSource java.security.ProtectionDomain.getCodeSource()' on a null object reference
at com.mongodb.connection.ClientMetadataHelper.getDriverVersion(ClientMetadataHelper.java:111)
at com.mongodb.connection.ClientMetadataHelper.getDriverInformation(ClientMetadataHelper.java:201)
at com.mongodb.connection.ClientMetadataHelper.addDriverInformation(ClientMetadataHelper.java:182)
at com.mongodb.connection.ClientMetadataHelper.<clinit>(ClientMetadataHelper.java:64)
at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41) 
at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68) 
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360) 
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:54) 
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:114) 
at com.mongodb.Mongo.createCluster(Mongo.java:744) 
at com.mongodb.Mongo.createCluster(Mongo.java:728) 
at com.mongodb.Mongo.createCluster(Mongo.java:702) 
at com.mongodb.Mongo.<init>(Mongo.java:310) 
at com.mongodb.Mongo.<init>(Mongo.java:306) 
at com.mongodb.MongoClient.<init>(MongoClient.java:284) 
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39) 
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14) 
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29) 
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Application terminated.
Unfortunately, the Mongo Java Driver does not work on Android, as Android is missing some Java classes, according to this StackOverflow post. However, a kind StackOverflow user has forked the Mongo Java Driver and fixed the issue. You can see their version of the library on Github.
Scroll down to the description and download the latest jar file. Right now, it's this one:
https://github.com/matfur92/mongo-java-driver/blob/gh-pages/JARs/mongo-java-driver-3.4.0-SNAPSHOT.jar?raw=true.
Next, go ahead and delete the line in your build.gradle dependencies for mongo-java-driver. The line to delete should look something like this:
dependencies {
...
compile 'org.mongodb:mongodb-driver:3.4.2'
...
}
Finally, add the jar you downloaded to your application (guide here). Now your code should work without modification. I was able to use regular MongoDB functionality just fine, but I was not able to get GridFS to work.
I had the same issue.
Indeed problem is that you call the connection in the main thread.
add the following to the onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Hope that helps.

Categories

Resources