-1

The problem is to return the public ip address for a given device. The easiest way to do this is to send a request to a website which returns the Ip. In the following method the url provided will send you the json object of your public ip address which will return a string, the problem might be with the connection to the website within android studio because it works fine in regular notepad++ and my cmd.

The method is

    public String getIP(){
    String out = "";
    try{
        out = new Scanner(new URL("https://api.ipify.org/?format=json").openStream(), "UTF-8").useDelimiter("\\A").next();
    }catch(MalformedURLException e){
        System.out.println(e);
    }catch(IOException e){
        System.out.println(e);
    }
    return out;
}

my entire stack trace is

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.matthewr.aiwlayout, PID: 2303
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matthewr.aiwlayout/com.example.matthewr.aiwlayout.MainFeed}: android.os.NetworkOnMainThreadException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                  at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
                  at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
                  at java.net.InetAddress.getAllByName(InetAddress.java:752)
                  at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
                  at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:187)
                  at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:156)
                  at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:98)
                  at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:345)
                  at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
                  at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
                  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
                  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
                  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
                  at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
                  at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
                  at java.net.URL.openStream(URL.java:1057)
                  at com.example.matthewr.aiwlayout.TownieDBHandler.getIP(TownieDBHandler.java:121)
                  at com.example.matthewr.aiwlayout.TownieDBHandler.databaseToString(TownieDBHandler.java:89)
                  at com.example.matthewr.aiwlayout.MainFeed.printDatabase(MainFeed.java:56)
                  at com.example.matthewr.aiwlayout.MainFeed.onCreate(MainFeed.java:39)
                  at android.app.Activity.performCreate(Activity.java:6662)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                  at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
theplaid
  • 69
  • 1
  • 7

1 Answers1

0

As the Exception states NetworkOnMainThreadException you're trying to call a network task on your main thread which will cause a lag on the UI, This should be done using another thread or Using AsyncTasks

Update

Here is how you solve this error using Asynctask

class RetrieveIP extends AsyncTask<String, Void, String> {

    private Exception exception;

    protected String doInBackground(String... urls) {
        try {
             return new Scanner(new URL("https://api.ipify.org/?format=json").openStream(), "UTF-8").useDelimiter("\\A").next();
        } catch (Exception e) {
            this.exception = e;
            return null;
        } 
    }

    protected void onPostExecute(String out) {
        // TODO: check this.exception
        // TODO: do something with the string url out you got from the api
    }
}

How to execute the task:

In MainActivity.java file you can add this line within your oncreate() method

new RetrieveIP().execute("");

Don't forget to add this to AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
Ismail Iqbal
  • 2,774
  • 1
  • 25
  • 46
  • can you give an example of how I would implement that? – theplaid Jan 20 '18 at 21:18
  • I have update the answer with the code, as @Kling Klang marked this as duplicate, make sure to do some research on your problem before posting it to SO. Some good tips from jonSkeet on posting question can be found on the link below, Read it before posting a question https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/ – Ismail Iqbal Jan 21 '18 at 05:15