What is it exactly? Error: vendor.camera.aux.packagelist - android-camerax

Currently trying out the new CameraX. Anyone know what's the problem. I should have all the permissions needed.
Here is my entire logcat.
2019-12-08 03:57:56.716 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:56.717 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:56.717 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:56.717 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:56.718 11667-11696/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:56.718 11667-11696/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:56.759 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.192 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.215 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.239 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.242 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.542 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.552 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.556 11667-11667/com.example.camerax E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
2019-12-08 03:57:57.557 11667-11667/com.example.camerax E/libc: Access denied finding property "vendor.camera.aux.packagelist"
2019-12-08 03:57:57.585 11667-11708/com.example.camerax E/libc: Access denied finding property "persist.vendor.camera.privapp.list"
2019-12-08 03:57:57.891 11667-11708/com.example.camerax E/Camera: Unable to open camera 0 due to CAMERA_DISABLED (1): validateClientPermissionsLocked:928: Caller "com.example.camerax" (PID 10280, UID 11667) cannot open camera "0" from background
2019-12-08 03:57:57.899 11667-11708/com.example.camerax E/Camera: CameraDevice.onError(): 0 with error: ERROR_CAMERA_DISABLED
2019-12-08 03:57:57.901 11667-11708/com.example.camerax E/AndroidRuntime: FATAL EXCEPTION: CameraX-
Process: com.example.camerax, PID: 11667
java.lang.IllegalStateException: onError() should not be possible from state: INITIALIZED
at androidx.camera.camera2.impl.Camera$StateCallback.onError(Camera.java:850)
at androidx.camera.core.CameraDeviceStateCallbacks$ComboDeviceStateCallback.onError(CameraDeviceStateCallbacks.java:120)
at android.hardware.camera2.impl.CameraDeviceImpl$8.run(CameraDeviceImpl.java:355)
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.os.HandlerThread.run(HandlerThread.java:65)
It clearly tries a lot, then gives up.
Given the complete lack of posts both here and on Google about it, I'm going to give you all my code.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.camerax">
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.camerax"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
def camerax_version = "1.0.0-alpha01"
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
package com.example.login3;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import android.content.pm.PackageManager;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.util.Rational;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
/**
* A simple {#link Fragment} subclass.
*/
public class FeedFragment extends Fragment {
public FeedFragment() {
// Required empty public constructor
}
private int REQUEST_CODE_PERMISSIONS = 10; //arbitrary number, can be changed accordingly
private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA","android.permission.WRITE_EXTERNAL_STORAGE"}; //array w/ permissions from manifest
private TextureView txView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_feed, container, false);
txView = v.findViewById(R.id.view_finder);
if(allPermissionsGranted()){
startCamera(); //start camera if permission has been granted by user
} else{
ActivityCompat.requestPermissions(getActivity(), REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
return v;
}
private void startCamera() {
//make sure there isn't another camera instance running before starting
CameraX.unbindAll();
/* start preview */
int aspRatioW = txView.getWidth(); //get width of screen
int aspRatioH = txView.getHeight(); //get height
Rational asp = new Rational (aspRatioW, aspRatioH); //aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //size of the screen
//config obj for preview/viewfinder thingy.
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview preview = new Preview(pConfig); //lets build it
preview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//to update the surface texture we have to destroy it first, then re-add it
#Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView);
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture());
updateTransform();
}
});
/* image capture */
//config obj, selected capture mode
ImageCaptureConfig imgCapConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
.setTargetRotation(getActivity().getWindowManager().getDefaultDisplay().getRotation()).build();
final ImageCapture imgCap = new ImageCapture(imgCapConfig);
getActivity().findViewById(R.id.capture_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + ".jpg");
imgCap.takePicture(file, new ImageCapture.OnImageSavedListener() {
#Override
public void onImageSaved(#NonNull File file) {
String msg = "Photo capture succeeded: " + file.getAbsolutePath();
Toast.makeText(getActivity(), msg,Toast.LENGTH_LONG).show();
}
#Override
public void onError(#NonNull ImageCapture.UseCaseError useCaseError, #NonNull String message, #Nullable Throwable cause) {
String msg = "Photo capture failed: " + message;
Toast.makeText(getActivity(), msg,Toast.LENGTH_LONG).show();
if(cause != null){
cause.printStackTrace();
}
}
});
}
});
//bind to lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgCap, preview);
}
private void updateTransform(){
/*
* compensates the changes in orientation for the viewfinder, bc the rest of the layout stays in portrait mode.
* methinks :thonk:
* imgCap does this already, this class can be commented out or be used to optimise the preview
*/
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
float centreX = w / 2f; //calc centre of the viewfinder
float centreY = h / 2f;
int rotationDgr;
int rotation = (int)txView.getRotation(); //cast to int bc switches don't like floats
switch(rotation){ //correct output to account for display rotation
case Surface.ROTATION_0:
rotationDgr = 0;
break;
case Surface.ROTATION_90:
rotationDgr = 90;
break;
case Surface.ROTATION_180:
rotationDgr = 180;
break;
case Surface.ROTATION_270:
rotationDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotationDgr, centreX, centreY);
txView.setTransform(mx); //apply transformations to textureview
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//start camera when permissions have been granted otherwise exit app
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(getActivity(), "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
private boolean allPermissionsGranted(){
//check if req permissions have been granted
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
}
I even tried implementing the code from: https://stackoverflow.com/a/56806751/12253594 but that didn't work.
Best regards.

Look at this answer.
For privacy and security, the camera is not allowed to run in the background

Related

Does startActivityForResult() not work when initiated from launching a specific activity?

In my launch options, I'm launching a specific activity in this case it's called "DailyActivity.java".
In that class, I have an OnClicklistener for a button that should open up a camera intent to take a picture and then perform text extraction on it.
fab_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "myimage.jpg");
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent camintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camintent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(camintent, 101); }});
And here is the onActivityResult that should run after startActivityForResult executes
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri image2 = data.getData();
InputImage image = null;
try {
image = InputImage.fromFilePath(this, image2);
TextRecognizer recognizer = TextRecognition.getClient();
When I click my button, my app crashes. I'm currently in the process of debugging and was wondering if it could be because I've launched from a specific activity initially? Would this affect future testing if I want the camera button to later redirect me to another activity(3rd one from the text extraction)?
This is the error I see in logcat when I click the button
2020-12-04 23:19:54.986 25037-25064/com.example.smartcalendar E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
2020-12-04 23:19:59.633 25037-25037/com.example.smartcalendar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.smartcalendar, PID: 25037
java.lang.SecurityException: Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=25037, uid=10087 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()
at android.os.Parcel.createException(Parcel.java:1950)
at android.os.Parcel.readException(Parcel.java:1918)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:476)
at android.content.ContentResolver.insert(ContentResolver.java:1587)
at com.example.smartcalendar.DailyActivity$2.onClick(DailyActivity.java:128)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
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:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Here are permissions from my Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On android 6 or above you have to check for permission in the runtime before opening the camera intent. Here's how you do it:
fab_camera.setOnClickListener{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED
) {
// Permission was not granted
// Ask for runtime permission
val permissions = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
requestPermissions(
permissions,
PERMISSION_CODE
)
} else {
// Permission already granted
openCamera()
}
} else {
// System OS < Marshmallow
openCamera()
}
}

How to get location using Geolocator in Android Studio?

code that has been used.
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _LoadingScreenState();
}
}
class _LoadingScreenState extends State<LoadingScreen> {
#override
void initState() {
super.initState();
getLocation();
}
void getLocation() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
print(position);
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
Output:
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Waiting for AOSP on IA Emulator to report its views...
Debug service listening on ws://127.0.0.1:51964/UEmjv7haU5w=/ws
Syncing files to device AOSP on IA Emulator...
I/Choreographer(14504): Skipped 116 frames! The application may be doing too much work on its main thread.
D/EGL_emulation(14504): eglMakeCurrent: 0xe8804b00: ver 3 1 (tinfo 0xea15ec70)
D/eglCodecCommon(14504): setVertexArrayObject: set vao to 0 (0) 1 2
I/OpenGLRenderer(14504): Davey! duration=2865ms; Flags=1, IntendedVsync=25791957327046, Vsync=25793890660302, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=25793896676340, AnimationStart=25793898368240, PerformTraversalsStart=25793934314440, DrawStart=25794433733640, SyncQueued=25794660799440, SyncStart=25794663501440, IssueDrawCommandsStart=25794663679640, SwapBuffers=25794747224740, FrameCompleted=25794825369240, DequeueBufferDuration=32086000, QueueBufferDuration=859000,
D/EGL_emulation(14504): eglMakeCurrent: 0xe88045c0: ver 3 1 (tinfo 0xea15e5e0)
D/eglCodecCommon(14504): setVertexArrayObject: set vao to 0 (0) 1 0
I/flutter (14504): The location service on the device is disabled.
Your output says "The location service on the device is disabled" so may you should check the permission in the manifest file. I suggest you to use the coarse and fine permissions together.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
But you should make a previous verification of the location service too before do geolocation-requests.
you should chechk if the service is enabled:
bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled();
print('location enabled: $isLocationServiceEnabled');
then check if the app has permissions:
LocationPermission permission = await Geolocator.checkPermission();
print(permission);
if you don't have permissions ask for them:
LocationPermission permission = await Geolocator.requestPermission();
print(permission);
with all that set up you can make a secure request
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
print(position);
You can use the codes :
var geolocator = Geolocator();
var locationOptions;
getPermission() async {
return Geolocator().checkGeolocationPermissionStatus();
}
then call this function in initState() :
getPermission().then((res) {
locationOptions =
LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
});
geolocator.getPositionStream(locationOptions).listen((Position position) {
setState(() {
lat = position.latitude.toDouble();
long = position.longitude.toDouble();
});
});

TarsosDSP in Android Studio

This is my first post on SO and I am trying to combine my music skills with computer science.
I am using Android studio 3.1.2 with gradle 4.5, Nexus 5X, API 25, Android 7.1.1, Windows 7.
I followed very careful these instructions:
Create a project called Pitchbender
Download the .jar of TarsosDSP and included in
C:\Users\Carlos\AndroidStudioProjects\Pitchbender\app\libs\TarsosDSP-Android-latest
I checked the build.gradle of my project:
dependencies { implementation fileTree(dir: ‘libs’, include: [‘*.jar’]) }
In my project, I have the following imports automatically done by Android Studio:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import be.tarsos.dsp.AudioEvent
import be.tarsos.dsp.io.android.AudioDispatcherFactory
import be.tarsos.dsp.pitch.PitchDetectionHandler
import be.tarsos.dsp.pitch.PitchDetectionResult
import be.tarsos.dsp.pitch.PitchProcessor
import kotlinx.android.synthetic.main.activity_main.*
import be.tarsos.dsp.pitch.PitchProcessor.PitchEstimationAlgorithm
import be.tarsos.dsp.AudioProcessor
import android.widget.TextView
import be.tarsos.dsp.AudioDispatcher
I have this permission in my manifest file
uses-permission android:name=”android.permission.RECORD_AUDIO”
Android Studio gives the option to convert to Kotlin the first line of the following code:
AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
If I respond to “No” to the Kotlin conversion, I have the following compilation error:
Clasifier “AudioDispatcher” does not have any companion object, and thus must be initialized here.
What can I do?
If I respond “Yes” to the Kotlin conversion question, that statement is converted to
val dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0)
and then, when I run this program, Android informs me that there is an error and closes my project and keeps closing my project. What to do?
Please help to run at least that first instruction of the complete code:
PitchDetectionHandler pdh = new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult res, AudioEvent e){
final float pitchInHz = res.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
processPitch(pitchInHz);
}
});
}
};
AudioProcessor pitchProcessor = new PitchProcessor(PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, pdh);
dispatcher.addAudioProcessor(pitchProcessor);
Thread audioThread = new Thread(dispatcher, "Audio Thread");
audioThread.start();
Question:
Do you have any simple project in Android Studio, so that I can see what my errors are?
I had a similar problem when I tried to run this example and my solution (Sep. 2019) was to add a runtime confirmation of the record permission. I'm not sure if it's the same case, buuuut
Here is my code to it:
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}

Google Map crash at specific location and zoom level 15

Google Map crashes with zoom level 15 at specific location (35.670, 139.760) on Android 8 (API level 26).
No crash with other zoom levels (say: 1,2,10, or 14 etc.)
When crash, the Logcat output is:
E/AndroidRuntime: FATAL EXCEPTION: GLThread 279
Process: test.map, PID: 5690
java.lang.StackOverflowError: stack size 1038KB
at java.util.Collections$UnmodifiableList.<init>(Collections.java:1344)
at java.util.Collections$UnmodifiableRandomAccessList.<init>(Collections.java:1437)
at java.util.Collections.unmodifiableList(Collections.java:1330)
at com.google.maps.api.android.lib6.common.g.<init>(:com.google.android.gms.DynamiteModulesB#11951470:9)
at com.google.maps.api.android.lib6.gmm6.indoor.o.b(:com.google.android.gms.DynamiteModulesB#11951470:142)
at com.google.maps.api.android.lib6.gmm6.indoor.o.c(:com.google.android.gms.DynamiteModulesB#11951470:144)
at com.google.maps.api.android.lib6.gmm6.indoor.o.e(:com.google.android.gms.DynamiteModulesB#11951470:286)
at com.google.maps.api.android.lib6.gmm6.indoor.o.d(:com.google.android.gms.DynamiteModulesB#11951470:182)
at com.google.maps.api.android.lib6.gmm6.indoor.o.a(:com.google.android.gms.DynamiteModulesB#11951470:180)
at com.google.maps.api.android.lib6.gmm6.indoor.o.a(:com.google.android.gms.DynamiteModulesB#11951470:82)
at com.google.maps.api.android.lib6.gmm6.indoor.o.a(:com.google.android.gms.DynamiteModulesB#11951470:70)
at com.google.maps.api.android.lib6.gmm6.indoor.o.c(:com.google.android.gms.DynamiteModulesB#11951470:147)
at com.google.maps.api.android.lib6.gmm6.indoor.o.e(:com.google.android.gms.DynamiteModulesB#11951470:286)
at com.google.maps.api.android.lib6.gmm6.indoor.o.d(:com.google.android.gms.DynamiteModulesB#11951470:182)
at com.google.maps.api.android.lib6.gmm6.indoor.o.a(:com.google.android.gms.DynamiteModulesB#11951470:180)
at com.google.maps.api.android.lib6.gmm6.indoor.o.a(:com.google.android.gms.DynamiteModulesB#11951470:82)
at com.google.maps.api.android.lib6.gmm6.indoor.o.a(:com.google.android.gms.DynamiteModulesB#11951470:70)
at com.google.maps.api.android.lib6.gmm6.indoor.o.c(:com.google.android.gms.DynamiteModulesB#11951470:147)
at com.google.maps.api.android.lib6.gmm6.indoor.o.e(:com.google.android.gms.DynamiteModulesB#11951470:286)
at com.google.maps.api.android.lib6.gmm6.indoor.o.d(:com.google.android.gms.DynamiteModulesB#11951470:182)
......
It's very easy to reproduce by running the following code in Nexus5X Android 8 emulator
package test.map;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(ll);
//
MapView mapView = new MapView(this);
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final GoogleMap googleMap) {
final LatLng latLng = new LatLng(35.670, 139.760);
final CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 15.0f);
googleMap.moveCamera(update);
}
});
ll.addView(mapView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
}
}
This is a long standing bug in Google Maps SDK, see https://issuetracker.google.com/issues/35829548
You can the issue this by disabling indoor maps:
#Override public void onMapReady(GoogleMap googleMap) {
googleMap.setIndoorEnabled(false);
}
Question is also a duplicate of Is there a workaround/fix to these Google Maps v2 StackOverflowError crashes?

Tomcat #Resource annotations API annotation stops working in Tomcat 7

I have been using Tomcat 6.0.26-6.0.35 for several years with JSF 2 Mojarra, various versions up to 2.1.2 which I have been using for some months. I have several request-scoped and session-scoped beans with code like this:
private #Resource(name="jdbc/cLabs", mappedName="jdbc/cLabs") DataSource cLabs;
which has been correctly injected in every version of Tomcat 6 I've used. I also have other types of #Resource that doesn't work either, so it isn't just DataSource resources. I've tried switching to Tomcat 7.0.27 and suddenly none of these constructs works any more. The resource is not injected. I also have other types of #Resource that doesn't work either, so it isn't just DataSource resources. However in each case the resource named does exist, and can be looked up via e.g.
new InitialContext().lookup("java:comp/env/jdbc/cLabs");
[They are defined by elements in context.xml]
This of course is a royal PITA as I spent some time a year or two ago replacing the latter with the former. Is there some other magic spell I have to weave with Tomcat 7 to make it work again?
Note that resources are injected correctly into Servlets, so it isn't completely broken. Some interaction between Tomcat and JSF.
My guess is something is causing org.apache.catalina.core.DefaultInstanceManager to ignore annotations because faces requires the #PostConstruct method to be processed apart from #Resource fields. I have created a workaround that works for fields annotated with #Resource.
Add the following to web.xml:
<context-param>
<param-name>com.sun.faces.injectionProvider</param-name>
<param-value>com.example.faces.Tomcat7InjectionProvider</param-value>
</context-param>
And add the class to your source:
package com.example.faces;
import java.lang.reflect.Field;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import org.apache.catalina.util.Introspection;
import com.sun.faces.spi.InjectionProviderException;
import com.sun.faces.vendor.WebContainerInjectionProvider;
public class Tomcat7InjectionProvider extends WebContainerInjectionProvider {
public Tomcat7InjectionProvider(ServletContext servletContext) {
}
#Override
public void inject(Object managedBean) throws InjectionProviderException {
if (managedBean != null) {
// see org.apache.catalina.core.DefaultInstanceManager
Field[] fields = Introspection.getDeclaredFields(managedBean.getClass());
for (Field field : fields) {
// field may be private
field.setAccessible(true);
if (field.isAnnotationPresent(Resource.class)) {
Resource annotation = null;
try {
annotation = field.getAnnotation(Resource.class);
Context ctx = new InitialContext();
Object resource = ctx.lookup("java:comp/env/" + annotation.name());
field.set(managedBean, resource);
} catch (Exception e) {
throw new InjectionProviderException("cannot find resource " + annotation.name(), e);
}
}
}
}
}
}
Answering my own question, an improved version of #JeffE's answer. The basic problem is:
A Tomcat6InjectionProvider was provided with JSF 2.0 but was removed at some point.
The default WebContainerInjectionProvider doesn't process #Resource annotations, as JeffE points out.
You can overcome this without web.xml context-entries as follows:
Create a file called META-INF/services/com.sun.faces.spi.injectionprovider and add the following line to it:
com.sun.faces.vendor.Tomcat7InjectionProvider:org.apache.catalina.core.DefaultInstanceManager
The meaning of this line is that if the second class is present in the deployment, the first class is used as the injection provider. The second class above is part of Tomcat 7.
Compile the following class.
This version contains numerous improvements over JeffE's version. Specifically:
it processes superclasses, as required by the #Resource and #Resources Javadoc
it processes #Resource and #Resources annotations at the class level
it processes methods annotated with #Resource, as required by the #Resource Javadoc
it handles empty or missing name attributes of #Resources correctly, as required by the #Resource Javadoc
it restores the Field's original access
it has no dependencies on Tomcat classes.
Adjust the package name above if you change its package name.
package com.sun.faces.vendor;
import com.sun.faces.spi.DiscoverableInjectionProvider;
import com.sun.faces.spi.InjectionProviderException;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
/**
* #author Jeff E
* #author Esmond Pitt Improvements named above.
*
* #see javax.annotation.Resource
*
* #see <a href="http://stackoverflow.com/a/21978577/207421">This StackOverflow
* answer, although what org.apache.catalina.util.Introspection may be and where
* it lives remains a mystery.</a>
*/
public class Tomcat7InjectionProvider
extends DiscoverableInjectionProvider
{
private Logger logger = Logger.getLogger(this.getClass().getName());
private ServletContext servletContext;
private WebContainerInjectionProvider delegate = new WebContainerInjectionProvider();
public Tomcat7InjectionProvider(ServletContext servletContext)
{
logger.config("constructed");
this.servletContext = servletContext;
}
#Override
public void inject(Object managedBean) throws InjectionProviderException
{
logger.log(Level.CONFIG, "managedBean={0}", new Object[]{managedBean.getClass().getName()});
Class<?> clazz = managedBean.getClass();
do
{
List<Resource> classResources = new LinkedList<>();
// Process class-level #Resources and #Resource
if (clazz.isAnnotationPresent(Resources.class))
{
Resources annotation = clazz.getAnnotation(Resources.class);
for (Resource resource : annotation.value())
{
classResources.add(resource);
}
}
if (clazz.isAnnotationPresent(Resource.class))
{
Resource annotation = clazz.getAnnotation(Resource.class);
classResources.add(annotation);
}
for (Resource annotation : classResources)
{
String name = annotation.name();
// Make sure the resource exists.
try
{
Context ctx = new InitialContext();
Object resource = ctx.lookup("java:comp/env/" + name);
}
catch (NamingException exc)
{
throw new InjectionProviderException("checking class resource " + annotation.name()+" of "+clazz.getName(), exc);
}
}
// Process fields with #Resource
// see org.apache.catalina.core.DefaultInstanceManager
// Field[] fields = Introspection.getDeclaredFields(managedBean.getClass());
Field[] fields = managedBean.getClass().getDeclaredFields();
for (Field field : fields)
{
if (field.isAnnotationPresent(Resource.class))
{
Resource annotation = field.getAnnotation(Resource.class);
String name = annotation.name();
logger.log(Level.CONFIG, "injecting #Resource(name=\"{2}\") into {0}.{1}", new Object[]
{
managedBean.getClass().getName(), field.getName(), name
});
try
{
Context ctx = new InitialContext();
Object resource;
if (name != null && name.length() > 0)
{
resource = ctx.lookup("java:comp/env/" + name);
}
else
{
resource = ctx.lookup(clazz.getName() + "/" + field.getName());
}
// field may be private
boolean accessibility = field.isAccessible();
try
{
field.setAccessible(true);
field.set(managedBean, resource);
}
finally
{
field.setAccessible(accessibility);
}
}
catch (NamingException | IllegalAccessException exc)
{
throw new InjectionProviderException("injecting resource " + annotation.name()+" into "+clazz.getName()+"."+field.getName(), exc);
}
}
}
// Process methods with #Resource
for (Method method : clazz.getDeclaredMethods())
{
if (method.isAnnotationPresent(Resource.class)
&& method.getName().startsWith("set")
&& method.getName().length() > 3
&& method.getReturnType() == void.class
&& method.getParameterTypes().length == 1)
{
// It's a setter with #Resource
Resource annotation = method.getAnnotation(Resource.class);
String name = annotation.name();
logger.log(Level.CONFIG, "injecting #Resource(name=\"{2}\") via {0}.{1}", new Object[]
{
managedBean.getClass().getName(), method.getName(), name
});
try
{
Context ctx = new InitialContext();
Object resource;
if (name != null && name.length() > 0)
{
resource = ctx.lookup("java:comp/env/" + name);
}
else
{
name = method.getName().substring(3);
name = name.substring(0,1).toLowerCase()+name.substring(1);
resource = ctx.lookup(clazz.getName() + "/" + name);
}
// method may be private
boolean accessibility = method.isAccessible();
try
{
method.setAccessible(true);
method.invoke(managedBean, resource);
}
finally
{
method.setAccessible(accessibility);
}
}
catch (NamingException | IllegalAccessException | InvocationTargetException exc)
{
throw new InjectionProviderException("injecting resource " + annotation.name()+" via "+clazz.getName()+"."+method.getName(), exc);
}
}
}
} while ((clazz = clazz.getSuperclass()) != Object.class);
}
#Override
public void invokePostConstruct(Object managedBean) throws InjectionProviderException
{
logger.log(Level.CONFIG, "managedBean={0}", new Object[]{managedBean});
delegate.invokePostConstruct(managedBean);
}
#Override
public void invokePreDestroy(Object managedBean) throws InjectionProviderException
{
logger.log(Level.CONFIG, "managedBean={0}", new Object[]{managedBean});
delegate.invokePreDestroy(managedBean);
}
}
E&OE
Another possibility, yet I would think unlikely; is you are using metadata-complete="true" in your web.xml or web-fragment.xml file(s).
Defined metadata-complete:
The metadata-complete attribute defines whether this deployment descriptor and other related deployment
descriptors for this module (e.g., web service descriptors) are complete, or whether the class files available
to this module and packaged with this application should be examined for annotations that specify
deployment information. If metadata-complete is set to "true", the deployment tool must ignore any
annotations that specify deployment information, which might be present in the class files of the
application. If metadata-complete is not specified or is set to "false", the deployment tool must examine the
class files of the application for annotations, as specified by the specifications.
Example web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ResourceTest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Sorry I'm unable to comment due to rep or I would of asked for more clarification on what errors/etc you are seeing. That being said I have tested with both Tomcat 7.0.27 and Tomcat 7.0.41 with java full version "1.6.0_51-b11-457" and was able to use #Resource.
Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/Sample" auth="Container"
type="javax.sql.DataSource" username="nbuser" password="nbuser"
driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost/Sample"
maxActive="8" maxIdle="4"/>
</Context>
ResourceTest.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
#WebServlet("/ResourceTest")
public class ResourceTest extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(name="jdbc/Sample")
private DataSource ds;
public ResourceTest() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("<body>");
try {
//Context initCtx = new InitialContext();
//Context envCtx = (Context) initCtx.lookup("java:comp/env");
//DataSource ds = (DataSource) envCtx.lookup("jdbc/Sample");
Connection conn = ds.getConnection();
Statement s = conn.createStatement();
s.execute("Select * From \"NBUSER\".\"Friends\"");
ResultSet rs = s.getResultSet();
while (rs.next()) {
out.println(rs.getString("NAME") + " is my friend.");
}
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
out.println("</body>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Resources