1

why the SAMPLE1 code is working fine and SAMPLE2 throws NullPointerException? do getWindowManager() work only inside onCreate?what can i do to create a method that will return height of the view and to make it available for all subclasses? please help..

SAMPLE1

public class MainActivity extends ActionBarActivity
        {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        final int height = displaymetrics.heightPixels;        
        float imheight= (float) (height*.4);
        int h=Math.round(imheight);

        ImageView im=(ImageView)findViewById(R.id.mainnews1);
        im.getLayoutParams().height = h;
        im.setScaleType(ImageView.ScaleType.FIT_XY);

        }

SAMPLE2

public class MainActivity extends ActionBarActivity
        {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

             ImageView im=(ImageView)findViewById(R.id.mainnews1);
        im.getLayoutParams().height = new MainActivity().heightof();
        im.setScaleType(ImageView.ScaleType.FIT_XY);
    }

    public int heightof()
    {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        final int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;
        float imheight= (float) (height*.4);
        int h=Math.round(imheight);
        return h;
    }
        }

2 Answers2

1

You should never call new MainActivity(), instead try to pass on or use context like, MainActivity.this

Mithun
  • 2,075
  • 3
  • 19
  • 26
  • can u plz post how to do? – mordern revolution May 24 '15 at 07:26
  • You are already in your `MainActivity` context, so you can any of its method simply. `new MainActivity().heightof();` is not needed, only `heightof()` or `this.heightof()` or MainActivity.this.heightof()` will work just fine – Mithun May 24 '15 at 07:28
  • you can read more about `new` vs `onCreate` from http://stackoverflow.com/questions/3302177/android-activity-constructor-vs-oncreate – Mithun May 24 '15 at 07:36
  • but i cant access from a static subclass,by this im.getLayoutParams().height = new MainActivity().heightof(); ,the subclass contain a fragment and ive to put the height to imageview in fragment..showing NullPointerException why?? – mordern revolution May 24 '15 at 07:41
  • In fragments you have to use `getActivity()` to get context of your root `Activity` – Mithun May 24 '15 at 07:48
1

Change this line:

>  im.getLayoutParams().height = new MainActivity().heightof();

to this line:

im.getLayoutParams().height = heightof();

Ramesh Kumar
  • 1,229
  • 14
  • 24