我有一个项目,我想编写一些使用 Internet 服务从MySQL服务器获取数据的函数。这些函数位于一些非活动类中。我打算从不同的活动中调用这些函数。我AsyncTask用来发出HTTP请求。以下是我设计的骨架。
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 ... */
}
}
}
我的活动将访问该课程,如下所示。
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 */
}
}
任何建议都会对我有很大帮助。由于我是新手,这可能是一个愚蠢的问题,但我的概念是重用代码。
UYOU
红颜莎娜
相关分类