Unable to start activity error with Scene2D - java

We are trying to draw something with the scene2D from libGDX. We have our main activity then use the extends Androidapplication to initialize our testgame class. Here we define our screen and then make our stage and actors in the screen class.
Problem is that we are getting the same error over and over:
>
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gamepadTest.app/com.gamepadTest.app.MainActivity}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.gamepadTest.app/com.gamepadTest.app.TestGame}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.gamepadTest.app.MainActivity" on path: DexPathList[[zip file "/data/app/com.gamepadTest.app-1.apk"],nativeLibraryDirectories=[/data/app- lib/com.gamepadTest.app-1, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
            
> at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
Have a look:
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
public class MainActivity extends AndroidApplication {
private TestGame testGame = new TestGame();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
initialize(testGame, cfg);
}
}
import com.badlogic.gdx.Game;
public class TestGame extends Game
{
TestScreen testScreen;
#Override
public void create() {
testScreen = new TestScreen();
setScreen(testScreen);
}
#Override
public void dispose() {
testScreen.dispose();
}
}
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class TestScreen implements Screen {
private Stage stage;
private TestActor testActor;
public TestScreen() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
testActor = new TestActor();
stage.addActor(testActor);
}
public void resize(int width, int height) {
stage.setViewport(800, 600, false);
stage.getCamera().translate(-stage.getGutterWidth(), -stage.getGutterHeight(), 0);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage.act(delta);
stage.draw();
}
#Override public void dispose() {
stage.dispose();
}
#Override public void show() {}
#Override public void hide() {}
#Override public void pause() {}
#Override public void resume() {}
}
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.scenes.scene2d.Actor;
public class TestActor extends Actor{
private ShapeRenderer renderer;
#Override
public void act(float delta) {
super.act(delta);
renderer = new ShapeRenderer();
}
#Override
public void draw (SpriteBatch batch, float parentAlpha) {
batch.end();
renderer.setProjectionMatrix(batch.getProjectionMatrix());
renderer.setTransformMatrix(batch.getTransformMatrix());
renderer.translate(getX(), getY(), 0);
renderer.begin(ShapeRenderer.ShapeType.Point);
renderer.rect(0, 0, 100, 100);
renderer.end();
batch.begin();
}
}
UPDATE:
Here is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gamepadTest.app"
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.gamepadTest.app.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

You have to declare your activity TestGame inside your AndroidManifest.xml as <activity>
For more info about the manifest: http://developer.android.com/guide/topics/manifest/manifest-intro.html
Should look something like this, and needs to be inside the <application>-tag:
<activity
android:name="com.example.TestGame"
android:label="#string/app_name" >
</activity>

TestGame isn't an Activity:
public class TestGame extends Game{
The Activity you must declare is MainActivity. So its wierd, probably you made another Activity with that same name. But anyway, try setting it with dot notation instead of the whole package:
<activity
android:name=".TestGame"
android:label="#string/app_name" >
</activity>
See this:
Unable to find explicit activity class

Related

Binding few activities to one service - class which connected treated like service - can't destroy activity

I will start from my approach I want to have one service which is running even if none of application screen is visible for user. This service will scan for beacons.
Every screen of application needs to get access to method of service so I used binding to service here.
I designed serviceconnector class which will be connecting Activities with service, this class look like this.
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
public class ServiceConnector {
Context context;
BeaconScanningService scanningService;
boolean mBound = false;
public ServiceConnector(Context context) {
LogShower.printLogs("Service Connector created");
this.context = context;
createBinding();
}
public void createBinding()
{
Intent intent = new Intent(context, BeaconScanningService.class);
if(scanningService.isBeaconScanningServiceRunning())
{
LogShower.printLogs("Service is already running.");
context.bindService(intent, mConnection, 0);
}
else
{
LogShower.printLogs("Service is not running yet.");
context.startService(new Intent(context, BeaconScanningService.class));
context.bindService(intent, mConnection, 0);
}
}
public void startScanning()
{
LogShower.printLogs("Start Scanning.");
scanningService.startBeaconScanner();
}
public void stopScanning()
{
LogShower.printLogs("Stop Scanning.");
scanningService.stopBeaconScanner();
}
public void destroyBinding()
{
if (mBound) {
scanningService.unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service)
{
LogShower.printLogs("onServiceConnected");
// We've bound to LocalService, cast the IBinder and get LocalService instance
BeaconScanningService.LocalBinder binder = (BeaconScanningService.LocalBinder) service;
scanningService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
LogShower.printLogs("onServiceDisconnected");
mBound = false;
}
};
}
This is activity when I make binding and try to unbind
import android.app.Activity;
import android.os.Bundle;
public class StartScreen extends Activity
{
ServiceConnector serviceConnector ;
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.starting_screen_layout);
serviceConnector = new ServiceConnector(this);
}
#Override
protected void onDestroy ()
{
serviceConnector.destroyBinding();
super.onDestroy();
}
}
Name of service is BeaconScanningService and this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bka.tog.ole" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ZooBeacon"
android:label="#string/app_name" >
</activity>
<service android:enabled="true" android:name=".beaconeserviceandconnector.BeaconScanningService">
</service>
<activity
android:name=".StartScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The problem is that I don't know why my ServiceConnector class is interprete as Service during unbinding process or just I can't make analysis of this logcat.
3405-3405/com.bka.tog.ole E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.bka.tog.ole, PID: 3405
java.lang.RuntimeException: Unable to destroy activity {com.bka.tog.ole/com.bka.tog.ole.StartScreen}: java.lang.IllegalArgumentException: Service not registered: com.bka.tog.ole.beaconeserviceandconnector.ServiceConnector$1#41d2f8d0
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3647)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3665)
at android.app.ActivityThread.access$1400(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1299)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5212)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Service not registered: com.bka.tog.ole.beaconeserviceandconnector.ServiceConnector$1#41d2f8d0
at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:973)
at android.app.ContextImpl.unbindService(ContextImpl.java:1671)
at android.content.ContextWrapper.unbindService(ContextWrapper.java:536)
at com.bka.tog.ole.beaconeserviceandconnector.ServiceConnector.destroyBinding(ServiceConnector.java:59)
at com.bka.tog.ole.StartScreen.onDestroy(StartScreen.java:27)
at android.app.Activity.performDestroy(Activity.java:5412)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1118)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3634)
            at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3665)
            at android.app.ActivityThread.access$1400(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1299)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5212)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
            at dalvik.system.NativeStart.main(Native Method)
What is the reason of this behavior?
In my ServiceConnector class should be:
context.unbindService(mConnection);
instead of this line:
scanningService.unbindService(mConnection);
I don't know how this misscoding come from, but I lost few hours, so be sure that you unbind from context of activity.
Normally i would delete this question, but one person make it favorite so I want to show what was the reason of my error.

I'm getting java.lang.ExceptionInInitializerError launching a libgdx game

I'm trying to develop a simple 2D game using libgdx in Android Studio (0.8.14), but at this point (just with a splash and an empty menu) I'm getting an error, with this LogCat output, when I launch the app (I'm testing on device, Sony Xperia Z1):
12-02 18:01:52.146 24248-24248/com.ak.thesoccerball.android D/dalvikvm﹕ Late-enabling CheckJNI
12-02 18:01:52.196 24248-24248/com.ak.thesoccerball.android W/ActivityThread﹕ Application com.ak.thesoccerball.android can be debugged on port 8100...
12-02 18:01:52.246 24248-24248/com.ak.thesoccerball.android D/dalvikvm﹕ Trying to load lib /data/app-lib/com.ak.thesoccerball.android-1/libgdx.so 0x447c06f0
12-02 18:01:52.246 24248-24248/com.ak.thesoccerball.android D/dalvikvm﹕ Added shared lib /data/app-lib/com.ak.thesoccerball.android-1/libgdx.so 0x447c06f0
12-02 18:01:52.246 24248-24248/com.ak.thesoccerball.android D/dalvikvm﹕ No JNI_OnLoad found in /data/app-lib/com.ak.thesoccerball.android-1/libgdx.so 0x447c06f0, skipping init
12-02 18:01:52.246 24248-24248/com.ak.thesoccerball.android W/dalvikvm﹕ Exception Ljava/lang/NullPointerException; thrown while initializing Lcom/ak/thesoccerball/AKGame;
12-02 18:01:52.246 24248-24248/com.ak.thesoccerball.android D/AndroidRuntime﹕ Shutting down VM
12-02 18:01:52.246 24248-24248/com.ak.thesoccerball.android W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41618d88)
12-02 18:01:52.256 24248-24248/com.ak.thesoccerball.android E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ak.thesoccerball.android, PID: 24248
java.lang.ExceptionInInitializerError
at com.ak.thesoccerball.android.AndroidLauncher.onCreate(AndroidLauncher.java:17)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.ak.thesoccerball.AKGame.<clinit>(AKGame.java:9)
            at com.ak.thesoccerball.android.AndroidLauncher.onCreate(AndroidLauncher.java:17)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:212)
            at android.app.ActivityThread.main(ActivityThread.java:5135)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
            at dalvik.system.NativeStart.main(Native Method)
The classes involved are as follows:
- AndroidLauncher.java
package com.ak.thesoccerball.android;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.ak.thesoccerball.AKGame;
public class AndroidLauncher extends AndroidApplication {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useAccelerometer = false;
config.useCompass = false;
initialize(new AKGame(), config);
}
}
AKGame.java
package com.ak.thesoccerball;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class AKGame extends Game {
public static final int WIDTH = Gdx.graphics.getWidth();
public static final int HEIGHT = Gdx.graphics.getHeight();
public SpriteBatch batch;
#Override
public void create() {
batch = new SpriteBatch();
setScreen(new SplashScreen(this));
}
public void render() {
super.render(); //important!
}
public void dispose() {
batch.dispose();
}
}
And here's the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ak.thesoccerball.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/GdxTheme" >
<activity
android:name="com.ak.thesoccerball.android.AndroidLauncher"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
What am I missing so hard?
Move this code:
public static final int WIDTH = Gdx.graphics.getWidth();
public static final int HEIGHT = Gdx.graphics.getHeight();
into the create() method, for example:
#Override
public void create() {
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
//..
}
The thing is that before the create method gets called the Gdx is still null and cannot be used yet.

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.
Intent i = new Intent(MainActivity.this, GameActivity.class);
Should be declared after
super.onCreate();
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.

Unable to instantiate activity ComponentInfo .. java.lang.NullPointerException

I'm trying to run a simple app using volley and a custom header, it builds with no error, I'm running it directly in my smartphone, but when the app start I get the following log:
06-24 16:35:35.653 1380-1380/com.rep E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rep, PID: 1380
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.rep/com.rep.app.principal.InicioActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:230)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.representemais.app.principal.InicioActivity.<init>(InicioActivity.java:86)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1084)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2126)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.access$800(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5102)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
that's the InicioActivity:
package com.rep.app.principal;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.rep.R;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InicioActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}
private TextView txtDisplay;
RequestQueue queue = Volley.newRequestQueue(this);
public class AutenticacaoLocalTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://192.168.1.15/rep-api/api/clients";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-API-TOKEN", "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8");
return headers;
}
};
queue.add(jsonObjReq);
return true;
} catch (Exception e) {
Log.e("RM", e.getMessage());
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
}
#Override
protected void onCancelled() {
}
}
}
and the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rep"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".app.principal.InicioActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".app.login.LoginActivity"
android:configChanges="keyboardHidden"
android:label="#string/app_name">
</activity>
<activity
android:name=".app.principal.MainActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.cliente.ClienteDetalheActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.login.LoginTelaBloqueada"
android:label="#string/app_name"></activity>
</application>
</manifest>
Initialize your RequestQueue, using Volley.newRequestQueue(this);, in onCreate() after the super.onCreate() call. You are trying to use your Activity from an initializer, which frequently causes problems like this.
Step #1: Replace:
RequestQueue queue = Volley.newRequestQueue(this);
with:
RequestQueue queue = null;
Step #2: Change your onCreate() to be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queue=Volley.newRequestQueue(this);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}

ClassNotFoundException in android program

I'm studyng from the book beginning android games opengl es for android.
I recreated an application to test some of the book's notions, based on his previous examples: here is the code
package com.badlogic.androidgames.glbasics;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class OpenGLBasicsStarter extends ListActivity {
String tests[] = { "GLSurfaceViewTest", "GLGameTest" };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, tests));
}
#Override
protected void onListItemClick(ListView list, View view, int position,
long id) {
super.onListItemClick(list, view, position, id);
String testName = tests[position];
try {
Class clazz = Class
.forName("com.badlogic.androidgames.framework.glbasics." + testName);
Intent intent = new Intent(this, clazz);
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
As you could see, it creates a list of others activities with the list of names reported in the tests array. Now: here there are the codes of the 2 activities:
package com.badlogic.androidgames.glbasics;
import java.util.Random;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
public class GLSurfaceViewTest extends Activity {
GLSurfaceView glView;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
glView = new GLSurfaceView(this);
glView.setRenderer(new SimpleRenderer());
setContentView(glView);
}
#Override
public void onResume() {
super.onPause();
glView.onResume();
}
#Override
public void onPause() {
super.onPause();
glView.onPause();
}
static class SimpleRenderer implements Renderer {
Random rand = new Random(); //crea i numeri random
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.d("GLSurfaceViewTest", "surface created");
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
Log.d("GLSurfaceViewTest", "surface changed: " + width + "x"
+ "height");
}
#Override
public void onDrawFrame(GL10 gl) {
gl.glClearColor(rand.nextFloat(), rand.nextFloat(),
rand.nextFloat(), 1);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
}
}
and
package com.badlogic.androidgames.glbasics;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Screen;
import com.badlogic.androidgames.framework.impl.GLGame;
import com.badlogic.androidgames.framework.impl.GLGraphics;
public class GLGameTest extends GLGame {
#Override
public Screen getStartScreen() {
return new TestScreen(this);
}
class TestScreen extends Screen {
GLGraphics glGraphics;
Random rand = new Random();
public TestScreen(Game game) {
super(game);
glGraphics = ((GLGame) game).getGLGraphics();
}
#Override
public void present(float deltaTime) {
GL10 gl = glGraphics.getGL();
gl.glClearColor(rand.nextFloat(), rand.nextFloat(),
rand.nextFloat(), 1);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
#Override
public void update(float deltaTime) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
}
also, there is the XML manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.badlogic.androidgames.glbasics"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="preferExternal" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="9" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="GL"
android:debuggable="true"
android:theme="#style/AppTheme" >
<activity
android:label="GL Surface View Test"
android:name=".GLSurfaceViewTest"
android:configChanges="keyboard|keyboardHidden|orientation" />
<activity
android:label="GL Game Test"
android:name=".GLGameTest"
android:configChanges="keyboard|keyboardHidden|orientation" />
<activity
android:name=".OpenGLBasicsStarter"
android:label="OpenGL Basics Starter"
android:configChanges="keyboard|keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
</manifest>
Now: when i start the application, evertyhing seems to be fine: it appaers a list with the 2 activities; but when i try to click one, a message appaers on the logcat:
02-01 16:10:20.540: W/System.err(394): java.lang.ClassNotFoundException: com.badlogic.androidgames.framework.glbasics.GLGameTest
02-01 16:10:20.550: W/System.err(394): at java.lang.Class.classForName(Native Method)
02-01 16:10:20.550: W/System.err(394): at java.lang.Class.forName(Class.java:234)
02-01 16:10:20.550: W/System.err(394): at java.lang.Class.forName(Class.java:181)
02-01 16:10:20.550: W/System.err(394): at com.badlogic.androidgames.glbasics.OpenGLBasicsStarter.onListItemClick(OpenGLBasicsStarter.java:26)
02-01 16:10:20.550: W/System.err(394): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
02-01 16:10:20.550: W/System.err(394): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
02-01 16:10:20.550: W/System.err(394): at android.widget.ListView.performItemClick(ListView.java:3513)
02-01 16:10:20.550: W/System.err(394): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
02-01 16:10:20.550: W/System.err(394): at android.os.Handler.handleCallback(Handler.java:587)
02-01 16:10:20.550: W/System.err(394): at android.os.Handler.dispatchMessage(Handler.java:92)
02-01 16:10:20.550: W/System.err(394): at android.os.Looper.loop(Looper.java:123)
02-01 16:10:20.550: W/System.err(394): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-01 16:10:20.550: W/System.err(394): at java.lang.reflect.Method.invokeNative(Native Method)
02-01 16:10:20.550: W/System.err(394): at java.lang.reflect.Method.invoke(Method.java:507)
02-01 16:10:20.550: W/System.err(394): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-01 16:10:20.550: W/System.err(394): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-01 16:10:20.550: W/System.err(394): at dalvik.system.NativeStart.main(Native Method)
02-01 16:10:20.560: W/System.err(394): Caused by: java.lang.NoClassDefFoundError: com.badlogic.androidgames.framework.glbasics.GLGameTest
02-01 16:10:20.560: W/System.err(394): ... 17 more
02-01 16:10:20.560: W/System.err(394): Caused by: java.lang.ClassNotFoundException: com.badlogic.androidgames.framework.glbasics.GLGameTest in loader dalvik.system.PathClassLoader[/mnt/asec/com.badlogic.androidgames.glbasics-1/pkg.apk]
02-01 16:10:20.560: W/System.err(394): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
02-01 16:10:20.560: W/System.err(394): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
02-01 16:10:20.560: W/System.err(394): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
02-01 16:10:20.560: W/System.err(394): ... 17 more
There must be an error on the nomenclature of the packages or classes, but i can't see anything. so where is the problem? Sometimes ago I created a similiar (radically identical) application previously to test other things and i never had errors, so...?
Exception states you're searching for com.badlogic.androidgames.framework.glbasics
Note the "framework"
This is how you're defining your class, where the exception originates...
Class clazz = Class.forName("com.badlogic.androidgames.framework.glbasics." + testName);
But all your classes are....
package com.badlogic.androidgames.glbasics;
No "framework"
Check for your package declaration:
In your classes you have:
package com.badlogic.androidgames.glbasics;
While in the error you posted you need something like:
com.badlogic.androidgames.framework.glbasics.GLGameTest

Categories