Geocoder.isPresent() causes NullPointerException? - java

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.

Related

How to fix java.lang.IllegalStateException

I'm currently working on my A Level Computer Science controlled assessment, making a Scout Manager App in Android Studio, using Java and XML - none of which I have used before. I'm now working on a n event creator.
I'm trying to create a record, which will show which transport has been selected for which event, however I have run into a problem - the LogCat is giving me the following error:
04-02 15:25:42.663 18482-18482/com.example.atomi.scoutmanagerprototype E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.atomi.scoutmanagerprototype, PID: 18482
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:4761)
at android.view.View$PerformClick.run(View.java:19767)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5310)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:4761)
at android.view.View$PerformClick.run(View.java:19767)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5310)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.example.atomi.scoutmanagerprototype/databases/ScoutManager.db
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1158)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.example.samogonovsky.scoutmanager.databaseHandler.getRandomTransport(databaseHandler.java:649)
at com.example.samogonovsky.scoutmanager.frmCreateEvent2.saveAndExit(frmCreateEvent2.java:528)
However, I have not closed the cursor in either of these two places.
Here is the code in the "databaseHandler" class:
//Select a random mode of transport
public Cursor getRandomTransport()
{
Cursor cursor=db.query(TABLE_TRANSPORT, null, null, null, null, null, "RANDOM()limit 1");
if (cursor!=null&&cursor.moveToFirst())
{
cursor.moveToFirst();
}
else
{
cursor=null;
}
return cursor;
}
And here is the code in the "frmAddEvent2" class:
double TotalTransportCost;
if (providingtransport==true)
{
int peopletotransport=noOfPeople;
TotalTransportCost = 0;
do
{
int eventtransportid=createEventTransportId();
Cursor ModeOfTransport = DatabaseHandler.getRandomTransport();
if (ModeOfTransport.moveToFirst()) {
int transportid=ModeOfTransport.getInt(ModeOfTransport.getColumnIndex(
DatabaseHandler.COLUMN_TRID));
double PriceForHiring = ModeOfTransport.getDouble(ModeOfTransport.getColumnIndex(
DatabaseHandler.COLUMN_HCOST));
double PricePerMile = ModeOfTransport.getDouble(ModeOfTransport.getColumnIndex(
DatabaseHandler.COLUMN_MCOST));
int NoOfSeats = ModeOfTransport.getInt(ModeOfTransport.getColumnIndex(
DatabaseHandler.COLUMN_SEATNO));
double ModeCost = ((PricePerMile*distancefrombase)+PriceForHiring);
eventTransportDetails eventtransport = new eventTransportDetails(eventtransportid,
id, transportid);
DatabaseHandler.createEventTransport(eventtransport);
BigDecimal bigdecimalmodecost=new BigDecimal(ModeCost);
BigDecimal bigdecimalpropermodecost=((bigdecimalmodecost.setScale(2,bigdecimalmodecost.ROUND_DOWN)));
double propermodecost=bigdecimalpropermodecost.doubleValue();
TotalTransportCost = TotalTransportCost + propermodecost;
peopletotransport = (peopletotransport-NoOfSeats);
ModeOfTransport.close();
}
else
{
Toast.makeText(
context,
"Error - you have not added any lunches, therefore food " +
"cannot be added.",
Toast.LENGTH_SHORT
).show();
return;
}
}
while (peopletotransport>0);
}
else
{
TotalTransportCost=0;
}
I was wondering if anybody could point me in the right direction?
Also, feel free to suggest any improvements to my question - as stated, a lot of this is new to me, so I may have left out some pretty important material.
Ok, so as it turns out, I put "db.close();" after a few of the functions in databaseHandler - by removing all of these, I fixed the problem. If you think this question would be better off not on the site, let me know and I'll delete it. Thanks though to all who commented.

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.

NullPointerException in my AsyncTask

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

retriving stock quote with yahoo finance

i have this form with a button upon submit i retrieve stock info from yahoo finance api, and use it to display onto three textviews
the url i use
http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2
and my button event handler is
URL url;
try {
url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2");
InputStream stream = url.openStream();
BufferedInputStream bis = new BufferedInputStream(stream);
ByteArrayBuffer bab = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
bab.append((byte) current);
}
String stockTxt = new String(bab.toByteArray());
String[] tokens = stockTxt.split(",");
String stockSymbol = tokens[0];
String stockPrice = tokens[1];
String stockChange = tokens[2];
String fstockSymbol = stockSymbol.substring(1, stockSymbol.length() -1);
String fstockChange = stockChange.substring(1, stockChange.length()-3);
symbolOut.setText(fstockSymbol);
priceOut.setText(stockPrice);
changeOut.setText(fstockChange);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
so what i noticed till the first line there seems to be no problem i.e url = new URL...,(even the bare http request done through browser, does return the info i need )
and my manifest entry looks like
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
below is the logcat output
05-02 18:36:32.804: D/AndroidRuntime(902): Shutting down VM
05-02 18:36:32.804: W/dalvikvm(902): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-02 18:36:33.113: E/AndroidRuntime(902): FATAL EXCEPTION: main
05-02 18:36:33.113: E/AndroidRuntime(902): android.os.NetworkOnMainThreadException
05-02 18:36:33.113: E/AndroidRuntime(902): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByName(InetAddress.java:220)
05-02 18:36:33.113: E/AndroidRuntime(902): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
so anybody knows where im going wrong
This is the key error in your LogCat message --> android.os.NetworkOnMainThreadException. You should move your network access to a background thread. You can use either an IntentService, AsynchTask, Handler, etc. to accomplish this.
Check out http://developer.android.com/training/articles/perf-anr.html for more information about why it is important to do network ops on a separate thread.

Categories