2016-04-13 198 views
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(); 
      } 

     } 
    }); 
} 
+0

嘗試訪問它時會出現什麼錯誤?空指針異常? –

+1

方法''Callback'的onResponse()'將從服務器獲得響應後異步運行。在'fetchGirls'中,你創建了類'Callback',但是沒有調用'onResponse'。所以'mGirlsList'尚未初始化 –

+0

@ShamasS是它的一個引起:java.lang.NullPointerException – Suzy21

回答

1

那麼你還沒有在任何地方初始化mGirlsList實例變量,但試圖訪問OnCreate方法內的大小。不像OnResponse方法那裏你做mGirlsList = girlClient.getGirlsListFromJson(jsonData);

因此,請確保您在OnCreate方法內的某個位置初始化mGirlsList