-3

When my device Network Connect, execute AsyncTask. this AsyncTask is get Public Ip.

asyncTask in MainActivity (inner)

I want asyncTask result (result value is public Ip) value from another class.

How to get public ip from another class?

My source

public class MainActivity extends Activity {
   static getAsyncPubIp async = new getAsyncPubIp();

   public static final class getAsyncPubIp extends AsyncTask<Void, Void, String> {
       String result;
       TextView pubView;

       @Override
       public void onPreExecute() {
          super.onPreExecute();
       }

       @Override 
       protected String doInBackground(Void... params) {
           try {
               URL pub = new URL("get public ip domain");
               BufferedReader in = new BufferedReader(new InputStreamReader( 
                       pub.openStream()));

               String strPub = in.readLine();
               result = strPub;
           } catch (Exception e) {
                e.printStackTrace();
           }
         } 

         @Override
         protected void onPostExecute(String result) {
            super.onPostExecute(result);

            pubView = (TextView) activity.findViewById(R.id.ip);
            pubView.setText(result);

            async = null;
            pubView = null;
         }
     }     

usually, call this asynctask on another class

MainActivity.getAsyncPubIp asyncPub = new MainActivity.getAsyncPubIp(); asyncPub.execute();

but I want only asyncTask result value from another class

How to get this ?

hyunwooks
  • 141
  • 3
  • 14
  • 3
    Possible duplicate of [How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?](https://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a) – K Neeraj Lal Oct 12 '17 at 05:09
  • You can access object of other class in Async task using singleton. – Vasant Oct 12 '17 at 05:11
  • Through Interface you can get, define an interface in another class and implement that interface in your MainActivity – Yatish Oct 12 '17 at 05:12
  • use putextra or store shared preference and use in another class or use public static. – Kevan Aghera Oct 12 '17 at 06:01

1 Answers1

1

Create a static variable in second activity's java class named SecondClass.java:

public static String public_ip;

Then in your MainActivity:

    @Override
         protected void onPostExecute(String result) {
            super.onPostExecute(result);

            //Add this
            SecondClass.public_ip = result;

            pubView = (TextView) activity.findViewById(R.id.ip);
            pubView.setText(result);

            async = null;
            pubView = null;
         }
Saify
  • 469
  • 1
  • 5
  • 20