我有一个项目,我想编写一些使用 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 */ } }任何建议都会对我有很大帮助。由于我是新手,这可能是一个愚蠢的问题,但我的概念是重用代码。
2 回答
UYOU
TA贡献1878条经验 获得超4个赞
如果您打算采用这种异步方式,那么您应该使用接口作为回调,或者您可以通过调用 AsyncTask 中的 get 方法来获取结果
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;
}
添加回答
举报
0/150
提交
取消