javaandroidhttpurlconnectiononcreatefragment-oncreateview

Use Async Task in oncreateview


Is there a way to overwrite the "week_kg" variable with the async task in the oncreateview method? The async task overwrites the variable, but the View is already created and doesn't contain the new value.

It's a Rest Communications with a Node.js Server and a Mysql database.

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

        }
    }

}

Solution

  • The onCreateView() method is only called once when the view is created.

    However, you can refresh your RecyclerView once your AsyncTask has finished executing. To achieve this, add the newly fetched data to your ArrayList feedback_halt and then call notifyDataSetChanged() on your adapter.

    When you call notifyDataSetChanged(), the views will be refreshed based on the data in your ArrayList.

    So, inside onPostExecute() after you have set the value of week_kg:

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

    Finally, the notifyDataSetChanged() method should only be called from a UI thread but the onPostExecute() method runs on the UI thread by design so you are good to go :-)