问题
I have a class that extends from AysncTask. Inside the doInBackground
method I want to update the cookies, so I have:
CookieSyncManager.createInstance(context); // <<<<<<<<<<<<<<<<<<
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie(cookie.getDomain(), cookieString);
CookieSyncManager.getInstance().sync();
But I get java.lang.NullPointerException
in the first line.
So, the question is:
- Why could be causing this ?
- Do I need to create it in another activity, and just used it in this activity ? how ? why ?
Notes:
- I know that my context is not null, I checked that.
- I can't have an onCreate method on an AsyncTask. To do this.
Here is the stack-trace:
java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
at android.webkit.JniUtil.setContext(JniUtil.java:53)
at android.webkit.CookieSyncManager.createInstance(CookieSyncManager.java:89)
at com.t.m.library.HttpRequest.doInBackground(HttpRequest.java:129)
at com.t.m.library.HttpRequest.doInBackground(HttpRequest.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
This is my doInBackground method:
request = new HttpGet(this.url);
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", this.basicAuthentication);
HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpClient httpclient = null;
httpclient = new DefaultHttpClient(httpParams);
HttpResponse response = httpclient.execute(request);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity, "UTF-8");
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie(cookie.getDomain(), cookieString);
CookieSyncManager.getInstance().sync();
回答1:
I call it in Application
's onCreate()
passing the application as context
回答2:
I've never used CookieSyncManager
, but from what I can see in the docs may be you should not use it within a Thread because its already creating one:
A separate thread saves the cookies between, driven by a timer.
- You should call
createInstance
when the application starts, usually inonCreate()
getInstance().startSync()
InActivity.onResume()
- And
getInstance().stopSync()
inActivity.onPause()
Here you have an example
Hope this help.
来源:https://stackoverflow.com/questions/23813034/nullpointerexception-in-cookiesyncmanager-createinstance-in-asynctask