Shubham Goel
Shubham Goel

Reputation: 43

Android : java.lang.NullPointerException Unable to start Activity

I know that this question is asked a lot of time but the answer is always for a specific code.

So, i am creating a game in which i need to switch between activities and i have tried everything but always my logcat give me that error and emulator says that "Application have Stopped Working ". So please help me to find out the bug.

My code is:

MainActivity.java

package com.example.experiment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView playG=(TextView)findViewById(R.id.playGame);
        playG.setOnClickListener(new View.OnClickListener()
        {   
            @Override
            public void onClick(View arg0)
            {
                Intent i=new Intent(MainActivity.this,GameActivity.class);
                startActivity(i);
            }
        });
    }
}

GameActivity.java

package com.example.experiment;

import android.app.Activity;
import android.os.Bundle;

public class GameActivity extends Activity 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(new Game(this));
    }
}

Game.java

package com.example.experiment;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class Game extends View 
{
int i=0,j=0;
int hei=0,wid=0,div=0;
int MoUp=0,MoUpDo=0,Rd;
float TouchXU=0,TouchYU=0,TouchXD=0,TouchYD=0;
float CirX,CirY;
int Score=0;
boolean MoveUp=false,Move=false,NextObs=false;
Path Rpath=new Path();
Paint paint=new Paint();
String ScoreStr="";
Random Rand=new Random();
Activity act=new Activity();
GamEnd g=new GamEnd(getContext());
Context context1=act.getApplicationContext();
Intent intent=new Intent();
public Game(Context context)
{
    super(context);
}
@Override
public void onDraw(Canvas canvas)
{
    Rd=Rand.nextInt(10);
    super.onDraw(canvas);
    paint.setAntiAlias(true);
    setBackgroundColor(Color.parseColor("#3E8E21"));
    MainPath(canvas);
    Obstacle1(canvas);
    Ball(canvas);
    Scores(canvas);
}
public void Ball(Canvas canvas)
{
    CirX=getWidth()/2;
    CirY=(getHeight()/2+getHeight()/4);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(Color.BLUE);
    paint.setStyle(Paint.Style.FILL);
    if(i<9)
    {
        postInvalidateDelayed(40);
        canvas.drawCircle(CirX, CirY+i, 30, paint);
        i+=3;
        Score+=10;
    }
    else if(MoveUp==true)
    {
        if(MoUp<200)
        {
            postInvalidateDelayed(30);
            canvas.drawCircle(CirX, CirY+i-MoUp, 30, paint);
            MoUp+=40;
            Score+=10;
        }
        else
        {
            postInvalidateDelayed(25);
            canvas.drawCircle(CirX, CirY+i-j+MoUpDo-MoUp, 30, paint);
            MoUpDo+=40;
            Score+=10;
            if(MoUpDo==200) 
            {
                MoUp=0;
                MoUpDo=0;
                MoveUp=false;
            }
        }
    }
    else
    {
        postInvalidateDelayed(40);
        canvas.drawCircle(CirX, CirY+i-j, 30, paint);
        j+=3;
        Score+=10;
        if(j==9) 
        {
            i=0;
            j=0;
        }
    }
    if(hei>=CirY-15 && hei<=CirY+10 && MoveUp==false)
    {
        Toast.makeText(getContext(), "You Are Out", Toast.LENGTH_LONG).show();
        Intent in=new Intent(getContext(),MainActivity.class);
        act.startActivity(in);
    }
}
public void MainPath(Canvas canvas)
{
    paint.setColor(Color.parseColor("#EE874B"));
    paint.setStyle(Paint.Style.FILL);
    Rpath.moveTo(getWidth()/2-getWidth()/6,0);
    Rpath.lineTo(getWidth()/2+getWidth()/6,0);
    Rpath.lineTo(getWidth()/2+getWidth()/3,getHeight());
    Rpath.lineTo(getWidth()/2-getWidth()/3,getHeight());
    Rpath.lineTo(getWidth()/2-getWidth()/6,0);
    canvas.drawPath(Rpath, paint);
    Rpath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
    switch(event.getAction())
    {
    case MotionEvent.ACTION_DOWN:
        TouchXD=(float)event.getRawX();
        TouchYD=(float)event.getRawY();
        break;
    case MotionEvent.ACTION_UP:
        TouchXU=(float)event.getRawX();
        TouchYU=(float)event.getRawY();
        break;
    case MotionEvent.ACTION_MOVE:
        Move=true;
        break;
    }
    if(TouchYD>TouchYU && Move==true)
    {
        MoveUp=true;
        Move=false;
    }
    return true;
}
public void Scores(Canvas canvas)
{
    paint.setColor(Color.parseColor("#4CB028"));
    paint.setTextSize(20);
    paint.setTextSkewX((float) 0.1);
    paint.setFakeBoldText(true);
    ScoreStr=String.valueOf(Score);
    canvas.drawText(ScoreStr, 10, 30, paint);
}
public void Obstacle1(Canvas canvas)
{
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(20);
    canvas.drawLine(getWidth()/2-getWidth()/6-wid, hei, getWidth()/2+getWidth()/6+wid, hei, paint);
    float heiDiv=getHeight()/40;
    float widDiv=(getWidth()/3-getWidth()/6)/40;
    wid+=widDiv;
    hei+=heiDiv;
    if(hei>=getHeight())
    {
        NextObs=true;
        hei=0;
        wid=0;
        Obstacle1(canvas);
    }
}
public void ShowEnd(Canvas canvas)
{
    setBackgroundColor(Color.parseColor("#003366"));
    canvas.drawColor(Color.BLACK);
}
}

My logcat

08-21 08:57:09.647: E/AndroidRuntime(1253): FATAL EXCEPTION: main
08-21 08:57:09.647: E/AndroidRuntime(1253): Process: com.example.experiment, PID: 1253
08-21 08:57:09.647: E/AndroidRuntime(1253): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.experiment/com.example.experiment.GameActivity}: java.lang.NullPointerException
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.os.Looper.loop(Looper.java:136)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at java.lang.reflect.Method.invokeNative(Native Method)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at java.lang.reflect.Method.invoke(Method.java:515)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at dalvik.system.NativeStart.main(Native Method)
08-21 08:57:09.647: E/AndroidRuntime(1253): Caused by: java.lang.NullPointerException
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at com.example.experiment.Game.<init>(Game.java:31)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at com.example.experiment.GameActivity.onCreate(GameActivity.java:12)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.Activity.performCreate(Activity.java:5231)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-21 08:57:09.647: E/AndroidRuntime(1253):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-21 08:57:09.647: E/AndroidRuntime(1253):     ... 11 more

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.experiment"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.experiment.MainActivity"
        android:configChanges="orientation"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.experiment.GameActivity"
        android:label="@string/title_activity_game" >
        <meta-data 
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.experiment.GameActivity"/>
    </activity>
</application>

</manifest>

Please friends help. Thanks in advance.

Upvotes: 0

Views: 894

Answers (2)

laalto
laalto

Reputation: 152927

Activity act=new Activity();

Never do this. An activity you instantiate yourself won't be good for anything, including a call to getApplicationContext(). Hence you get the NPE there.

Instead, pass a Context as a parameter to objects and methods that require it, such as your Game class constructor.

Upvotes: 0

localhost
localhost

Reputation: 5598

Intent i = new Intent(MainActivity.this, GameActivity.class);

Should be declared after

super.onCreate();

Upvotes: 2

Related Questions