How to Calculate Screen Size

0 Usman Mohy ud Din · October 22, 2014
Hy everyone...

I am using following code to calculate screen size of android device.But app crashed when activity launched.
Please guide if you know...

Code

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv=(TextView)findViewById(R.id.textview);
        setContentView(R.layout.main);
        
        
        @SuppressWarnings("deprecation")
int ScreenHeight = getWindow().getWindowManager().getDefaultDisplay()
.getHeight();// 480
@SuppressWarnings("deprecation")
int ScreenWidth = getWindow().getWindowManager().getDefaultDisplay()
.getWidth();// 854
                 tv.setText("Your Screen Size has length "+ScreenHeight +" & Width " +ScreenWidth);
    }
}


Error


10-22 22:02:44.290: E/AndroidRuntime(5082): FATAL EXCEPTION: main
10-22 22:02:44.290: E/AndroidRuntime(5082): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calcscreensize/com.example.calcscreensize.MainActivity}: java.lang.NullPointerException
10-22 22:02:44.290: E/AndroidRuntime(5082): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)

Post a Reply

Replies

Oldest  Newest  Rating
0 Alex Sweps · October 23, 2014
Its looking for something that isnt there hence the null pointer. Check your xml for the ids you are refering too. 

R.id.textview //Make sure you have an id for textview in your xml file.
R.layout.main //Make sure you actually have a layout in named main
0 Usman Mohy ud Din · October 23, 2014
I reset the attributes of TextView in xml and it starts working.

Thanx Alex :)
  • 1

Java / Android Development

107,277 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator