TurtleOrRodeo
TurtleOrRodeo

Reputation: 63

Error from getWindowManager in DisplayMetrics declaration error in Android

I'm designing my first android app, and part of that requires getting the screen size. I'm using the DisplayMetricsobject in the standard way:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics); //the error is on all 3 methods here
int height = metrics.heightPixels;
int width = metrics.widthPixels;

But I am getting an Invalid method declaration error on the 2nd line, on each of the 3 methods. This code is in my mainactivity.java file, created as an empty activity. None of the alterations suggested in other questions help here. I have tried the (Activity) cast and getContext() methods.

This is the whole file:

package com.example.android.cloudmusic;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;

    }
}

Any pointers greatly appreciated.

Upvotes: 0

Views: 1710

Answers (1)

Aalap Patel
Aalap Patel

Reputation: 2076

You should just use this code inside onCreate method and not outside. Remove unnecessary braces and its all good.

package com.example.android.cloudmusic;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      DisplayMetrics metrics = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(metrics);
      int height = metrics.heightPixels;
      int width = metrics.widthPixels;
      // use these height and width here onwards.. 
  }
}

Upvotes: 2

Related Questions