首页 > 解决方案 > 在使用 Web 视图的 onCreateView 期间,Android 应用程序未按预期设置变量

问题描述

在 Java 和 Android 设备上编程的新手。我的问题是我似乎无法postcontent为 Web 视图设置变量以使用它。当我在获取数据后记录值时,我可以确认它postcontent是正确的。但是网络视图永远不会看到postcontent使用新数据设置的内容。

package org.appname.app.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.util.Log;
import org.appname.app.calendar.*;
import java.io.IOException;
import okhttp3.*;



public class CalendarFragment extends android.support.v4.app.Fragment {

    public static CalendarFragment newInstance() {
        return new CalendarFragment();
    }
    public static final String TAG = CalendarFragment.class.getSimpleName();
    private static final String calendarJSON = "https://www.example.com/.json";
    String postcontent = "";
    private String postTest = "<p><h3>CACHED</h3></p><p><strong>Saturday, May 5</strong></p>";



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(org.appname.app.R.layout.fragment_giving, container, false);

        final WebView mWebView = view.findViewById(org.appname.app.R.id.giving_webview);


            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(calendarJSON)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call,Response response) throws IOException {

                    try {
                        String jsonData = response.body().string();
                        if (response.isSuccessful()) {
                            CalendarHelper data = Converter.fromJsonString(jsonData);
                            ObjectElement[] objects = data.getObjects();
                            postcontent = objects[0].getPostBody();
                            Log.v(TAG, postcontent.toString());
                        } else {
                            //alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.v(TAG, "Exception caught : ", e);
                    }
                }
            });

        if (postcontent.isEmpty()) {
            Log.v(TAG, "empty");
            mWebView.loadDataWithBaseURL(null, postTest, "text/html", "utf-8", null);

        } else {
            mWebView.loadDataWithBaseURL(null, postcontent, "text/html", "utf-8", null);

            Log.v(TAG, "not empty");
        };

        return view;
    }

}

标签: javaandroid

解决方案


call.enqueue()是一个asynchronous调用,该调用不是阻塞调用。但它会在通话结束时提供,callback例如。onResponseonFailure

要在异步调用成功时更新 UI 状态,只需在onResponse回调中进行。mHandler.post()此处用于确保 UI 更新仅在 UI 线程中发生。

同样,要在异步调用失败时更新 UI,请在onFailure回调中使用类似的技术。

// to be used to update UI in UI thread
private Handler mHandler;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(org.stmarcus.stmarcusmke.R.layout.fragment_giving, container, false);

    final WebView mWebView = view.findViewById(org.stmarcus.stmarcusmke.R.id.giving_webview);

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(calendarJSON)
            .build();

    // instantiate mHandler
    mHandler = new Handler(Looper.getMainLooper());

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call,Response response) throws IOException {

            try {
                String jsonData = response.body().string();
                if (response.isSuccessful()) {
                    CalendarHelper data = Converter.fromJsonString(jsonData);
                    ObjectElement[] objects = data.getObjects();
                    postcontent = objects[0].getPostBody();
                    Log.v(TAG, postcontent.toString());

                    // update UI in UI Thread
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (postcontent.isEmpty()) {
                                Log.v(TAG, "empty");
                                mWebView.loadDataWithBaseURL(null, postTest, "text/html", "utf-8", null);

                            } else {
                                mWebView.loadDataWithBaseURL(null, postcontent, "text/html", "utf-8", null);

                                Log.v(TAG, "not empty");
                            };
                        }
                    });

                } else {
                    //alertUserAboutError();
                }
            } catch (IOException e) {
                Log.v(TAG, "Exception caught : ", e);
            }
        }
    });

推荐阅读