Java – You cannot add data to a HashMap declared in a non-Activity class

You cannot add data to a HashMap declared in a non-Activity class… here is a solution to the problem.

You cannot add data to a HashMap declared in a non-Activity class

I declared a HashMap in a non-activity class as follows:

public class Wifi {
    HashMap<String, String> AccessPoints = new HashMap<String, String>();
    AccessPoints.put("AP1", "first_ap");

public ArrayList<Integer> scanWifi(Context context) {
             code here
    }
}

Then I tried to add data to HashMap, but I got a “Unable to parse symbols” error in Android Studio.

When I set AccessPoints.put("AP1", "first_ap"); When placed in a function of a class, it seems to work fine.

Solution

AccessPoints.put("AP1", "first_ap");

Calling a method should be done inside a block:

  • One way.
  • Static initializer.
  • An instance initializer.
  • Constructor.

Related Problems and Solutions