在 oncreateview 中使用异步任务

Use Async Task in oncreateview

有没有办法用oncreateview方法中的异步任务覆盖"week_kg"变量? 异步任务覆盖变量,但视图已创建且不包含新值。

这是与 Node.js 服务器和 Mysql 数据库的休息通信。

public class Feedback extends Fragment {
    private RecyclerView mRecylcerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;


    public String username = "ilovenature";

    public double week_kg;

    String resturl = "http://192.168.178.199:3000/"; //ip


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_feedback, container, false);

        new HttpGet().execute(resturl + "user/" + username);

        ArrayList < Feedback_inhalt > feedback_inhalt = new ArrayList<>();
        feedback_inhalt.add(new Feedback_inhalt(R.mipmap.ic_plastic_color, "Verwertungskosten", "kg eingespart", week_kg));


        mRecylcerView = view.findViewById(R.id.feedback_view);
        mRecylcerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this.getActivity());
        mAdapter = new FeedbackAdapter(feedback_inhalt);

        mRecylcerView.setLayoutManager(mLayoutManager);
        mRecylcerView.setAdapter(mAdapter);

        return view;
    }


    public class HttpGet extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String...strURLs) {
            URL url;
            String output;
            HttpURLConnection conn;
            try {
                url = new URL(strURLs[0]);
                conn = (HttpURLConnection) url.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                while ((output = br.readLine()) != null) {
                    sb.append(output);
                }
                return sb.toString();
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        @Override
        protected void onPostExecute(String result) {
            try {
                JSONArray jsonArray = new JSONArray(result);

                JSONObject jsonObject = jsonArray.getJSONObject(0);
                week_kg = jsonObject.getDouble("wochenkilogramm");

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

        }
    }

}

onCreateView() 方法仅在创建视图时调用一次。

但是,您可以在 AsyncTask 完成执行后刷新 RecyclerView。为此,将新获取的数据添加到您的 ArrayList feedback_halt,然后在您的适配器上调用 notifyDataSetChanged()

当您调用 notifyDataSetChanged() 时,将根据 ArrayList 中的数据刷新视图。

因此,在 onPostExecute() 中设置 week_kg 的值后:

feedback_inhalt.add(new Feedback_inhalt(R.mipmap.ic_plastic_color, "Verwertungskosten", "kg eingespart", week_kg));
mAdapter.notifyDatSetChanged()

最后,notifyDataSetChanged() 方法只能从 UI 线程调用,但 onPostExecute() 方法在设计上运行在 UI 线程上,因此您可以去:-)