Java Android Studio Null Pointer Exception on Jaunt Webcrawler

404 views Asked by At

I am trying to run the simple Jaunt example from the website and got an error for Null Pointer Exception. I am not sure what to do because there is very little support for using Jaunt in Android Studio. Here is my code:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try{
        UserAgent userAgent = new UserAgent();
        userAgent.visit("http://jaunt-api.com/examples/signup.htm");         
    }
    catch(JauntException e){
        System.out.println(e);
    }

}

}

Here is the error I got when I ran it:

java.lang.NullPointerException: Attempt to invoke interface method 'void com.android.okhttp.internal.http.Transport.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference

The error was on the userAgent.visit line.

This is where I got the code: http://jaunt-api.com/jaunt-tutorial.htm

3

There are 3 answers

0
Nick Cardoso On

This problem usually occurs on Android if you failed to connect your HttpURLConnection first - or can be a side effect if you forgot to add the internet permission to your manifest

0
Ege Kuzubasioglu On

First make sure your url is correct

http://jaunt-api.com/examples/signup.htm 

this is definitely wrong url

then

Here is a workaround class for NPE that you can use in OkHttp

public class NullOnEmptyConverterFactory extends Converter.Factory {


    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
        return (Converter<ResponseBody, Object>) body -> {
            if (body.contentLength() == 0) return null;
            return delegate.convert(body);
        };
    }
}

In your OkHttp client builder addNetworkInterceptor first, order matters

0
Bruno Carletti On

Try add the permissions in your AndroidManifest.xml:

<uses-permission
     android:name="android.permission.WRITE_EXTERNAL_STORAGE"
     android:maxSdkVersion="18" />
<uses-permission
     android:name="android.permission.INTERNET"
     android:maxSdkVersion="18" />