There is a MainActivity and API class.

When running activity, a request is sent to the server. After sending the request, you need to return the result to the onRequestEnd function in MainActivity.

In the API, when the class is initialized, the class and context MainActivity is given.

How can I call onRequestEnd () from the API, given that the API can be accessed in the same way from different activities and always return the result in onRequestEnd ()?

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); API API = new API(MainActivity.class, MainActivity.this); API.request("getStartData"); } public void onRequestEnd(String result) { showToast("request end"); } void showToast(final String text) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show(); } }); } } 

 public class API { private static Context context = null; private static Class callbackClass = null; public API(Class cls, Context cntxt){ context = cntxt; callbackClass = cls; } public void request(String method) { new Request().execute(method); } public class Request extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { //запрос к api } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // вызов MainActivity.onRequestEnd } } } 

    1 answer 1

     public interface Callback { void onRequestEnd(String result); } public class MainActivity extends AppCompatActivity implements Callback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); API api = new API(this); api.setCallback(this); api.request("getStartData"); } @Override public void onRequestEnd(String result) { showToast("request end"); } ... } public class API { private static Callback callback; public void setCallback(Callback callback){ this.callback = callback; } @Override protected void onPostExecute(String result) { callback.onRequestEnd(result); } } 
    • An example call in MainActivity.onCreate () is possible? - d_reseller
    • one
      You can, there is one line to add in your code and all in fact. - yno7