java - Android 从 Okhttp onResponse 函数中提取字符串

标签 java android string handler okhttp

我想使用Android Studio从OkHttp3中的onResponse函数获取字符串值,这是

final String title_name = jsonarray_news_extract_Data(jsonStr, index)

在下面的代码中。 我尝试在参数中插入字符串变量“a”,但它说

Variable is accessed within inner class. Needs to be declared final

所以我宣布为最终结果然后它说

Cannot Assign a Value to Final Variable

我试图把

a = title_name;

删除Handler方法后仍然不起作用。

如果您有任何想法,请帮助我。 谢谢

public void news_From_API_Title(String url_news, final int index, final TextView textView, String a){

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url_news)
            .build();

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

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            final String jsonStr = Objects.requireNonNull(response.body()).string();
            final String title_name = jsonarray_news_extract_Data(jsonStr, index);

            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {

                    a = title_name;
                }
            });
        }
    });

}

private String jsonarray_news_extract_Data(String jsonString_News, int index){
    try {
        JSONObject jsonObject = new JSONObject(jsonString_News);
        JSONArray jsonArray = jsonObject.getJSONArray("Data");
        return jsonArray.getJSONObject(index).getString("title");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

最佳答案

您可以使用自定义界面,如下所示:

interface ApiCallback{
    void onOkHttpResponse(String data);
    void onOkHttpFailure(Exception exception);
}

然后,您将 ApiCallback 实例传递给实际执行调用的方法,而不是 String:

public void news_From_API_Title(String url_news, final int index, final TextView textView, ApiCallback callback){

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url_news)
            .build();

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

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            final String jsonStr = Objects.requireNonNull(response.body()).string();
            final String title_name = jsonarray_news_extract_Data(jsonStr, index);

            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onOkHttpResponse(title_name);
                }
            });
        }
    });

}

现在您可以使用 ApiCallback 的实现,如下所示:

String url_news = "https://some.web.address/news";
int index = 7;
TextView textView;
news_From_API_Title(url_news, index, textView, new apiCallback(){
    @Override
    public void onOkHttpResponse(String data){
        // do something with data here
        Log.d("TEST", "data = " + data);
    }

    @Override
    onOkHttpFailure(Exception exception){
        // exception handling
    }
});
<小时/>

请注意,如果您不将 TextView 作为参数传递到方法中,而是在 onOkHttpResponse() 中设置文本,从架构角度来看可能会更好:

// TextView will be initialized before calling news_From_API_Title()
// either make TextView a field (then use "private") 
// or declare it locally (then use "final")
private TextView textView;

// ... other code ...

String url_news = "https://some.web.address/news";
int index = 7;

// method will only take parameters which are not related to the UI 
// since it's desirable to avoid tight coupling of networking and UI components 
news_From_API_Title(url_news, index, new apiCallback(){
    @Override
    public void onOkHttpResponse(String data){
        // do something with data here
        // e.g. show data in TextView
        textView.setText(data);
    }

    @Override
    onOkHttpFailure(Exception exception){
        // exception handling
    }
});

关于java - Android 从 Okhttp onResponse 函数中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60581853/

相关文章:

android - 从服务器向 Android 应用程序发送命令

python - 按特定顺序格式化字符串

android - 忽略创建时触发的 OnItemSelectedListener

java - 在 Android 上反序列化数组

java - 在 catalinaopts 中附加多个 javaagents

java - XML block 有效吗?

C++ 用户定义的字符串需要包含空格(但程序不允许..?)

string - 在 Grails 中连接多个字符串

java - 创建多个 fragment 的通用方法

java - 使用 appium 的一个应用程序的 Cpu 内存使用情况