Issue
I have a project where I want to write some functions that use internet service to get the data from the MySQL
server. These functions are inside some non-activity classes. I intend to call these functions from different activities. I use AsyncTask
to make HTTP requests. Following is the skeleton of my design.
public class MyLibrary{
String myData;
protected String getMyData(String param){
HashMap<String, String> params = new HashMap<>();
params.put("param1", apicall);
params.put("param2", param);
MyAsyncClass myAsyncClass = new MyAsyncClass(params);
myAsyncClass.execute();
/* Here after finishing the task I want to return the data to the caller */
return myData;
}
private class MyAsyncClass extends AsyncTask<String, Integer, String> {
MyAsyncClass(HashMap<String, String> params) {
this.postData = params;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
RequestHandler requestHandler = new RequestHandler();
return requestHandler.sendPostRequest(GlobalConstants.myurl, postData);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* parse code here ... */
}
}
}
This class will be accessed by my activities like following.
public class SampleActivity extends AppCompatActivity{
String returnedData;
@Override
protected void onCreate(Bundle savedInstanceState) {
MyLibrary myLibraryObject = new MyLibrary();
returnedData = myLibraryObject.getMyData("cih");
/* do something with returnedData */
}
}
Any suggestions would be a huge help to me. As I am a novice, this might be a stupid question, but my concept is to reuse codes.
Solution
if your planning to do this asynchronous manner then you should use a interface as callback or u can get result by calling get method in AsyncTask
protected String getMyData(String param){
HashMap<String, String> params = new HashMap<>();
params.put("param1", apicall);
params.put("param2", param);
MyAsyncClass myAsyncClass = new MyAsyncClass(params);
myData= myAsyncClass.execute().get();
/* Here after finishing the task I want to return the data to the caller */
return myData;
}
Answered By - Geo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.