当前位置: 首页 > 知识库问答 >
问题:

如何在android中通过AsyncTask返回多个List?

越涛
2023-03-14

我创建了一个扩展AsyncTask的AsynTaskInsideActivity类

  • 位置\u id

我想从每一列中提取记录。因此,为了存储每个列的每个记录,我创建了四个类型数组(即每列一个),并成功地将检索到的光标数据存储在每个数组中。现在,问题是我需要返回每一列的记录。因此,具体地说,我如何从one-AsyncTask类返回这四个单独的List-type数组。目前,我只返回列表类型的数组,即locationId,它包含我从location表的location\u id列获取的所有location id。

问题:

  • 如何从单个AsyncTask类返回多个列表数组项?毕竟,在查询数据库时,有时我们需要来自单个表中多个列的记录来处理进一步的操作
  • 有没有更好的方法可以用来克服这个问题?或者我不得不相信有些事情真的是不可能的

这就是我的AsyncTask类的外观:

public class AsyncTaskInsideActivity extends AsyncTask<Void, Void, List<String>> {

private static final String CLASS_TAG = AsyncTaskInsideActivity.class.getSimpleName();

@Override
protected List<String> doInBackground(Void... params) {

    Log.v(CLASS_TAG, "AsyncTaskInsideActivity started successfully....");

    SoCalledDbHelper soCalledDbHelper = new SoCalledDbHelper
            (getBaseContext());

    //key-value pairs for inserting data into the table
    ContentValues soCalledValues = new ContentValues();
    soCalledValues.put(SoCalledContract.LocationTable.COLUMN_CITY_NAME, "Kim Kardishian");
    soCalledValues.put(SoCalledContract.LocationTable.COLUMN_STATE, "No Ass Holes");
    soCalledValues.put(SoCalledContract.LocationTable.COLUMN_ZIP_CODE, 007);

    //insert location data
    soCalledDbHelper.addLocationData(soCalledValues);
    //For storing the cursor data which will be retrieved by the read query.
    Cursor locationDataCursor;

    //Query for all the data in the location table
    locationDataCursor = soCalledDbHelper.getAllLocationData(null, null, null, null);

    List<String> sCLocationId = new ArrayList<String>();
    List<String> sCCityName = new ArrayList<String>();
    List<String> sCState = new ArrayList<String>();
    List<String> sCZipCode = new ArrayList<String>();

    if (locationDataCursor.getCount() > 0) {
        //Reset the cursor location
        locationDataCursor.moveToPosition(-1);
        while (locationDataCursor.moveToNext()) {
            //Extracting data from the location cursor
            sCLocationId.add(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("_id")));
            sCCityName.add(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("city_name")));
            sCState.add(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("state")));
            sCZipCode.add(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("zip_code")));
        }
        Log.i(CLASS_TAG, "Success: Cursor has data! #Total Records: " +
                locationDataCursor.getCount());
        for (String locationIds : sCLocationId) {
            Log.i(CLASS_TAG, "Location Id: + " + locationIds);
        }
        for (String cityNamez : sCCityName) {
            Log.i(CLASS_TAG, "City Names: + " + cityNamez);
        }
        for (String statesNames : sCState) {
            Log.i(CLASS_TAG, "State Names: + " + statesNames);
        }
        for (String zipCodes : sCZipCode) {
            Log.i(CLASS_TAG, "Zip Codes: + " + zipCodes);
        }
    } else {
        Log.w(CLASS_TAG, "Error: Cursor is empty! #Total Records: " +
                locationDataCursor.getCount());
    }
    locationDataCursor.close();
    soCalledDbHelper.close();
    Log.v(CLASS_TAG, "AsyncTaskDbHelper ended successfully....");
    return sCLocationId;
}

}

共有2个答案

单于扬
2023-03-14

好吧,在互联网上研究这个问题的解决方案并花了几个小时让单个AsyncTask返回多个值之后,我想出了一个带有嵌套列表的解决方案,即列表

原始学分:

@西蒙:谁给了我一个指示(或暗示),我如何更新我的异步任务来完成工作,这被证明是非常有用的
@VERT9x:感谢您付出了努力,并以不同的方式完成了工作。

解决方案:

public class AsyncTaskInsideActivity extends AsyncTask<Void, Void, List<List<String>>> {

    private static final String CLASS_TAG = AsyncTaskInsideActivity.class.getSimpleName();

    @Override
    protected List<String> doInBackground(Void... params) {

Log.v(CLASS_TAG, "AsyncTaskInsideActivity started successfully....");

SoCalledDbHelper soCalledDbHelper = new SoCalledDbHelper
        (getBaseContext());

//key-value pairs for inserting data into the table
ContentValues soCalledValues = new ContentValues();
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_CITY_NAME, "Kim Kardishian");
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_STATE, "No Ass Holes");
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_ZIP_CODE, 007);

//insert location data
soCalledDbHelper.addLocationData(soCalledValues);
//For storing the cursor data which will be retrieved by the read query.
Cursor locationDataCursor;

//Query for all the data in the location table
locationDataCursor = soCalledDbHelper.getAllLocationData(null, null, null, null);

List<String> sCLocationId = new ArrayList<String>();
List<String> sCCityName = new ArrayList<String>();
List<String> sCState = new ArrayList<String>();
List<String> sCZipCode = new ArrayList<String>();

if (locationDataCursor.getCount() > 0) {
    //Reset the cursor location
    locationDataCursor.moveToPosition(-1);
    while (locationDataCursor.moveToNext()) {
        //Extracting data from the location cursor
        sCLocationId.add(locationDataCursor.getString
                (locationDataCursor.getColumnIndex("_id")));
        sCCityName.add(locationDataCursor.getString
                (locationDataCursor.getColumnIndex("city_name")));
        sCState.add(locationDataCursor.getString
                (locationDataCursor.getColumnIndex("state")));
        sCZipCode.add(locationDataCursor.getString
                (locationDataCursor.getColumnIndex("zip_code")));
    }
    Log.i(CLASS_TAG, "Success: Cursor has data! #Total Records: " +
            locationDataCursor.getCount());
    for (String locationIds : sCLocationId) {
        Log.i(CLASS_TAG, "Location Id: + " + locationIds);
    }
    for (String cityNamez : sCCityName) {
        Log.i(CLASS_TAG, "City Names: + " + cityNamez);
    }
    for (String statesNames : sCState) {
        Log.i(CLASS_TAG, "State Names: + " + statesNames);
    }
    for (String zipCodes : sCZipCode) {
        Log.i(CLASS_TAG, "Zip Codes: + " + zipCodes);
    }
} else {
    Log.w(CLASS_TAG, "Error: Cursor is empty! #Total Records: " +
            locationDataCursor.getCount());
}
locationDataCursor.close();
soCalledDbHelper.close();

//Creating a List that can store List(s) within it.
//List of Lists String
List<List<String>> arrayOfLists = new ArrayList<List<String>>();

//Adding those Lists that was used to store each column records
arrayOfLists.add(sCLocationId);
arrayOfLists.add(sCCityName);
arrayOfLists.add(sCState);
arrayOfLists.add(sCZipCode);

//Start iterating over the parent arrayOfLists List 
for(int i = 0; i < arrayOfLists.size(); i++) {
    //Print each arrayOfLists data item it contains
    Log.v(CLASS_TAG, "Parent List: " + arrayOfLists.get(i).toString());
    //Start iterating over child of arrayOfLists List
    for(int j = 0; j < arrayOfLists.get(i).size(); j++) {
        //Print each arrayOfLists CHILD data item it contains
        Log.v(CLASS_TAG, "Child List: " + arrayOfLists.get(i).get(j).toString());
    }
}
        //Size of the arrayOfLists  
        Log.v(CLASS_TAG, "Parent List Size: " + Integer.toString(arrayOfLists.size()));
        //Size of the arrayOfLists child container  
        Log.v(CLASS_TAG, "Child List Size: " + Integer.toString(arrayOfLists.get(1).size()));
Log.v(CLASS_TAG, "AsyncTaskDbHelper ended successfully....");
return arrayOfLists;
}

我所做的更改:

>

  • 将AsyncTask类和doInBackground()返回类型的第3个参数更改为List

    <代码>位置数据光标。关闭() 所谓的帮助。关闭()

  • 穆锋
    2023-03-14

    您只需返回extend your AsyncTask off of AsyncTask

    更好的方法是扩展异步任务

    public class Location
    {
        private String location_id;
        private String country;
        private String state;
        private String zip_code;
    
        // Constructors, getters and setters go here. Your IDE should be able to generate them.
        // You can also override the toString method to format the output better
    }
    

    然后,您的循环将如下所示:

    List<Location> locations_list = new ArrayList<Location>();
    if (locationDataCursor.moveToFirst()) {// Moves to first if cursor is not empty
        do{
            Location location = new Location();
            //Extracting data from the location cursor
            location.setID(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("_id")));
            location.setCity(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("city_name")));
            location.setState(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("state")));
            location.setZip(locationDataCursor.getString
                    (locationDataCursor.getColumnIndex("zip_code")));
    
            // Add location to the list
            locations_list.add(location)
        }while (locationDataCursor.moveToNext())
    
        Log.i(CLASS_TAG, "Success: Cursor has data! #Total Records: " +
                locationDataCursor.getCount());
        for (Location l : locations_list) {
            Log.i(CLASS_TAG, "Location: " + l.toString());
        }
    } else {
        Log.w(CLASS_TAG, "Error: Cursor is empty!"
    }
    
    // Close any open DB objects
    locationDataCursor.close();
    soCalledDbHelper.close();
    Log.v(CLASS_TAG, "AsyncTaskDbHelper ended successfully....");
    
    // Return the list of locations
    return locations_list;
    
     类似资料:
    • 我正试图在android工作室中建立一个非常基本的天气应用程序。我正在使用AsyncClass返回多个字符串。 正如您在代码中看到的,我使用了一个名为“wrapper”的类,用于存储字符串,这样我就可以返回一个类对象,并在AsyncTask的onPostExecute方法中使用它。我面临的问题是,当我测试应用程序时,所有返回的字符串都是未定义的(包装类的默认值)。这意味着没有在doInBackgr

    • 问题内容: 一个简单的问题:是否可以返回in的值? 然后在我的: 编辑:这是很久以前我不熟悉Java的地方问的,现在我对它有了更好的了解,我将做一个简短的总结: 异步任务的要点是该任务为,这意味着调用该任务后,该任务将在其自己的线程上开始运行。从asynctask返回一个值将毫无意义,因为原始的调用线程已经进行了其他工作(因此该任务是异步的)。 考虑时间:在某个时间点,你启动了一个将与主线程并行运

    • 我想知道是否有可能在一次往返(网络呼叫)到Firestore数据库的过程中,通过ID列表获取多个文档。

    • 我想通过传递一个网址来加载多个图像。与本教程不同http://www.learn2crack.com/2014/06/android-load-image-from-internet.html其中只有一个图像被下载并使用img.setImageBitmap(图像)查看;我的问题是如何将url发送到一个方法以加载该url的图像,该方法返回一个图像,然后我在图像视图中显示它。

    • 问题内容: 我正在使用具有以下签名的类: 我正试图通过其他班级来称呼它: 但是在这里我得到这个错误: 为什么在Class扩展行中将我指定为第三个参数? 问题答案: 您可以通过对返回的AsyncTask调用AsyhncTask的get()方法来获得结果,但是当它等待获取结果时,它将把它从异步任务变成同步任务。 由于您的AsyncTask位于单独的类中,因此您可以创建一个接口类并在AsyncTask中