NullPointerException in my AsyncTask - java

Hey everyone ,
I have an Async Task for pointing to a point on the map based on user inputted address. I have a NullPointerException in the onPostExecute and I can work out why. Here is the async class
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting only one address that matches the query
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found.Please check address", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
mMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){// this is line 585 from the logcat
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng_search = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng_search);
markerOptions.title(addressText);
mMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng_search));
}
}
}
here is the logcat:
09-28 02:51:45.501: E/AndroidRuntime(16587): FATAL EXCEPTION: main
09-28 02:51:45.501: E/AndroidRuntime(16587): java.lang.NullPointerException
09-28 02:51:45.501: E/AndroidRuntime(16587): at drkstr.yar.Create_reminder_loc$GeocoderTask.onPostExecute(Create_reminder_loc.java:585)
09-28 02:51:45.501: E/AndroidRuntime(16587): at drkstr.yar.Create_reminder_loc$GeocoderTask.onPostExecute(Create_reminder_loc.java:1)
09-28 02:51:45.501: E/AndroidRuntime(16587): at android.os.AsyncTask.finish(AsyncTask.java:417)
09-28 02:51:45.501: E/AndroidRuntime(16587): at android.os.AsyncTask.access$300(AsyncTask.java:127)
09-28 02:51:45.501: E/AndroidRuntime(16587): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
09-28 02:51:45.501: E/AndroidRuntime(16587): at android.os.Handler.dispatchMessage(Handler.java:99)
09-28 02:51:45.501: E/AndroidRuntime(16587): at android.os.Looper.loop(Looper.java:143)
09-28 02:51:45.501: E/AndroidRuntime(16587): at android.app.ActivityThread.main(ActivityThread.java:4196)
09-28 02:51:45.501: E/AndroidRuntime(16587): at java.lang.reflect.Method.invokeNative(Native Method)
09-28 02:51:45.501: E/AndroidRuntime(16587): at java.lang.reflect.Method.invoke(Method.java:507)
09-28 02:51:45.501: E/AndroidRuntime(16587): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-28 02:51:45.501: E/AndroidRuntime(16587): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-28 02:51:45.501: E/AndroidRuntime(16587): at dalvik.system.NativeStart.main(Native Method)
The error is turning up at line 585 , I have marked this in the code. The only 2 variables in that line are i and address and I check if address in null. I don't get why I am still getting a null pointer exception.
Let me know if you need to see anymore of the code.
Thanks for taking the time to read this and for any help that you can give.

if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found.Please check address", Toast.LENGTH_SHORT).show();
return; // add this
}

As suggested in the comment, your addresses variable is most likely null.
You check if addresses is null in the conditional statement, but you never actually handle this situation. If addresses is null all you do is notify the user through a Toast, but a FRACTION of a second later (before the animation of the Toast is even loaded on your screen) your program crashes.
You need to handle the situation where addresses is null (that is, not call methods on the variable and try to populate the variable, or something completely different), or make sure it never is null.

Put your for loop in else part because right now even if your addresses is null or address.size=0 the for loop gets executed with the null value and gives NPE

Related

Android http connection refused

I created an Android test program with service and activity.
In activity I start sticky service. Service make http requests every 10 seconds.
If I not exit from activity, all works fine. If I exit, service works sometime, then killed by system and restarted. After restart sometimes http requests works, sometimes gives an error message:
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: java.net.ConnectException: failed to connect to www.ya.ru/87.250.250.242 (port 80) after 15000ms: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.Socket.connect(Socket.java:882)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService.sendPostRequest(MyService.java:160)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:128)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:109)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.lang.Thread.run(Thread.java:818)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: ... 21 more
After the appearance of this error, the following requests will also fail.
I tried to start service in another process, tried to start each http request in new IntentService, tried to restart service after this error, but no results.
If an error has occurred, then other subsequent requests will also give an error. Only application restart helps.
Has anyone encountered such problem? How to make a stable connection? I read a lot of topics, but did not find the right answer.
MyService.java
package home.xmpp;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MyService extends Service implements ComponentCallbacks2 {
private Boolean disconnectAppeared = false;
static MyService instance;
private Handler mHandler = new Handler();
MyTask mt;
Boolean mtruned = false;
public static MyService getInstance(){
return instance;
}
#Override
public IBinder onBind(final Intent intent) {
//throw new UnsupportedOperationException("Not yet implemented");
return new LocalBinder<MyService>(this);
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
mHandler.postDelayed(timeUpdaterRunnable, 100);
Log.e("MyService"," created");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_STICKY;
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("MyService"," destroyed");
mHandler.removeCallbacks(timeUpdaterRunnable);
}
public void onTrimMemory(int level) {
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL: //Release any memory that your app doesn't need to run.
//the system will begin killing background processes. !!!
Log.e("Memory level","4");
break;
default:
break;
}
}
private Runnable timeUpdaterRunnable = new Runnable() {
public void run() {
if (mtruned == false) {
Log.e("Time", " update");
mt = new MyTask();
mt.execute();
mHandler.postDelayed(this, 10000);
} else {
cancelTask();
}
}
};
private void cancelTask() {
if (mt == null) return;
Log.d("MyService", "cancel result: " + mt.cancel(false));
}
class MyTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
mtruned = true;
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("http","updated");
mtruned = false;
}
#Override
protected String doInBackground(String... params) {
String result = "";
HashMap<String,String> data = new HashMap<>();
data.put("data", "data");
result = sendPostRequest("http://www.ya.ru", data);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
mtruned = false;
}
}
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Update 05.10.17 I still not find a solution. I tested this programm on Android 4.1.2. It works fine. On Android 5.1.1 it works about 3 minutes after exiting the activity and then I receive connection refused error. When I return to activity, errors disappears. On Android 6.0.1 similar situation, but the error is slightly different java.net.SocketTimeoutException: failed to connect to /94.130.25.242 (port 80) after 10000ms. I think that the system blocks network activity in services after a while, but never in activities (?).
Update 05.10.17
I noticed that the connection disappears not only after the restart of the service, but also after 2-3 minutes, when exiting activity. When I return to activity, connections are restored.
I have made a video Link
Update 06.10.17
One Android specialist told me, that this problem appear only in Xiaomi phones. MIUI rejects network connections after some minutes. Only OkHttp helps. I will try it and will make feedback here.
A "connect failed: ECONNREFUSED (Connection refused)" most likely means that there is nothing listening on that port AND that IP address. Possible explanations include:
the service has crashed or hasn't been started,
your client is trying to connect using the wrong IP address or port,
or
server access is being blocked by a firewall that is "refusing" on
the server/service's behalf. This is pretty unlikely given that
normal practice (these days) is for firewalls to "blackhole" all
unwanted connection attempts.
It is impossible to use long network connections in background on Xiaomi phones. It's MIUI blocks any network connections after some time. For critical network connections, you can use Firebase Cloud Messaging, which have high priority in Android system. It can initiate necesary background job.

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.

unfortunately app closed error in android app when i debug the code

I have developed an app in android to find power shut down.When i run the app ,unfortunately closed once I debug the app.Here I got the error in doInbackground
My java code is here
private static final String URL = "http://livechennai.com/powershutdown_news_chennai.asp";
//private static final String URL = "http://livechennai.com/powercut_schedule.asp";
ProgressDialog mProgressDialog;
EditText filterItems;
ArrayAdapter<String> arrayAdapter;
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
// Connect to website
Document document = Jsoup.connect(URL).get();
// Get the html document title
websiteTitle = document.title();
Elements table=document.select("#table13>tbody>tr>td>a[title]");
for(Element link:table){
hrefs.add(link.attr("abs:href"));
//int arraySize=hrefs.size();
//websiteDescription=link.attr("abs:href");
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
websiteDescription=hrefs.get(0);
websiteDescription1=hrefs.get(1);
websiteDescription2=hrefs.get(2);
websiteDescription3=hrefs.get(3);
}
Below is the error log
06-09 23:17:10.284 17923-17937/com.example.poweralert.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:60)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:30)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.poweralert.app.PrimaryActivity$FetchWebsiteData.doInBackground(PrimaryActivity.java:144)
at com.example.poweralert.app.PrimaryActivity$FetchWebsiteData.doInBackground(PrimaryActivity.java:100)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:838)
06-09 23:17:10.
How to solve this error/issue? It shows null in website description .
Looks like there is an error in URL connection. Are you not passing valid URL?
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL

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.

Geocoder.isPresent() causes NullPointerException?

I got the following error message from Google Play Developer Console.
Besides the try/catch I cannot find anything that could give a null pointer, was it the
Geocoder.isPresent() which is not available in API 8?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxxxx.SearchActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
at android.app.ActivityThread.access$600(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
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:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.xxxxxxxx.SearchActivity.updateUserLocationNameBasedOnNewCoordinates(SearchActivity.java:367)
at com.xxxxxxxx.SearchActivity.useDeviceLocation(SearchActivity.java:338)
at com.xxxxxxxx.SearchActivity.start(SearchActivity.java:495)
at com.xxxxxxxx.SearchActivity.onCreate(SearchActivity.java:253)
at android.app.Activity.performCreate(Activity.java:5206)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
... 11 more
ACTIVITY:
public void updateUserLocationNameBasedOnNewCoordinates() {
String city = null;
String country = null;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list;
if (Geocoder.isPresent()) {
try {
list = geocoder.getFromLocation(userLocation.getLatitude(),
userLocation.getLongitude(), 1);
Address address = list.get(0);
city = address.getLocality();
country = address.getCountryName();
} catch (IOException e) {
e.printStackTrace();
}
}
if (city == null || country == null)
locationDescription = "Map location";
else
locationDescription = city + " " + country;
}
MANIFEST:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
If you see the documentation of Geocoder.isPresent(), it says: Lack of network connectivity may still cause these methods to return null or empty lists. So make sure you are connected.
Other important thing is that the document says that it was added in API level 9 but you have stated android:minSdkVersion=8 in the manifest. Try to mention android:minSdkVersion=9 or above. Hope this helps.

Categories