Search code examples
androidloopj

How to use inner class variable in whole class


I have a method like this to get firstname from webservices using loopj.

private void getfirstName() {
  List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept", "application/json"));

  RestClient.getShiftCodes(MainActivity.this, "RestService/First_Name", headers.toArray(new Header[headers.size()]),
            null, new JsonHttpResponseHandler() {
  @Override
  public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
  ArrayList<String> firstNameArray = new ArrayList<String>();   
  for (int i = 0; i < response.length(); i++) {
  try {
         JSONObject c = response.getJSONObject(i);
         String  first_NameArray = c.getString("firstName");
         firstNameArray.add(first_NameArray); 
       } 
       catch (JSONException e) {
          e.printStackTrace();
       }
   }
   String first_Name= firstNameArray.get(0);
  }
 });

}

If I want to use the first_name string value in other methods, I get this error

Cannot refer to a non-final variable first_name inside an inner class defined in a different method

Even if I change it to final I cannot use it. How can I use it in the whole class.


Solution

  • You cannot be able to get the reference of inner class variable directly instead declare in outer class and assign the value in inner class. Then You can access the variable from any of the classes.