![](/img/trans.png)
[英]How to pass application context from main activity to a class that implements async task to attach adapter from onPostExecute() in async task?
[英]How to pass data from Async Class to Main Activity class
我有轉換為JSONArray
JSON數據。 我已經在擴展AsyncTask
的內部類中執行了此轉換。
現在我有包含Images
及其Titles
。 我想創建一個Loop並動態創建ImageView
。
我面臨的問題是我的數據在內部類和doInBackground()
方法中,以及其他內容中; 即:我需要創建的ImageView
在外部類和onCreate()
方法中。
我無法理解如何使用jsonArray
我在我的創建InnerClass
在我的外部類。
內部艙位:
公共類NewsService擴展了AsyncTask {
@Override
protected JSONArray doInBackground(String... params) {
URL url = null;
try {
//All JSON to JSONArray conversion code goes here
//..
JSONArray jsonArray = new JSONArray(jsonString);
return jsonArray;
主要活動
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NewsService newsService = new NewsService();
newsService.execute();
//I need to use `jsonArray` in this part of my code
對於您的問題,我有很多解決方案。
最重要的是,您將活動類的上下文作為異步任務類的數據成員傳遞,然后在onPostExecute中完成工作時
(((YourActivityName)context).createDynamicImages(yourJsonArray);
在此之前,您需要將活動的上下文另存為異步任務類的數據成員
YourAsyncTask task = new YourAsyncTask(this);
task.execute();
因此您的異步任務類的構造函數將變為
public YourAsyncTask(Context context){
this.context = context;
}
一種簡單的方法是將interface
定義為AsyncTask
的回調。 這是一個例子:
public interface Callback {
void processData(DataType data);
}
在您的MainActivity
您應該implement
該interface
:
public class MainActivity extends Activity implements Callback {
...
void processData(DataType data) {
//your code here
}
}
並在您的調用代碼中:
new NewService(this).execute();
和您的NewService
類:
public class NewService extends AsyncTask ... {
...
Callback cb;
public NewService(Callback cb) {
this.cb = cb;
}
...
}
並在onPostExecute
調用您的Callback
方法
void onPostExecute(DataType data) {
cb(data);
}
AsynTask.doInBackground
在Background上運行,而不是在主線程上運行,因此,如果要在主線程上處理數據(包括UI更新),則應使用onPostExecute
(此方法在任務完成后運行) ,可以使用AsyncTask
類內部的interface
:
interface OnJsonArrayReceive {
void onReceive(JSONArray array);
}
AsyncTask
類將如下所示:
class SomeTask extends AsyncTask<String, Void, JSONArray> {
OnJsonArrayReceive mOnJsonArrayRecieve;
public SomeTask(OnJsonArrayRecieve listener) {
mOnJsonArrayRecieve = listener;
}
@Override
protected JSONArray doInBackground(String... params) {
//do something with and return your array
//this runs on background
return jsonArray;
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
//This runs on main thread
if (mOnJsonArrayReceive != null) {
mOnJsonArrayReceive.onReceive(jsonArray);
}
}
}
此類使用OnJsonArrayRecieve
偵聽器作為參數(在MainActivity
實現),並且在完成后台數據處理onRecieve
將在其代碼中使用它,如下所示:
new SomeTask(new OnJsonArrayRecieve() {
@Override
public void onReceive(JSONArray array) {
//do something with json array
}
}).execute(someArgument);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.