Raul Figueira Raul Figueira - 22 days ago 7
Android Question

Singleton Design Pattern cannot assign value final variable instance

I am trying to use the Singleton design pattern in ItemControl, but Android Studio says that I cannot assign a value to final variable 'instance'. How can I compile my code if the variable must be static final?

public final class ItemControl {
private final Map<Long, Item> itemMap = new HashMap<>();
private static final ItemControl instance;

private ItemControl() { }

public static synchronized ItemControl getInstance() {
if(instance == null) {
instance = new ItemControl();
}
return instance;
}

public void addItem(Item item) {
itemMap.put(item.getId(), item);
}

public List<Item> retrieveItems() {
if(itemMap.isEmpty()) {
List<Item> items = carregarItems();
if(items != null) {
for(Item item : items) {
itemMap.put(item.getId(), item);
}
}
}
return new ArrayList<>(itemMap.values());
}

private List<Item> carregarItems() {
List<Item> items = new ArrayList<>();

Item.Builder livroBuilder = new Item.Builder(System.nanoTime(), "Java for Beginners")
.setAno(2013).setAutor("Glauber Rocha").setQuantidade(3)
.setDescricao("Livro para programadores iniciantes.");

Item.Builder revistaBuilder = new Item.Builder(System.nanoTime(), "Geek on the table")
.setAno(2013).setAutor("Robson Duarte").setQuantidade(2)
.setDescricao("Revista para geeks.");

items.add(livroBuilder.build());
items.add(revistaBuilder.build());

return items;
}
}

Answer

This has nothing to do with Android Studio. See, you have the variable instance which has been declared final. And its being assigned in getInstance(). So since its final you cannot assign it anywhere but there itself.

So do this:
private static final ItemControl instance = new ItemControl();

And in getInstance() return that variable

public static ItemControl getInstance() {
        return instance;
    }