Unable to start receiver (Package name).Class On Camera.open() - runtime-error

Creating an widget to turn on and off Flash light
Getting Error on turning off flash light
My Widget Class Code
Code In onRecieve
#Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if(SYNC_CLICKED.equals(intent.getAction()))
{
AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget__flash);
ComponentName componentName=new ComponentName(context,Widget_Flash.class);
if(Allowed_Flash) {
if (!Flash_Light_On) {
getCamera();
Turn_On_Flash_Light();
views.setImageViewResource(R.id.Widget_On_Off_Button, R.drawable.button2);
Flash_Light_On = true;
} else {
views.setImageViewResource(R.id.Widget_On_Off_Button, R.drawable.button1);
getCamera();
Turn_Off_Flash_Light();
}
Flash_Light_On = false;
}
}
appWidgetManager.updateAppWidget(componentName, views);
}
}
Get Camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
}
}
}
Turn On
private void Turn_On_Flash_Light()
{
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}
Turn Off
private void Turn_Off_Flash_Light()
{
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.startPreview();
camera.release();
}
Error
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start receiver
io.farooq.flash_light.Widget_Flash: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2287)
at android.app.ActivityThread.access$1600(ActivityThread.java:140)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at
io.farooq.flash_light.Widget_Flash.Turn_Off_Flash_Light(Widget_Flash.java:143)
at io.farooq.flash_light.Widget_Flash.onReceive(Widget_Flash.java:74)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2280)
at android.app.ActivityThread.access$1600(ActivityThread.java:140) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4921) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 
at dalvik.system.NativeStart.main(Native Method)
In Samsung J5 Prime (API 23) Code is working fine But in Tried it in (API 16) & (API 19) Flash Is Turning On But getting error while turning off

Related

Subscription query always throws AxonServerException: CANCELLED: AXONIQ-5000

Axon framework version : 4.4.7
Axon server : 4.5.7
#Component
#ProcessingGroup("product-group")
public class ProductEventHandler {
private final ProductRepository productsRepository;
private final QueryUpdateEmitter queryUpdateEmitter;
public ProductEventHandler(ProductRepository productsRepository, QueryUpdateEmitter queryUpdateEmitter) {
this.productsRepository = productsRepository;
this.queryUpdateEmitter = queryUpdateEmitter;
}
#EventHandler
public void handle(ProductCreatedEvent event) throws Exception {
ProductEntity entity = new ProductEntity();
BeanUtils.copyProperties(event, entity);
try {
productsRepository.save(entity);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
#EventHandler
public void handle(ProductUpdatedEvent event) {
ProductEntity entity = new ProductEntity();
BeanUtils.copyProperties(event, entity);
try {
productsRepository.save(entity);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
ProductResponse productResponse = new ProductResponse();
productResponse.setProductId(event.getProductId());
productResponse.setStatus("Updated");
//queryUpdateEmitter.emit(FetchProductQuery.class, query -> true, productResponse);
queryUpdateEmitter.emit(FetchProductQuery.class,
query -> query.getProductId().equals(event.getProductId()), productResponse);
}
}
#RestController
#RequestMapping("/product")
public class ProductController {
private final CommandGateway commandGateway;
private final QueryGateway queryGateway;
private SubscriptionQueryResult<ProductResponse, ProductResponse> queryResult;
#Autowired
public ProductController(CommandGateway commandGateway, QueryGateway queryGateway) {
this.queryGateway = queryGateway;
this.commandGateway = commandGateway;
}
#PutMapping("/{id}")
public ProductResponse updateProduct(#PathVariable("id") String id,
#Valid #RequestBody ProductRequest request) {
UpdateProductCommand updateProductCommand = UpdateProductCommand.builder().productId(id)
.price(request.getPrice()).quantity(request.getQuantity()).title(request.getTitle()).build();
commandGateway.sendAndWait(updateProductCommand);
queryResult = queryGateway.subscriptionQuery(
FetchProductQuery.builder().productId(id), ResponseTypes.instanceOf(ProductResponse.class),
ResponseTypes.instanceOf(ProductResponse.class));
try {
// return queryResult.updates().blockFirst();
return queryResult.initialResult().block();
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
queryResult.close();
}
}
}
#Component
public class ProductsQueryHandler {
private final ProductRepository productsRepository;
public ProductsQueryHandler(ProductRepository productsRepository) {
this.productsRepository = productsRepository;
}
#QueryHandler
public ProductResponse handler(FetchProductQuery query) {
ProductEntity productEntity = productsRepository.findByProductId(query.getProductId());
ProductResponse productResponse = new ProductResponse();
BeanUtils.copyProperties(productEntity, productResponse);
return productResponse;
}
}
I could not see any subscription queries in AXON dashboard, getting below error. Can you please help me for the cause and solution???
2021-10-21 18:09:42.468[0;39m [32m INFO[0;39m [35m19608[0;39m [2m---[0;39m [2m[nio-8888-exec-2][0;39m [36mo.a.m.interceptors.LoggingInterceptor [0;39m [2m:[0;39m Dispatched messages: [FetchProductQueryBuilder]
org.axonframework.axonserver.connector.AxonServerException: CANCELLED: AXONIQ-5000
at org.axonframework.axonserver.connector.ErrorCode.lambda$static$24(ErrorCode.java:145)
at org.axonframework.axonserver.connector.ErrorCode.convert(ErrorCode.java:182)
at org.axonframework.axonserver.connector.ErrorCode.convert(ErrorCode.java:213)
at org.axonframework.axonserver.connector.ErrorCode.convert(ErrorCode.java:202)
at org.axonframework.axonserver.connector.event.util.GrpcExceptionParser.parse(GrpcExceptionParser.java:57)
at reactor.core.publisher.Mono.lambda$onErrorMap$31(Mono.java:3437)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94)
at reactor.core.publisher.MonoCompletionStage.lambda$subscribe$0(MonoCompletionStage.java:79)
at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
at java.base/java.util.concurrent.CompletableFuture.uniWhenCompleteStage(CompletableFuture.java:883)
at java.base/java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:2321)
at java.base/java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:143)
at reactor.core.publisher.MonoCompletionStage.subscribe(MonoCompletionStage.java:57)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
at reactor.core.publisher.Mono.subscribe(Mono.java:4099)
at reactor.core.publisher.Mono.block(Mono.java:1702)
at com.demo.product.controller.ProductController.updateProduct(ProductController.java:75)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:920)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:831)
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)
at reactor.core.publisher.Mono.block(Mono.java:1703)
... 51 more
[2m2021-10-21 18:09:42.493[0;39m [33m WARN[0;39m [35m19608[0;39m [2m---[0;39m [2m[nio-8888-exec-2][0;39m [36m.m.m.a.ExceptionHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.axonframework.axonserver.connector.AxonServerException: CANCELLED: AXONIQ-5
000]
The error code AXONIQ-5000 indicates that no query handler for the given query request type could be found.
I don't have the complete code, of course, but checking the code it looks like the first parameter of the query request is a builder (the result of FetchProductQuery.builder().productId(id)) and not a FetchProductQuery instance.

my netty program sometimes occur exception like “connection reset by peer”

i am coding a http server with netty-all-4.1.0.Final.jar,while the server listening,sometimes while happen "connection reset by peer",the detail like below:
Connection reset by peer
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1098)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:350)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:112)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:544)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:485)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:399)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:371)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:742)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:145)
at java.lang.Thread.run(Thread.java:748)
this is my main server code:
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
//将同一个http请求的内容组装到一起,调用一次handler
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new HttpServerHandler());
}
});
int port = ConfUtils.port;
ChannelFuture f = b.bind(port).sync();
logger.info("start lisner-------port is {}",port);
f.channel().closeFuture().sync();
} catch(Exception e){
logger.error(e.getMessage(),e);
}
finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
this is my handler class:
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if(msg instanceof FullHttpRequest){
try{
logger.info("accept http msg!");
FullHttpRequest fullHttpRequest = (FullHttpRequest)msg;
ProcessMsg.dealMsg(fullHttpRequest);
logger.info("full header is {}",fullHttpRequest);
String responseHtml = "response from server!";
byte[] responseBytes = responseHtml.getBytes("UTF-8");
int contentLength = responseBytes.length;
FullHttpResponse response = new
DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/html; charset=utf-8");
response.headers().set("Content-Length", Integer.toString(contentLength));
Thread.sleep(1000 * 5);
ctx.writeAndFlush(response);
ctx.flush();
logger.info("response from server!");
}catch(Exception e){
logger.error(e.getMessage(),e);
}
}
else{
logger.info("this is not http request");
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LoggerFactory.getLogger("excplog").error(cause.getMessage(),cause);
ctx.close();
}
}
it's not always happend,sometimes happen and most times not,and we can't find any question about request

Retrofit Throwing null pointer exception

Showing Null pointer exception** in this code.
** yrWebService.getUserInfo()**
I have tried most of the things but I can't figure it out.
Anyone please help to fix this issue.
The getUserInfo() throwing null pointer exception.
someone help me to solve this. I pasted the interface down there.
public void fetchUserProfile() {
YRWebService.getUserInfo()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<YRUserResponse>() {
#Override
public void onError(Throwable e) {
Toast.makeText(YarraApplication.this, "Error on server :" +e, Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete() {
}
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(YRUserResponse yrUserResponse) {
//progressDialog.dismiss();
if (yrUserResponse != null) {
if (yrUserResponse.getUser() != null) {
YRPreferenceManager.setString(PreferenceKeys.USER_PROFILE_RESPONSE,
new Gson().toJson(yrUserResponse));
YRUser yrUser = yrUserResponse.getUser();
YarraApplication.userId = yrUserResponse.getUser().getUser_id();
YarraApplication.access = yrUserResponse.getUser().getGoogle_access_token();
YarraApplication.email = yrUser.getEmail();
YarraApplication.fName = yrUser.getFirst_name();
YarraApplication.lName = yrUser.getLast_name();
YarraApplication.mobile = yrUser.getTelephone();
}else {
// YRUtils.showUnknownErrorDialog(YarraApplication.this);
}
}// else {
// YRUtils.showUnknownErrorDialog(UserProfileActivity.this);
// }
}
});
}
**Interface :::: **
The interface we are using here is this
public interface YRWebService {
#GET("/users")
Observable<YRUserResponse> getUserInfo();
}
public class YRUserResponse {
List<YRError> errors;
YRUser user;
public YRUser getUser() {
return user;
}
public void setUser(YRUser user) {
this.user = user;
}
**retrofit.RetrofitError**:
```
2019-05-06 15:26:49.506 30475-30475/com.rever.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rever.app, PID: 30475
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rever.app/com.rever.app.UserProfileActivity}: retrofit.RetrofitError
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: retrofit.RetrofitError
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:400)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
at java.lang.reflect.Proxy.invoke(Proxy.java:913)
at $Proxy0.getUserInfo(Unknown Source)
at com.rever.app.UserProfileActivity.fetchUserProfile(UserProfileActivity.java:220)
at com.rever.app.UserProfileActivity.onCreate(UserProfileActivity.java:132)
at android.app.Activity.performCreate(Activity.java:7084)
at android.app.Activity.performCreate(Activity.java:7075)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:176) 
at android.app.ActivityThread.main(ActivityThread.java:6635) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.squareup.okhttp.internal.Dns$1.getAllByName(Dns.java:29)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:231)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:317)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:241)
at com.squareup.okhttp.Call.getResponse(Call.java:198)
at com.squareup.okhttp.Call.execute(Call.java:80)
at retrofit.client.OkClient.execute(OkClient.java:53)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240) 
at java.lang.reflect.Proxy.invoke(Proxy.java:913) 
at $Proxy0.getUserInfo(Unknown Source) 
at com.rever.app.UserProfileActivity.fetchUserProfile(UserProfileActivity.java:220) 
at com.rever.app.UserProfileActivity.onCreate(UserProfileActivity.java:132) 
at android.app.Activity.performCreate(Activity.java:7084) 
at android.app.Activity.performCreate(Activity.java:7075) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2767) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:176) 
at android.app.ActivityThread.main(ActivityThread.java:6635) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 
```

Application Crash when attempting to get child from Firebase

MY application is crashing on line 43:
float value = dataSnapshot.child("temp").getValue(float.class);
When i remove the .child from the addChildEventListener and from the Datasnapshot , the app will display the float value from the database.
My aim is to display both a float value and then add in another line to display the Humidity value my database will hold.
so i will be attempting .child("temp").child("humi") to be displayed on a listview.
Can anybody steer me in the right direction or help me resolve why i cant specify child entries.
ListView listview = (ListView) findViewById(R.id.listview);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
listview.setAdapter(adapter);
//INITIALIZE FIREBASE DB
db = FirebaseDatabase.getInstance().getReference();
db.child("temp").limitToLast(1).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
float value = dataSnapshot.child("temp").getValue(float.class);
list.add("System Temperture: " + value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
adapter.clear();
float value = dataSnapshot.child("temp").getValue(float.class);
list.add("System Temperture: " + value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
JSON value from firebase
{
"humi" : {
"-KaxKLD00Ib97d1dRbvR" : 17.0
},
"temp" : {
"-KaxKL8G17y4ezfdBMDP" : 21.0
}
}
Logcat
01-20 18:32:18.675 16935-16935/com.m.j.project.josephmay E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.m.j.project.josephmay, PID: 16935
java.lang.NullPointerException: Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference
at com.m.j.project.josephmay.MainActivity$1.onChildAdded(MainActivity.java:43)
at com.google.android.gms.internal.zzblz.zza(Unknown Source)
at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
01-20 18:32:26.645 16935-17099/com.m.j.project.josephmay W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
01-20 18:32:26.645 16935-17099/com.m.j.project.josephmay W/ResourcesManager: getTopLevelResources: /data/app/com.google.android.gms-1/base.apk / 1.0 running in com.m.j.project.josephmay rsrc of package com.google.android.gms
I think I was running into a similar issue and this response from Frank helped me: https://groups.google.com/forum/#!topic/firebase-talk/-cdTDFBOmMw.
When you are creating the new record within Firebase, are you doing setValue() for "humi" and "temp" separately or doing setValue() for the entire object? Try switching it to setValue() for the whole object.

JavaFX Application : cannot find SunPKCS11 class

I am developing a JavaFX application used to sign pdf using eToken Pro. The sign methods run perfectly in a normal Java project. While when run in the JavaFX application, it keeps encountering exceptions like this:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NoClassDefFoundError: sun/security/pkcs11/SunPKCS11
at javafxapplication3.JavaFXApplication3.start(JavaFXApplication3.java:21)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
... 1 more
Caused by: java.lang.ClassNotFoundException: sun.security.pkcs11.SunPKCS11
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 12 more
Java Result: 1
the codes I used to sign pdf are as follows:
#Override
public void start(Stage primaryStage) {
Signer signer = new Signer(new File("C:/Users/Adam/Desktop/pdf/hello.pdf"));
signer.signWithToken(true);
}
the codes of class Signer are as follows:
public class Signer {
// define the file to be signed
private final File file;
private static String smartcardDllPath;
private static int level;
private static String reason;
private static String src;
private static String dest;
private static String location;
private static Collection<CrlClient> crlList;
private static OcspClient ocspClient;
private static TSAClient tsaClient;
private static final String DLL = "C:/Windows/System32/eTPKCS11.dll";
public Signer(File theFile) {
location = "HK SAR";
smartcardDllPath = null;
file = theFile;
}
public void signWithToken(boolean certified) {
try {
String config = "name=eToken\nlibrary=" + DLL + "\nslotListIndex=" + getSlotsWithTokens(DLL)[0];
ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
Provider providerPKCS11 = new SunPKCS11(bais);
Security.addProvider(providerPKCS11);
configureParameters(certified);
// create PdfSignatureAppearance
PdfSignatureAppearance appearance = getPdfSigAppearance();
// configure the keystore, alias, private key and certificate chain
char[] pin = "love4Sakura".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, pin);
String alias = (String) ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, null);
Certificate[] chain = ks.getCertificateChain(alias);
printChainInfo(chain);
// configure the CRL, OCSP and TSA
configCrlOcspTsa(chain);
// create the signature
ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "SunPKCS11-eToken");
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, digest, pks, chain, crlList, ocspClient,
tsaClient, 0, MakeSignature.CryptoStandard.CMS);
} catch (IOException | DocumentException | GeneralSecurityException ex) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static long[] getSlotsWithTokens(String libraryPath) {
CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();
String functionList = "C_GetFunctionList";
initArgs.flags = 0;
PKCS11 tmpPKCS11 = null;
long[] slotList = null;
try {
try {
tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, false);
System.out.println(tmpPKCS11.toString());
} catch (IOException ex) {
try {
throw ex;
} catch (IOException ex1) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex1);
}
}
} catch (PKCS11Exception e) {
try {
initArgs = null;
tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, true);
} catch (IOException | PKCS11Exception ex) {
}
}
try {
slotList = tmpPKCS11.C_GetSlotList(true);
for (long slot : slotList) {
CK_TOKEN_INFO tokenInfo = tmpPKCS11.C_GetTokenInfo(slot);
System.out.println("slot: " + slot + "\nmanufacturerID: "
+ String.valueOf(tokenInfo.manufacturerID) + "\nmodel: "
+ String.valueOf(tokenInfo.model));
}
} catch (PKCS11Exception ex) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex);
}
return slotList;
}
Before you guys answer: I want to emphasize that I reference the Signer class in a normal Java Project perfectly. So I donn't think it's a 32-bit or 64-bit problem. Plus, I am using the 32-bit JDK 1.7
This issue can be because unsupported version of java.Do one thing download particular jar file for that and include it on your project it'll work for you.
You can download the jar from this link -
http://www.docjar.com/jar/sunpkcs11.jar
I was also getting the same error -
java.lang.ClassNotFoundException: sun.security.pkcs11.SunPKCS11
Adding the following dependency in pom.xml helped me -
<dependency>
<groupId>sunpkcs11</groupId>
<artifactId>sunpkcs11</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>/Library/Java/JavaVirtualMachines/jdk1.8.0_341.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar</systemPath>
</dependency>
In <systemPath>...</systemPath>, give the appropriate path of sunpkcs11.jar from your system.

Resources