[英]How to return anonymous List or ArrayList on AsyncTask in Android
完成AsyncTask
后,我有6種不同類型的List
結果。 並且List
結果應該返回給Activity
。 例如: List<A>
, List<B>
, List<C>
, List<D>
, List<E>
,最后是List<F>
。
這是我的AsyncTask
:
public class myAsync extends AsyncTask<String, String, List> {
private List resultList;
@Override
protected List doInBackground(String... params) {
//params[0] is url
//params[1] is type
callAPI api = new callAPI(params[0], params[1]);
// According to type api decides type of List and generates
return api.getJSON(); // returns a List which already parse JSON
}
@Override
protected void onPostExecute(List result) {
// Result is here now, may be 6 different List type.
this.resultList = result
}
// returns result
public List getResultList() { return this.resultList; }
}
我會像這樣調用AsyncTask:
myAsync task = new myAsync();
task.execute(params);
List myList = task.getResultList(); // type is uncertain
Log.d("Tag", Integer.toString(myList.size());
你知道,我必須指出<>標簽之間的返回類型(Result)。 如果我為List
選擇特定類型,則它不適用於其他類型。
實際上,我已經嘗試返回List<Object>
並且只返回List
類型。 但是沒有用。
我不想使用6種不同的Async
。 是否有可能只用AsyncTask
來解決這個問題? 我想我需要匿名列表或類似的東西不確定。 有誰能解釋一下?
首先,我應該指出,您獲取列表的順序是不正確的。 讓我來證明:
// Initialize myAsync
myAsync task = new myAsync();
// This will do work for some period of time, this statement DOES NOT 'block'
// till myAsync completes, it will run it in the background
task.execute(params);
// This will return null because by the time you get here, task.execute most
// likely hasn't finished yet.
task.getResultList();
編輯:現在您已經包含了要對列表結果執行的操作,以下是如何修改onPostExecute
方法:
@Override
protected void onPostExecute(List result) {
Log.d(TAG, "The returned list contains " +result.size()+ "elements");
// Do anything else you need to with the returned list here
}
總而言之,如果您需要對返回的列表執行任何其他操作(除了打印它們的大小),例如比較,打印項目等,您需要在onPostExecute
方法中執行此onPostExecute
。
根據列表的內容(A,B,C等),您可以為它們創建一個界面。
因此,如果A,B,C等是對象,則可以創建一個我們稱之為ListContentInterface的接口。 然后,每個元素都必須實現ListContentInterface。 然后,您可以將類型指出為:
List<ListContentInterface>.
之后,您可以通過獲取列表的第一個元素並檢查它的類來測試列表內容的真正含義:
if(element.getClass() == ClassToTestFor.class) ...
如果對象有任何共同的方法,則應在界面中指定它們。 如果它們具有共同的ALL方法,則可以直接使用List列表,而無需測試對象的類(因為它們都可以執行接口定義的操作)。
我希望這對你有意義。 它可能不是最好的接口使用或最佳解決方案,但它可能會解決您的問題。
我正在使用execute()解決這類問題.get();
例
call from activity
ArrayList<String> arraylistitem= new jsonparsing(getActivity()).execute().get();
In async task
public class jsonparsing extends AsyncTask<Void, Void, ArrayList<String>>
{
public jsonparsing(Activity activity)
{
this.activity = activity;
arraylistitem = new ArrayList<String>();
}
protected ArrayList<String> doInBackground(Void... arg0)
{
// Do anything else you need to with the returned list here
return arraylistitem;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.