简体   繁体   English

好的http。 无法保存加载的数据

[英]okhttp. Can't save loaded data

I can't save data loaded from okhttp. 我无法保存从okhttp加载的数据。 What is wrong in my code. 我的代码有什么问题。 When I try to load data on Log app crashes. 当我尝试在Log应用程序上加载数据时崩溃。 Please Help. 请帮忙。

public class MainActivity extends AppCompatActivity {
private static final String URL = "https://chroniclingamerica.loc.gov/search/titles/results/?terms=michigan&format=json&page=5";
private String data;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    loadData();
    Log.d("DATA", data);
}

private void loadData() {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(URL)
            .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 {
            data = response.body().string();
        }
    });
}

} }

Explanation 说明

The problem is around how your code is being executed (ie sync vs async). 问题在于您的代码如何执行(即同步与异步)。

You call the method loadData() which will not set the class attribute data as you're expecting - it will set the attribute data once it gets a response however that function loadData will not wait for the response (ie it doesn't block the current thread or execution code.) . 您调用方法loadData()不会像您期望的那样设置类属性数据-它将在响应后设置属性data ,但是该函数loadData不会等待响应(即,它不会阻止响应当前线程或执行代码。)。 Which means on the next line LOG.d("Data", data); 这意味着在下一行LOG.d("Data", data); , data has not been set, thus is null (and will crash your app). ,数据尚未设置,因此为null(将导致您的应用崩溃)。

Solution

If you just want to LOG data, then just move your log statement after you assign it on your onResponse callback. 如果只想记录数据,则在onResponse回调中分配日志语句后移动它即可。

private void loadData() {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(URL)
            .build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // Some error has occurred
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {   
            processData(response.body().string());
        }
    });
}

private void processData(String data) {
    Log.d("DATA", data);
    // To other stuff here given your value data. 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM