异步任务片段背景数据

时间:2019-06-17 23:32:08

标签: java android android-recyclerview android-asynctask

对于如何从此网站将大量模板JSON数据加载到我的应用程序中而又不减慢主UI线程的速度,我感到非常困惑。我可以将数据从JSON响应加载到我的回收站视图中,但是单击显示数据的底部导航选项卡需要很长时间才能加载到页面上。

我了解这是因为数据没有正确加载到后台线程上,这就是我感到困惑的地方。

我希望能够从后台任务中返回一个ArrayList,并使用填充的arraylist并将其作为我的recyclerview适配器。这是包含AsyncTask和recyclerview代码的片段:

public class LoadJSONAsyncTask extends AsyncTask<String, String, ArrayList<String>>
    {

        protected void onPreExecute()
        {


        }

        public String getJSONFromURL(String inUrl) throws IOException
        {
            URL url2 = new URL(inUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url2.openConnection();
            StringBuilder total = new StringBuilder();

            try
            {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader r = new BufferedReader(new InputStreamReader(in));

                for(String line; (line = r.readLine()) != null;)
                {
                    total.append(line).append('\n');
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            finally
            {
                urlConnection.disconnect();
            }

            return total.toString();
        }

        @Override
        protected ArrayList<String> doInBackground(String... params)
        {
            LoadJSONAsyncTask jParser = new LoadJSONAsyncTask();
            JSONArray array = null;
            JSONObject json = null;
            String url = "https://baconipsum.com/api/?type=meat-and-filler";

            StringBuilder returnMe = new StringBuilder();
            results = new ArrayList<>();

            try {
                array = new JSONArray(jParser.getJSONFromURL(url));
                for(int n = 0; n < array.length(); n++)
                {
                    try {
                        json = new JSONObject();

                        json.put("name", jParser.getJSONFromURL(url));
                        results.add(jParser.getJSONFromURL(url));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



            return results;
        }

        protected void onPostExecute()
        {

        }

    }

在片段的onCreateView()方法中,recyclerview定义如下:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        try
        {
            results = new LoadJSONAsyncTask().execute(url).get();
            for(int i = 0; i < results.size(); i++)
            {
                newsFeedList.add(new NewsFeed(results.get(i)));
            }
        } catch (ExecutionException e) {

        } catch (InterruptedException e) {e.printStackTrace();
            e.printStackTrace();
        }
        View view = inflater.inflate(R.layout.fragment_feeds, container, false);

        newsFeedList = new ArrayList<>();

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));


        final NewsAdapter mAdapter = new NewsAdapter(getActivity(), newsFeedList);
        recyclerView.setAdapter(mAdapter);


        return view;
    }

我有一种感觉,在我的onCreateView()方法内部,调用数组列表执行数据的方式就是将数据挂在线程上。一个清晰的爆炸和例子将不胜感激!

2 个答案:

答案 0 :(得分:1)

覆盖onPostExecute中的LoadJSONAsyncTask,并将所有用户界面更新都放在其中。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_feeds, container, false);

        newsFeedList = new ArrayList<>();

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        final NewsAdapter mAdapter = new NewsAdapter(getActivity(), newsFeedList);
        recyclerView.setAdapter(mAdapter);

        LoadJSONAsyncTask asyncTask = new LoadJSONAsyncTask() {
        @Override
        void onPostExecute(ArrayList<String> results) {
                // update your adapter here with the result

                for(int i = 0; i < results.size(); i++)
                {
                    newsFeedList.add(new NewsFeed(results.get(i)));
                }

                // notify adapter here to update the view
                mAdapter.notifyDataSetChanged()
            }
        }

        asyncTask.execute(url);

        return view;
    }

.get()挂断您的主线程。

以下是正确使用AsyncTask的方法。 How can I create cross platform icon in react native?

答案 1 :(得分:0)

LoadJSONAsyncTask结束后调用片段