-1

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

这是一个带有 Node.js 服务器和 Mysql 数据库的 Rest Communications。

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();
            }

        }
    }

}
4

1 回答 1

1

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

但是,您可以RecyclerViewAsyncTask完成执行后刷新。为此,请将新获取的数据添加到您的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 线程上运行,所以你很高兴 :-)

于 2019-01-12T16:13:01.340 回答