我无法保存从okhttp加载的数据。我的代码有什么问题。当我尝试在Log app崩溃时加载数据。请帮助。
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();
}
});
}
}
答案 0 :(得分:2)
问题在于您的代码是如何执行的(即同步与异步)。
您调用的方法loadData()
不会像您期望的那样设置类属性数据 - 一旦获得响应,它将设置属性data
但是函数loadData
将不等待响应(即它不阻止当前线程或执行代码。)。这意味着在下一行LOG.d("Data", data);
上,数据尚未设置,因此为空(并且会使您的应用崩溃)。
如果您只想记录数据,那么只需在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.
}