使用AsyncTask从服务器获取数据

时间:2018-08-29 18:26:58

标签: android android-asynctask

在我的程序中,许多值存储在服务器上。 我使用AsyncTask类从服务器读取了这些数据。

这是我的代码:

public class TestActivity extends AppCompatActivity {
    private static List<String> mPackName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPackName = new ArrayList<>();
        try {
            boolean check = new GetDataAsyncTask().execute("1234567").get();
        } catch (InterruptedException e) {

        } catch (ExecutionException e) {
            e.printStackTrace();
            e.printStackTrace();
        }

    }

    private class GetDataAsyncTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            final String mCode = params[0];

            APIGettingPosts apiGettingPosts = new APIGettingPosts(TestActivity.this, "get_off_code.php");
            apiGettingPosts.getOffCode(new APIGettingPosts.OnOffCodeReceived() {
                @Override
                public void onReceived(List<Posts> posts) {
                    if (!(posts == null || posts.isEmpty()))
                        for (int i = 0; i < posts.size(); ++i) {
                            mPackName.add(posts.get(i).getTitle());
                            Log.e("mPackName["+String.valueOf(i)+"]",mPackName.get(i));
                        }
                }
            });
            Log.e("Size of mPackName: ", String.valueOf(mPackName.size()));

            for (int i = 0; i < mPackName.size(); ++i)
                if (mCode.equals(mPackName.get(i))) {
                    Log.e("Is Equal: ", mPackName.get(i));
                    return true;
                }
            return false;
        }
    }
}

程序正确从服务器接收数据并将其存储在mPackName列表中。在doInBackground函数的最后,程序检查GetDataAsyncTask().execute("1234567")列表中是否存在mPackName函数中的输入值,并返回true值。

尽管GetDataAsyncTask().execute("1234567")函数的输入值在mPackName列表中,但程序将返回false值。

Log cat的输出如下:

  

08-28 / com.green E / mPackName的大小:: 0

     

08-28 / com.green E / mPackName [0]:1234567

     

08-28 / com.green E / mPackName [1]:QAZXSWE

     

08-28 / com.green E / mPackName [2]:QWERTYU

mPackName列表的大小在Log cat中也为零,尽管它具有三个值{'1234567','QAZXSWE','QWERTYU'}

问题是:如何在mPackName列表中搜索'1234567'值以返回true中的check = new GetDataAsyncTask().execute("1234567").get();值  代码?

2 个答案:

答案 0 :(得分:3)

  

编辑答案

看起来您甚至不需要AsyncTask,因为getOffCode方法已经在后台线程中运行。

删除GetDataAsyncTask类,并创建如下所示的方法。

private void search(final SearchCallback callback) {
    APIGettingPosts apiGettingPosts = new APIGettingPosts(TestActivity.this, "get_off_code.php");
    apiGettingPosts.getOffCode(new APIGettingPosts.OnOffCodeReceived() {
        @Override
        public void onReceived(List<Posts> posts) {
            if (!(posts == null || posts.isEmpty())) {
                for (int i = 0; i < posts.size(); ++i) {
                    mPackName.add(posts.get(i).getTitle());
                    Log.e("mPackName[" + String.valueOf(i) + "]", mPackName.get(i));
                    if (mCode.equals(mPackName.get(i))) {
                        callback.onSearchFound(true);
                        break;
                    }
                }
            }
            callback.onSearchFound(false);
        }
    });
}

public interface SearchCallback{
    void onSearchFound(boolean success);
}

然后从如下所示的onCreate方法调用

search(new SearchCallback(){
    @Override
    public void onSearchFound(boolean success) {

    }
});

答案 1 :(得分:1)

尝试在onPostExecute()方法中放置一个开关。

EG。

...

private class GetDataAsyncTask extends AsyncTask<String, Void, Boolean> {

@Override
void onPostExecute(Object o){
    handleResults()
}

...

void handleResults(){
// Insert your check here
}