Search code examples
androidapiandroid-asynctaskgeonames

I am unable to get the City name from postal code using Geonames API


I am trying to search or get the City name from Postal Code using the Geonames API.

However, I am getting a null value expectation.

Below is the code where I get the Postal Code and I have passed it to the AsyncTask to do in the Background

private void sharedPreferenceCreate(final String userAddress, Double latitude, Double longitude, Intent data) throws Exception {

    final String City;
    final String Country;
    final String State;

    Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
    List<Address> addresses = null;

    try {
        addresses = gcd.getFromLocation(latitude, longitude, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (addresses.size() > 0) {

        City= addresses.get(0).getLocality();
        Country= addresses.get(0).getCountryName();
        State= addresses.get(0).getAdminArea();
        String q=addresses.get(0).getSubLocality();
        String w=addresses.get(0).getFeatureName();
        String e=addresses.get(0).getPostalCode();  //Here I get the Postal code
        String r=addresses.get(0).getSubAdminArea();
        String t=addresses.get(0).getPremises();
        String g= e+"&country=";

        urlBackground background= new urlBackground();

        background.doInBackground(e);
        background.execute();

        Log.i(TAG, "sharedPreferenceCreate: "+city);

        distanceRestaurant(latitude,longitude, City,Country,State);
              }).show();

    }
    else {
        Toast.makeText(this, "Unable to fetch your location, try again", Toast.LENGTH_SHORT).show();
    }
}

Here is my AsyncTask Class

public class urlBackground extends AsyncTask<String, Void, String> {

    String result;

    public urlBackground() {
    }

    @Override
    protected String doInBackground(String... strings) {

        WebService.setUserName("Jack"); // add your username here

        ToponymSearchCriteria searchCriteria = new ToponymSearchCriteria();
        searchCriteria.setQ(String.valueOf(strings));
        ToponymSearchResult searchResult = new ToponymSearchResult();

        try {
            searchResult = WebService.search(searchCriteria);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (Toponym toponym : searchResult.getToponyms()) //When I run the Code it skip this line IDK Why?? 
              {
            System.out.println(toponym.getName()+" "+ toponym.getCountryName());

            try {
                result= toponym.getAdminCode3();
            } catch (InsufficientStyleException e) {
                e.printStackTrace();
            }
        }

        return result; // I get null Value
    }
}

When I use the WebSite Geonames.org and search for the City name from the Postal Code I am able to get it.

Can anyone help me!! It's like 2 days I have tried to do but still, I get a null reference

StackTrace

2020-06-18 17:39:08.171 18749-18749/com.chonang.main D/VanillaMapActivity: AddressResultReceiver.onReceiveResult: address: Pilongri Bhavan, Vaikang Road, Rongkhelan, Diphu, Assam 782460, India
2020-06-18 17:39:09.682 18749-19054/com.chonang.main D/FetchAddressIntentService: Addresses >> [{}]
2020-06-18 17:39:09.683 18749-19054/com.chonang.main I/FetchAddressIntentService: Address found
2020-06-18 17:39:09.684 18749-18749/com.chonang.main D/VanillaMapActivity: AddressResultReceiver.onReceiveResult: address: NH329, Assam 782460, India
2020-06-18 17:39:18.957 18749-18749/com.chonang.main W/om.chonang.mai: Got a deoptimization request on un-deoptimizable method java.net.InetAddress[] libcore.io.Linux.android_getaddrinfo(java.lang.String, android.system.StructAddrinfo, int)
2020-06-18 17:39:18.958 18749-18749/com.chonang.main W/System.err: android.os.NetworkOnMainThreadException
2020-06-18 17:39:18.959 18749-18749/com.chonang.main W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
2020-06-18 17:39:18.960 18749-18749/com.chonang.main W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
2020-06-18 17:39:18.961 18749-18749/com.chonang.main W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
2020-06-18 17:39:18.962 18749-18749/com.chonang.main W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:1152)
2020-06-18 17:39:18.962 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.Dns$1.lookup(Dns.java:41)
2020-06-18 17:39:18.963 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
2020-06-18 17:39:18.964 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
2020-06-18 17:39:18.965 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
2020-06-18 17:39:18.966 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
2020-06-18 17:39:18.967 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
2020-06-18 17:39:18.968 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
2020-06-18 17:39:18.969 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
2020-06-18 17:39:18.970 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
2020-06-18 17:39:18.971 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
2020-06-18 17:39:18.972 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
2020-06-18 17:39:18.973 18749-18749/com.chonang.main W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
2020-06-18 17:39:18.974 18749-18749/com.chonang.main W/System.err:     at org.geonames.WebService.connect(WebService.java:235)
2020-06-18 17:39:18.974 18749-18749/com.chonang.main W/System.err:     at org.geonames.WebService.connectAndParse(WebService.java:302)
2020-06-18 17:39:18.975 18749-18749/com.chonang.main W/System.err:     at org.geonames.WebService.search(WebService.java:1292)
2020-06-18 17:39:18.976 18749-18749/com.chonang.main W/System.err:     at com.chonang.main.MainActivity$urlBackground.doInBackground(MainActivity.java:344)
2020-06-18 17:39:18.977 18749-18749/com.chonang.main W/System.err:     at com.chonang.main.MainActivity.sharedPreferenceCreate(MainActivity.java:283)
2020-06-18 17:39:18.978 18749-18749/com.chonang.main W/System.err:     at com.chonang.main.MainActivity.onActivityResult(MainActivity.java:142)
2020-06-18 17:39:18.978 18749-18749/com.chonang.main W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:8135)
2020-06-18 17:39:18.980 18749-18749/com.chonang.main W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4955)
2020-06-18 17:39:18.981 18749-18749/com.chonang.main W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:5003)
2020-06-18 17:39:18.982 18749-18749/com.chonang.main W/System.err:     at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
2020-06-18 17:39:18.983 18749-18749/com.chonang.main W/System.err:     at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
2020-06-18 17:39:18.983 18749-18749/com.chonang.main W/System.err:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
2020-06-18 17:39:18.984 18749-18749/com.chonang.main W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
2020-06-18 17:39:18.985 18749-18749/com.chonang.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:107)
2020-06-18 17:39:18.985 18749-18749/com.chonang.main W/System.err:     at android.os.Looper.loop(Looper.java:214)
2020-06-18 17:39:18.986 18749-18749/com.chonang.main W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7682)
2020-06-18 17:39:18.986 18749-18749/com.chonang.main W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2020-06-18 17:39:18.987 18749-18749/com.chonang.main W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
2020-06-18 17:39:18.988 18749-18749/com.chonang.main W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)`

I have made some changes but still, I get null.

Here is my updated Code

 @Override
    protected String doInBackground(String... strings) {

         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        SharedPreferences sharedPreferences= getSharedPreferences("POSTAL",MODE_PRIVATE);
        String code= sharedPreferences.getString("postal","");

        WebService.setUserName("jack"); // add your username here

        String result= new String();

        ToponymSearchCriteria searchCriteria= new ToponymSearchCriteria();
        searchCriteria.setQ(code);

        ToponymSearchResult searchResult = new ToponymSearchResult();
        try {
            searchResult = WebService.search(searchCriteria);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (Toponym tp: searchResult.getToponyms()){

            result= tp.getAdminName3();
            Log.i(TAG, "doInBackground: city name is "+ result);
        }

        Log.i(TAG, "doInBackground: postal Admin3 name is"+ result);


        return result;// ignore this value!!
    }

However, when I search the result on Web I get the Result:

enter image description here


Solution

  • I want to thanks everyone who has tried giving me the answer. Unfortunately, I didn't get the answer. However, after two days of struggle, I was finally able to get the required result. With the Postal code, I was able to get the City name.

    The above which I have added was right nothing was wrong but due to Strick mode I was unable to fetch it. But still, there is a catch, where instead of ToponmySearch, I have used the below code:

    PostalCodeSearchCriteria codeSearchCriteria= new PostalCodeSearchCriteria();
                codeSearchCriteria.setPostalCode("<Past_Your_postal_code_here>");
        List<PostalCode> postalCodes= WebService.postalCodeSearch(codeSearchCriteria);
                    String ci= postalCodes.get(0).getAdminName3(); //CityName
                    String cq= postalCodes.get(0).getAdminCode1();//StateName
                    String cw= postalCodes.get(0).getAdminName2();//DistrictName
                    String ce= postalCodes.get(0).getPlaceName();//PlaceName and etc many more you cam call there.```
    
    

    I hope it will helps all the other those who want the City name from postal code. However, you have to have an account in GEONAMES.ORG, and you have activate the free service option. After that you will be able to get the required values which you need from postal code. YOu have to use the Geonames API for that.

    Thank you!!