0
我有一個問題,我不能訪問mGirlsLisl
變量。 我認爲這是try catch中的一個問題。無法訪問實例變量
代碼運行良好,但onCreate
方法無法訪問mGirlsList
變量。 請檢查代碼 公共類MainActivity擴展AppCompatActivity {
private ArrayList<Girl> mGirlsList;
private GirlClient girlClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fetchGirls("girls.json");
Log.i("LOG", String.valueOf(mGirlsList.size())); // ERROR can't get size
}
private void fetchGirls(String query) {
girlClient = new GirlClient();
String url = girlClient.getApiUrl(query);
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) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String jsonData = response.body().string();
try {
mGirlsList = girlClient.getGirlsListFromJson(jsonData);
Log.i("LOG", String.valueOf(mGirlsList.size())); // 5 OK
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
嘗試訪問它時會出現什麼錯誤?空指針異常? –
方法''Callback'的onResponse()'將從服務器獲得響應後異步運行。在'fetchGirls'中,你創建了類'Callback',但是沒有調用'onResponse'。所以'mGirlsList'尚未初始化 –
@ShamasS是它的一個引起:java.lang.NullPointerException – Suzy21