Answer the question
In order to leave comments, you need to log in
How to call a function from a class by reference to the class?
There is a MainActivity and an API class.
When an activity starts, 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 MainActivity class and context are given.
How can onRequestEnd() be called from the API, given that the API can also be accessed 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
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question