FATAL EXCEPTION: CameraX-audio encoding thread - java

I am recording videos using the camera X library. When i take video for 5 seconds before that (i,e)two seconds if i close the video its crashing with above error.How to handle this run time exception in android cameraX library
E/AndroidRuntime: FATAL EXCEPTION: CameraX-audio encoding thread
Process: .debug, PID: 4625
java.lang.IllegalStateException
at android.media.MediaCodec.native_dequeueOutputBuffer(Native Method)
at android.media.MediaCodec.dequeueOutputBuffer(MediaCodec.java:2698)
at androidx.camera.core.VideoCapture.audioEncode(VideoCapture.java:705)
at androidx.camera.core.VideoCapture$1.run(VideoCapture.java:340)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.os.HandlerThread.run(HandlerThread.java:65)
sometimes the below issue
FATAL EXCEPTION: CameraX-video encoding thread
Process: <packagename>, PID: 10794
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaCodec.dequeueOutputBuffer(android.media.MediaCodec$BufferInfo, long)' on a null object reference
at androidx.camera.core.VideoCapture.videoEncode(VideoCapture.java:604)
at androidx.camera.core.VideoCapture$2.run(VideoCapture.java:348)
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)
in this samples also not fixed yet
https://github.com/android/camera-samples/issues/2#issuecomment-546812852

By adding a callback to videoCapture.startRecording(videoFile, executor, onVideoSavedCallback); you should be able to handle the exeption in the onError method.
/**
* Define callback that will be triggered after a video has been taken and saved to disk
*/
private VideoCapture.OnVideoSavedCallback onVideoSavedCallback= new VideoCapture.OnVideoSavedCallback() {
#SuppressLint("RestrictedApi")
#Override
public void onVideoSaved(#NonNull File file) {
Log.d("VIDEO_CAPTURE", "Video capture succeeded");
}
#Override
public void onError(int videoCaptureError, #NonNull String message, #Nullable Throwable cause) {
Log.e("VIDEO_CAPTURE", "Video capture failed");
if (cause != null) {
cause.printStackTrace();
Toast.makeText(context,"Video capture failed",Toast.LENGTH_LONG).show();
}
}
};

Related

How to Fix Jsoup nullpointerexception in android studio 2019 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am creating an app in which i want to scrape google data with the help of jsoup and show it to text view in android studio.
But after doing some coding with the help of jsoup i am getting following error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.yasht.cricketapp, PID: 11929
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.jsoup.nodes.Element.text()' on a null object reference
at com.example.yasht.cricketapp.Bottomnav.score_scrape.doInBackground(score_scrape.java:30)
at com.example.yasht.cricketapp.Bottomnav.score_scrape.doInBackground(score_scrape.java:13)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
this is my jsoup code with async task :
public class score_scrape extends AsyncTask<Void,Void,Void> {
String words;
TextView score;
public score_scrape( TextView score){
this.score =score;
}
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://www.google.com/search?q=india+vs+australia+3rd+odi+live+score").get();
Element element = doc.select("div[imspo_mh_cricket__score-major]").first();
words = element.text();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
score.setText(words);
}
}
I am using async task method which is declared i my main activity.
Comment for any further information.
In your case you don't want to use select You can simply change below line.
Change line from
Element element = doc.select("div[imspo_mh_cricket__score-major]").first();
To
Element element = doc.getElementsByClass("imspo_mh_cricket__score-major").first();
Output:
230

Query working on local backend but not on deployed backend

class EndpointsAsyncTask extends AsyncTask<Void, Void, List<Quote>> {
private static QuoteEndpoint myApiService = null;
private Context context;
EndpointsAsyncTask(Context context) {
this.context = context;
}
#Override
protected List<Quote> doInBackground(Void... params) {
if(myApiService == null) { // Only do this once
/*QuoteEndpoint.Builder builder = new QuoteEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
// end options for devappserver
QuoteEndpoint.Builder builder = new QuoteEndpoint.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://momcares-987.appspot.com/_ah/api/");
myApiService = builder.build();
}
try {
return myApiService.listQuote().execute().getItems();
} catch (IOException e) {
return Collections.EMPTY_LIST;
}
}
#Override
protected void onPostExecute(List<Quote> result) {
for (Quote q : result) {
Toast.makeText(context, q.getWho() + " : " + q.getWhom(), Toast.LENGTH_LONG).show();
}
}
}
The above class has been included in my MainActivity.java file.
http://rominirani.com/2014/08/26/gradle-tutorial-part-9-cloud-endpoints-persistence-android-studio/
I have been following this tutorial. I manually inserted quotes (Quote is the bean I am using) in the API Explorer and I successfully get the list of quotes in my emulator when I run the local server and test. However, when I deploy the same backend and run the application, I get a NullPointerException in the onPostExecuteMethod. Please help. Thanks!
Error Log:
06-26 11:50:19.889 26342-26342/com.sickstudios.sickapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x430d4140)
06-26 11:50:19.909 26342-26342/com.sickstudios.sickapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sickstudios.sickapplication, PID: 26342
java.lang.NullPointerException
at com.sickstudios.sickapplication.EndpointsAsyncTask.onPostExecute(MainActivity.java:64)
at com.sickstudios.sickapplication.EndpointsAsyncTask.onPostExecute(MainActivity.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
at dalvik.system.NativeStart.main(Native Method)
06-26 11:50:23.639 26342-26342/com.sickstudios.sickapplication I/Process﹕ Sending signal. PID: 26342 SIG: 9
Try this:
http://www.momcares-987.appspot.com/_ah/api/
Sometimes https calls raise the connectivity issue.

Android rxJava Error handling with retrofit

I'm using the newer RX java where instead of
Observable.create(new Observable.OnSubscribeFunc<T>() {...});
this is used: (due to deprecation)
Observable.create(new Observable.OnSubscribe<T>() {...});
(This can be important as most example, tutorial, explonation uses the old one...)
Well, lets see my problem. I have a Java class, relevant parts from it:
private interface ApiManagerService {
#FormUrlEncoded
#POST("/login")
User getUser(#Field("username") String userName, #Field("password") String password);
}
private static RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(HOST)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
private static ApiManagerService apiManager = restAdapter.create(ApiManagerService.class);
public static Subscription login(final String userName, final String password, Observer<User> observer) {
return Observable.create(new Observable.OnSubscribe<User>() {
#Override
public void call(Subscriber<? super User> subscriber) {
try {
User user = apiManager.getUser(userName, password);
subscriber.onNext(user);
subscriber.onCompleted();
} catch (RetrofitError e) {
subscriber.onError(e);
} catch (Throwable e) {
subscriber.onError(e);
}
}
}
).subscribeOn(Schedulers.io())
.retry(3)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
This code almost works perfectly, if everything is ok. But if I make an intentional error, like I turn off the WiFi.. than retrofit get the "UnKnownHostException"... as it should happen at the retrofit call (getUser) in the try catch block. But instead of handling the error to onError(Throwable t) --> where I could handle, it just crashes the app. So it is like if the error never gets to the catch block.
What is strange that HTTP errors (like 404, 401 etc.) is catched, got by onError(...) and everything is just fine.
Everything goes for 3 times before crash, as of .retry(3) but none gets into catch clause.
EDIT 1
LogCat Output:
01-08 16:19:31.576 15285-16162/asd.bdef.gh D/Retrofit﹕ ---- ERROR https://testapi.com/api/login
01-08 16:19:31.606 15285-16162/asd.bdef.gh D/Retrofit﹕ java.net.UnknownHostException: Unable to resolve host "testapi.com": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:394)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.squareup.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:259)
at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:233)
at com.squareup.okhttp.internal.http.RouteSelector.nextUnconnected(RouteSelector.java:159)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:133)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:314)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:237)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:423)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:105)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:239)
at com.squareup.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
at retrofit.client.UrlConnectionClient.prepareRequest(UrlConnectionClient.java:68)
at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:37)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:321)
at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
at retrofit.RestAdapter$RestHandler$1.invoke(RestAdapter.java:265)
at retrofit.RxSupport$2.run(RxSupport.java:55)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at retrofit.Platform$Android$2$1.run(Platform.java:142)
at java.lang.Thread.run(Thread.java:841)
01-08 16:19:31.606 15285-16162/asd.bdef.gh D/Retrofit﹕ ---- END ERROR
01-08 16:19:31.977 15285-15285/asd.bdef.gh D/AndroidRuntime﹕ Shutting down VM
01-08 16:19:31.977 15285-15285/asd.bdef.gh W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41c9d8b0)
01-08 16:19:31.977 15285-15285/asd.bdef.gh E/AndroidRuntime﹕ FATAL EXCEPTION: main
the given api address is not the real one, but the real one is reachable. I just turned off the WiFi to test error handling.
And one more use-case: If I add to the observable .onExceptionResumeNext([2nd observable]) than it goes to the 2nd observable, and it not crashes. But this is not the solution of the problem.
EDIT 2
ApiManager.login(userName, pass, new Observer<User>() {
#Override
public void onCompleted() { }
#Override
public void onError(Throwable e) {
DialogManager.showBasicErrorDialog(getApplicationContext(), e.getLocalizedMessage());
logger.showLog("Login Not ok");
e.printStackTrace();
}
#Override
public void onNext(User user) {
logger.showLog("login ok, user: " + user.getName().toString());
{...}
}
});
EDIT 3
FATAL EXCEPTION: main
rx.exceptions.OnErrorFailedException: Error occurred when trying to propagate error to Observer.onError
at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:175)
at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:97)
at rx.internal.operators.NotificationLite.accept(NotificationLite.java:144)
{...}
Caused by: java.lang.NullPointerException: Attempt to read from field 'rx.functions.Action0 rx.schedulers.TrampolineScheduler$TimedAction.action' on a null object reference
at rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue(TrampolineScheduler.java:85)
Thanks in advance for helping.
You don't have to build your own Observable with Retrofit, as Retrofit can directly return Observable:
http://square.github.io/retrofit/
Retrofit also integrates RxJava to support methods with a return type
of rx.Observable
#GET("/user/{id}/photo") Observable getUserPhoto(#Path("id")
int id);
(You won't have to handle errors by yourself)
Can you post the stacktrace of your crash ? As I think like you, that your application shouldn't crash.
It looks like you may be running into an issue has been fixed as of RxJava 1.0:
TrampolineScheduler NullPointerException

NullPointerException for method invocation on "this"

On my android project, I am getting an intermittent NullPointerException reported in both crashlytics and the play store for a null pointer exception when invoking one of my objects invokes a method on itself.
Here is the entirety of the method that has the NullPointerException:
#Override
public void notifyActivityStarted() {
startUpdatingLocation(); // <-- NullPointerException occurs here. This is line 83 of DefaultAndroidLocationProvider.java
}
private void startUpdatingLocation() {
final String bestProvider = getBestProviderName();
Log.d(LOGTAG, "Starting to update location for provider: " + bestProvider);
// If we don't have a location yet, then let's make sure we get one at
// least
// temporarily.
Location currentLoc = getLastLocationFromBestProvider();
if (currentLoc != null) {
Log.d(LOGTAG, "Hydrating with last location");
mLastLocation.hydrate(currentLoc);
}
mWorker = new WorkerThread("DefaultAndroidLocation");
// Get a location update every 10s from both network and GPS.
if (mManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
10000,
0,
DefaultAndroidLocationProvider.this,
mWorker.getLooper());
}
if (mManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
10000,
0,
DefaultAndroidLocationProvider.this,
mWorker.getLooper());
}
mIsUpdatingLocation = true;
shutdownInitiated = false;
}
Here is the stack trace:
java.lang.NullPointerException
at com.jingit.mobile.location.DefaultAndroidLocationProvider.notifyActivityStarted(DefaultAndroidLocationProvider.java:83)
at com.jingit.mobile.location.ActivityObserverSet.onStartObserved(ActivityObserverSet.java:48)
at com.jingit.mobile.location.LocationAwareFragment.onStart(LocationAwareFragment.java:41)
at android.support.v4.app.Fragment.performStart(Fragment.java:1484)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5633)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:896)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
at dalvik.system.NativeStart.main(NativeStart.java)
I wasn't able to find anything to give me hints on the documentation for NullPointerException, and haven't been able to find any other helpful hints. Any thoughts or ideas would be greatly appreciated.

Android with websocket communication (Node Websocket server and Android Java Client). Dosen't work on Android 4

I tried to use as a Android client Websocket - weberknecht with a thread to send every second a message to a Nodejs Websocket (js): Node WebSocket Server
It work fine on android 2 or 2.3.3, but when i trie on android 4 i get an error on websocket.connect();
Do you know why or what i am doing wrong?
My code is:
public class MainThread extends Thread {
private boolean is_running;
private URI url = null;
private de.roderick.weberknecht.WebSocket websocket = null;
public MainThread() {
this.is_running = false;
try {
url = new URI("ws://192.168.1.88:8088/");
websocket = new WebSocketConnection(url);
websocket.setEventHandler(new WebSocketEventHandler() {
public void onOpen(){
System.out.println("--open");
}
public void onMessage(WebSocketMessage message){
System.out.println("--received message: " + message.getText());
}
public void onClose(){
System.out.println("--close");
}
});
} catch (WebSocketException wse) {
wse.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (URISyntaxException use) {
use.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
#Override
public void run() {
while(is_running){
try {
websocket.send("hello world");
Thread.sleep(10000);
}
catch (WebSocketException wse) {
wse.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void set_running(boolean is_running) {
if(is_running == true)
try {
websocket.connect();
this.is_running = is_running;
} catch (WebSocketException e) {
System.out.println(e.toString());
//e.printStackTrace();
}
}
}
and the error I get on android 4:
ERROR/AndroidRuntime(562): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.biskis.test.websocket/com.biskis.test.websocket.GameActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at de.roderick.weberknecht.WebSocketConnection.createSocket(WebSocketConnection.java:238)
at de.roderick.weberknecht.WebSocketConnection.connect(WebSocketConnection.java:83)
at com.biskis.test.websocket.MainThread.set_running(MainThread.java:76)
at com.biskis.test.websocket.GameActivity.onCreate(GameActivity.java:20)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
... 11 more
Or do you know how to implement this in a better way to comunicate a client (java, android) to a server (nodejs, websocket) ?
Thank you.
Don't connect to the Websocket on the main Thread (i.e. in GameActivity.onCreate) and the error will go away. You could use an AsyncTask to connect to the Websocket in the background.
Blocking the main thread by I/O operations (and network access is ultimately a I/O operation) will lead (in the worst case) to a sluggish user interface or Android killing your application because it didn't react timely. See the designing for responsiveness document.

Categories