How to fix java.lang.IllegalStateException - java

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.

Related

Xamarin.Android app reported crash with java.lang.reflect.InvocationTargetException Exception

First upon all this is not a duplicate question or have been answered on stackoverflow or xamarin forums. On xamarin forums this problem/question is still under discussion so i have posted it here.
So the problem with my app and also bunch of others which have been developed in Xamarin.Android reporting crashes (opt-in and opt-out) on Google's play console.
App actually not crashing. It just reporting automated crash reports to Google's play console.
Following is crash Stack Traces for Android 6.0 and 7.0 :
java.lang.RuntimeException:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException:
at java.lang.reflect.Method.invoke(Native Method:0)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:726)
In Android 5.1 and 5.0 :
java.lang.RuntimeException:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.reflect.InvocationTargetException:
at java.lang.reflect.Method.invoke(Native Method:0)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
For Android 4.2 and 4.4 :
java.lang.RuntimeException:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method:0)
Caused by: java.lang.reflect.InvocationTargetException:
at java.lang.reflect.Method.invokeNative(Native Method:0)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
Seems this exception occurring majorly in Android 6.0 and 7.0. Above is the only stack traces google play console provided for my and other developers app. There is not any detailed trace available yet.
For my app, crash reported whenever notification received on app. It impacting all of the app users at exact same time when they received notification.
Images of crash reports at the time of notification recieved
Following is the my FCM code :
MainActivity :
Task.Run(() =>
{
var instanceid = FirebaseInstanceId.Instance;
instanceid.DeleteInstanceId();
Log.Debug("TAG", "{0} {1}", instanceid.Token, instanceid.GetToken(this.GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));
});
Token Registration :
[Service]
[IntentFilter(new[] {
"com.google.firebase.INSTANCE_ID_EVENT"
})]
class MyFirebaseIIDService : FirebaseInstanceIdService
{
const string TAG = "MyFirebaseIIDService";
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
Log.Debug(TAG, "Refreshed token: " + refreshedToken);
SendRegistrationToServer(refreshedToken);
}
void SendRegistrationToServer(string token) { }
}
OnMessageReceived :
[Service]
[IntentFilter(new[] {
"com.google.firebase.MESSAGING_EVENT"
})]
class MyFireMessagingService : FirebaseMessagingService
{
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
var title = string.Empty;
if (message.Data.Count > 0)
{
//Log.Debug(Tag, "Message data payload: " + message.Data);
title = message.Data["title"];
}
SendNotificatios(title);
}
public void SendNotificatios( string Header)
{
Notification.Builder builder = new Notification.Builder(this);
builder.SetSmallIcon(Resource.Drawable.Icon);
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
builder.SetContentIntent(pendingIntent);
// builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon));
builder.SetContentTitle(Header);
builder.SetPriority(1);
builder.SetContentText("read more..");
builder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
builder.SetSound(Android.Net.Uri.Parse("android.resource://" + Application.PackageName + "/" + Resource.Raw.demonstrative));
builder.SetAutoCancel(true);
Random r = new Random();
int uniw = r.Next(1, 10);
NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(uniw, builder.Build());
}
}
Note : Notification works fine, just whenever notification arrived app reported crash to Google play console.
Please if anyone have any knowledge related to this problem will be helpful. TIA

Checking for internet connectivity in Android app [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
I'm trying to check for INTERNET connectivity from an Android app but just keep running in to problems.
I'm NOT looking for code that tests for an available network connection - I've got that bit working - this is to test whether I can reach an internet site or not.
(I appreciate that if I am behind a system which presents a logon screen instead of the requested site, I may not get the exact result I want, but I will handle that later)
Thanks to the following question I think I've made some progress, but when I run the app it crashes out (error info below).
The code I have so far is as follows (and I must admit that I find the try/catch stuff a bit puzzling and tedious :-/ )
static public boolean isInternetReachable() {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
I'm sure there are neater ways to do this and so any general advice is welcome.
The error that I'm getting when the app crashes is:
01-24 19:53:14.767 10617-10617/com.nooriginalthought.bluebadgeparking E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.nooriginalthought.bluebadgeparking, PID: 10617
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nooriginalthought.bluebadgeparking/com.nooriginalthought.bluebadgeparking.PreLoadChecks}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1155)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:236)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.isInternetReachable(PreLoadChecks.java:41)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.onCreate(PreLoadChecks.java:70)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:155) 
at android.app.ActivityThread.main(ActivityThread.java:5696) 
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:1028) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 
As David is mentioning in the comments, you should just Google for the Exception name and try to get a turnaround by yourself.
By looking at the StackOverflow answer that he is referring to, you need to make all network communications outside the Main thread. The most used way to do this is by creating an AsyncTask.
In your case, it would look (you can create a new InternetTask.java or just append it to your current MainActivity.java) something like:
class InternetTask extends AsyncTask<Void, Void, Boolean>{
private MainActivity activity;
InternetTask(MainActivity activity){
this.activity = activity;
}
#Override
protected Boolean doInBackground(Void... params) {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
activity.receiveMagic(aBoolean);
}
}
Then, you just need to add a new public method in your activity to receive the boolean in your MainActivity.
public void receiveMagic(Boolean isGood){
if (isGood){
Toast.makeText(MainActivity.this, "It is good", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "It is not connected", Toast.LENGTH_SHORT).show();
}
}
And you would need to call your new AsyncTask from your Activity with:
new InternetTask(this).execute();
Make sure you add the internet permission to your Manifest also.

Android FTP connection problems [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
Hi I have been trying for two days to get a simple ftp connection to transfer a small xml file. I have tried lots of different examples of code, but all seem to give the same errors.
Main FTP class code:
public class MyFTPClientFunctions {
public FTPClient mFTPClient = null;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
//Log.d(TAG, "Error: could not connect to host " + host);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private Context getApplicationContext() {
return null;
}
}
Main Activity code to send
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set up FTP file transfer here
MyFTPClientFunctions ftpSend = new MyFTPClientFunctions();
ftpSend.ftpConnect("xxxxxx.asuscomm.com","admin","xxxxxxxxxx",21);
}
LogCat messages
06-22 12:09:21.460 17329-17329/com.example.rats.moham_2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rats.moham_2, PID: 17329
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getByName(InetAddress.java:305)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
at com.example.rats.moham_2.MyFTPClientFunctions.ftpConnect(MyFTPClientFunctions.java:25)
at com.example.rats.moham_2.MainActivity$3.onClick(MainActivity.java:155)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This Exception is usualy thrown, if you are using the network on the main thread.
Please use Async Tasks.

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