• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Unable to start activity ComponentInfo / Nullreference

Im a bit unsure why i get a nullreference why i place my :

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

in my LevelDesigner class, but when i keep it in the MainActivity there is no problem? I want to handle all my drawing in my leveldesigner class so not to get my MainActivity cluttered up!

MainActivity:

Code:
public class MainActivity extends Activity {

    LevelDesigner levelDesigner;
    int level = 1;

    [USER=1021285]@override[/USER]
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

/*        Paint whitePaint = new Paint();
        whitePaint.setColor(Color.parseColor("#FFFFFF"));

        int bgHeight = displayMetrics.heightPixels;
        int bgWidth = displayMetrics.widthPixels;

        Bitmap background = Bitmap.createBitmap(bgHeight, bgWidth, Bitmap.Config.ARGB_8888);
        Canvas canvasbackground = new Canvas(background);
        canvasbackground.drawRect(0, 0, bgHeight, bgWidth, whitePaint);

        LinearLayout ll = (LinearLayout) findViewById(R.id.rect);
        ll.setBackground(new BitmapDrawable(background));*/

        levelDesigner = new LevelDesigner();
        levelDesigner.SetLevel(level);
    }

    [USER=1021285]@override[/USER]
    public void onStart()
    {
        super.onStart();
    }

    [USER=1021285]@override[/USER]
    public void onStop()
    {
        super.onStop();
    }
}

Main xml:

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sharkgaming.myapplication.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:eek:rientation = "vertical"
        android:id="@+id/rect">
    </LinearLayout>

</RelativeLayout>

LevelDesigner class:

Code:
public class LevelDesigner extends AppCompatActivity
{
    List<Tile> tiles = new ArrayList<Tile>();
    Paint bgPaint = new Paint();
    Bitmap background;
    Canvas canvasbackground;
    Tile tile;

    public LevelDesigner()
    {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        bgPaint.setColor(Color.parseColor("#FFFFFF"));

        int bgHeight = displayMetrics.heightPixels;
        int bgWidth = displayMetrics.widthPixels;

        background = Bitmap.createBitmap(bgHeight, bgWidth, Bitmap.Config.ARGB_8888);
        canvasbackground = new Canvas(background);
        canvasbackground.drawRect(0, 0, bgHeight, bgWidth, bgPaint);

        LinearLayout ll = (LinearLayout) findViewById(R.id.rect);
        ll.setBackground(new BitmapDrawable(background));

    }

    public void SetLevel(int _level)
    {
        switch (_level)
        {
            // clean tiles list
            case 1:
                tiles.add(new Tile("W", 10, 10));

                Draw();
                break;

            case 2:
                Draw();
                break;

            case 3:
                Draw();
                break;

        }
    }

    public void Draw()
    {
        for(Tile tile : tiles)
        {
            canvasbackground.drawRect(tile.positionX, tile.positionX, tile.height, tile.width, tile.color);
        }
    }
}

My error:

Code:
FATAL EXCEPTION: main
                  Process: com.example.sharkgaming.myapplication, PID: 9499
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sharkgaming.myapplication/com.example.sharkgaming.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.Display android.view.WindowManager.getDefaultDisplay()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.Display android.view.WindowManager.getDefaultDisplay()' on a null object reference
                      at com.example.sharkgaming.myapplication.LevelDesigner.<init>(LevelDesigner.java:41)
                      at com.example.sharkgaming.myapplication.MainActivity.onCreate(MainActivity.java:42)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
 
Last edited by a moderator:
Try this

Code:
public LevelDesigner(Context context) {
  DisplayMetrics displayMetrics = new DisplayMetrics();
  ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
  ...
}

And in MainActivity:

Code:
levelDesigner = new LevelDesigner(this);
 
Btw you will likely encounter more problems with your LevelDesigner class, because you're assuming it will behave like an Activity. It won't, because it has not been created in the normal way. You cannot simply instantiate an Activity class, because it needs to be initialised by the system. Your code should go in methods like onCreate(), which are called by the framework.
Just creating a new instance of the class LevelDesigner will probably cause findViewById() to not work.

The bottom line is that if you want to use methods like findViewById() and getWindowManager(), you need a valid context (Activity) which has been created and initialised by the Android runtime framework, not simply created by your code.
 
Didnt do the trick, still have a null pointer in the
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); line, but it is probably caused by what you just said, as it makes sense. Ill probably just move it to the MainActivity class then, save myself the troubles^^
 
Yes you are setting yourself up for problems. Activity classes don't normally have a constructor method. That's because your code should never create one. If you need to start an Activity, do it with startActivity(), with an Intent. The system creates your Activity.
 
Back
Top Bottom