java - Android 应用程序在使用 Web View 的 onCreateView 期间未按预期设置变量

标签 java android

Java 和 Android 设备编程的新手。我的问题是我似乎无法获取 postcontent 变量来设置 Web View 以使用它。我可以在获取数据后记录值时确认 postcontent 是正确的。但是 WebView 永远看不到 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;
    }

}

最佳答案

call.enqueue() 是一个异步 调用,该调用不是阻塞调用。但是它提供了回调,比如调用结束时的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);
            }
        }
    });

关于java - Android 应用程序在使用 Web View 的 onCreateView 期间未按预期设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235972/

相关文章:

java - 获取jboss的信息

android - java.lang.NullPointerException 在 android.widget.TabHost.dispatchWindowFocusChanged(TabHost.java :298)

android - 如何使用正确的调理?

java - 宽度和高度为 match_parent 的 Recyclerview 返回固定大小错误

android - 检测 ListView(或 ScrollView)内的滚动位置

android - 如何修复错误 Could not find class 'io.realm.rx.RealmObservableFactory$2'?

java - 如何从本地超链接调用Java程序?

java - 为什么我没有从 NetBeans GUI 中的 if 语句获得输出?

java - 如何在Hadoop环境中执行用Java编写的Hadoop Job

java - Java中有没有办法提取数组中对象的所有属性名称