1

I am trying to get the IP address of the android device using an API from ipify. I tried using the API suggested in https://www.ipify.org/. It is simple.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.ramesh.getipaddress">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
     App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>

    </application>

</manifest>



import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public void onClick(View v) {


        Log.i("Test", "End");

        new networkingTask().execute();

        //getContents("http://localhost:8080");


        Log.i("Error", "Error1");
    }

}

 class networkingTask extends AsyncTask<String, String,String> {
    protected String doInBackground(String... urls) {
        //now call your ipify method which is doing the networking or calling a method that might be doing the networkign

        //getContents("http://localhost:8080");

        getipify();

        return null;
    }

     public void getipify() {

        try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("https://api.ipify.org").openStream(), "UTF-8").useDelimiter("\\A")) {
            System.out.println("My current IP address is " + s);
        } catch (java.io.IOException e) {
            System.out.println("======");
            System.out.println(e);
            System.out.println("======");

        }


         Log.i("Test","====TEST====");
     }

}

For some reason it wont open the stream. I get the error

java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick

I have used this method in swift and it works just fine. I have looked at all other methods but this appears easy.

Error section from Android Studio: --------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.ramesh.getipaddress, PID: 2381 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ramesh.getipaddress/com.example.ramesh.getipaddress.MainActivity}: android.os.NetworkOnMainThreadException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) 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) Caused by: 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)

Any help will be greatly appreciated.

Thanks

Ramesh

Ram Ramesh
  • 169
  • 1
  • 2
  • 9
  • Issue doesn't seem to be with this API but it seems to be with your onClickListener. Please provide the complete code and line number where you are receiving the error. – java_doctor_101 Dec 07 '16 at 03:38
  • Added, the rest of the code and the error section as per request. Appreciate your help. – Ram Ramesh Dec 07 '16 at 12:42

1 Answers1

0

Going through your full code looks like your acitivty is crashing because you are attempting to perform a network call on the main thread. You must do the networking in a background thread. You can and should use async task to achieve this:

You code will look like this:

Update: For the second error: do this:

 // just make sure to replace button with the id of your button
 Button b = (Button) findViewById(R.id.button);

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        new networkingTask().execute();
        }
    });

public void onClick(View v) {

        Log.i("Test", "End");
        Log.i("Error", "Error1");

new networkingTask().execute();

    } 

//create a asynctask class:

private class networkingTask extends AsyncTask<String, String,String> {
     protected String doInBackground(String... urls) {
       //now call your ipify method which is doing the networking or calling a method that might be doing the networkign

        //getContents("http://localhost:8080");

                   getipify();

      return null;
     }

}
java_doctor_101
  • 3,287
  • 4
  • 46
  • 78
  • FATAL EXCEPTION: main Process: com.example.ramesh.getmyip1, PID: 2561 java.lang.IllegalStateException: Could not find method onClick (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button1' – Ram Ramesh Dec 07 '16 at 19:21
  • Same issue I am facing. If I simply use onClick and put a print statement, it works fine every time. Onlly with the network stuff, it is giving errors – Ram Ramesh Dec 07 '16 at 19:22
  • It is working for me just fine. The first error was coming because you were calling geipify() method in the main thread. With above changes first error should be resolved. This new error is coming the method name in your layout.xml file. I have updated my answer – java_doctor_101 Dec 07 '16 at 19:28
  • Thanks for your help. I should be able to call this directly from the onCreate() as well ? I.e without using a user to click the button? – Ram Ramesh Dec 07 '16 at 19:45
  • Yeah. absolutely. no button clicked needed just call new networkingTask().execute(); from onCreate – java_doctor_101 Dec 07 '16 at 19:46
  • Since you mentioned async task, I am working on a project where I need to do several tasks asynchronously. For eg, check network, send email, send sms, make a call, writing to SQL Db - all these at certain time intervals. I have been trying to use Job Scheduler or is there a simpler way of doing these tasks async without user intervention. – Ram Ramesh Dec 07 '16 at 20:58
  • Thanks much. It works now. Hopefully you will have some time to respond to my earlier query on JobScheduler. – Ram Ramesh Dec 07 '16 at 23:02
  • Sorry, I am really new to stackoverflow.com. How do I return the IP to the main function where I am calling "new networkingTask().execute()" ? thanks – Ram Ramesh Dec 08 '16 at 01:28
  • check out this answer to know how to receive a string back from async task http://stackoverflow.com/a/33182711 Also, for your other follow up question I would advice creating a different question with more specific details but in general you should use async task for all networking related stuff – java_doctor_101 Dec 08 '16 at 02:22
  • Thanks for the tip.. I will create a new question. – Ram Ramesh Dec 08 '16 at 03:31
  • Thanks again. The return to main worked every well !! It was simple as well. – Ram Ramesh Dec 08 '16 at 04:14