thread is throwing error (frame animation) - android

I am working on frame animation in which i am using thread but thread is throwing me error .
my code is as follow ....
public class Newton_LawsActivity extends Activity implements OnTouchListener, OnGestureListener,OnDoubleTapListener {
/** Called when the activity is first created. */
OnTouchListener l;
ImageView animation;
ImageView hideimage;
TextView t;
Thread timer;
int Rid;
double pixel;
String law="null";
private GestureDetector gestureDetector;
float x,y;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(this);
// the frame-by-frame animation defined as a xml file within the drawable folder
animation = (ImageView)findViewById(R.id.image);
//animation.setBackgroundResource(R.drawable.anatomy_5);
hideimage=(ImageView)findViewById(R.id.imagein);
t=(TextView) findViewById(R.id.t);
animation.setBackgroundResource(R.anim.startanimation);
final AnimationDrawable newtonAnimation = (AnimationDrawable) animation.getBackground();
AnimationStart(newtonAnimation);
animation.setOnTouchListener(this);
}
public void AnimationStart(final AnimationDrawable newanimation){
timer=new Thread(){
#Override
public void run(){
try{
}catch(Exception e){}
finally{
Newton_LawsActivity.this.runOnUiThread(new Runnable() {
public void run(){
newanimation.start();
}});
}
}
};
timer.start();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Toast.makeText(this, "animation", Toast.LENGTH_LONG).show();
return gestureDetector.onTouchEvent(event);
}
private void animationswitch(float x, float y) {
// TODO Auto-generated method stub
pixel = getmaskpixel(x,y,animation,hideimage);
Log.w("DEBUG","which is null:pixel" + pixel );
if (pixel==-583672){
animation.setBackgroundResource(R.anim.firstlaw_01);
final AnimationDrawable firstlaw_01 = (AnimationDrawable) animation.getBackground();
law="firstlaw_02";
firstlaw_01.start();
animationstop_01();
}
t.setText(Double.toString(pixel));
}
private double getmaskpixel(float x, float y, ImageView view,ImageView hideimage) {
// TODO Auto-generated method stub
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.touchnewtonfinal415);
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) view.getWidth()) / width;
float scaleHeight = ((float) view.getHeight()) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// matrix.postRotate(90);
// recreate the new Bitmap
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, width, height,matrix, false);
Log.w("DEBUG","which is null:image " + hideimage.getWidth() + " OR " +hideimage.getHeight() );
double bmWidth = view.getWidth();
double bmHeight = view.getHeight();
if ( x < 0 || y < 0 || x > hideimage.getWidth() || y >hideimage.getHeight()){
return 0; //Invalid, return 0
}else{
//Convert touched x, y on View to on Bitmap
int xBm = (int)(x * (bmWidth / hideimage.getWidth()));
int yBm = (int)(y * (bmHeight / hideimage.getHeight()));
return bitmap.getPixel((int)xBm,(int) yBm);
}
}
public boolean onSingleTapUp(MotionEvent e) {
return false;
// TODO Auto-generated method stub
}
#Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onDoubleTap(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// TODO Auto-generated method stub
x=e.getX();
y= e.getY();
Log.w("DEBUG","which is null:image " + x + " OR " +y);
animationswitch(x, y);
return true;
}
void animationstop_01(){
if(law=="firstlaw_02"){
timer=new Thread(){
#Override
public void run(){
try{
Thread.sleep(8750);
}catch(Exception e){}
finally{
Log.w("debug","it is firstlaw_02");
animation.setBackgroundResource(R.anim.firstlaw_02);
final AnimationDrawable firstlaw_02 = (AnimationDrawable) animation.getBackground();
law="firstlaw_03";
AnimationStart(firstlaw_02);
}};
};
timer.start();
}
}
}
it is throwing me following error..
06-06 14:15:00.668: E/AndroidRuntime(966): FATAL EXCEPTION: Thread-10
06-06 14:15:00.668: E/AndroidRuntime(966): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
06-06 14:15:00.668: E/AndroidRuntime(966): at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
06-06 14:15:00.668: E/AndroidRuntime(966): at android.view.ViewRoot.invalidateChild(ViewRoot.java:607)
06-06 14:15:00.668: E/AndroidRuntime(966): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633)
06-06 14:15:00.668: E/AndroidRuntime(966): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505)
06-06 14:15:00.668: E/AndroidRuntime(966): at android.view.View.invalidate(View.java:5139)
06-06 14:15:00.668: E/AndroidRuntime(966): at android.view.View.setBackgroundDrawable(View.java:7486)
06-06 14:15:00.668: E/AndroidRuntime(966): at android.view.View.setBackgroundResource(View.java:7395)
06-06 14:15:00.668: E/AndroidRuntime(966): at Newtons.law.Newton_LawsActivity$2.run(Newton_LawsActivity.java:183)

Change your animationstop_01 method to:
void animationstop_01(){
if(law=="firstlaw_02"){
timer=new Thread(){
#Override
public void run(){
try{
Thread.sleep(8750);
}catch(Exception e){
}finally{
Log.w("debug","it is firstlaw_02");
Newton_LawsActivity.this.runOnUiThread(new Runnable() {
public void run(){
animation.setBackgroundResource(R.anim.firstlaw_02);
final AnimationDrawable firstlaw_02 = (AnimationDrawable) animation.getBackground();
law="firstlaw_03";
AnimationStart(firstlaw_02);
}
});
}
};
};
timer.start();
}
}

Error is inside the mehod name animationstop_01() where you are trying,
animation.setBackgroundResource(R.anim.firstlaw_02);
put that inside runOnUiThread()

try this:
animation.post(new Runnable() {
public void run() {
animation.setBackgroundResource(R.anim.firstlaw_02);
}
});
In that way you are posting it to the UI thread. View can only be changed from the original thread that created the View.

Related

TabPageIndicator.scrollTo is not working

I want to implement interactive TabPageIndicatot in android. I am using ViewPager.TabPageIndicator to make object of indicator.I am trying to implement scrollTo in TabPageIndicator class.
This is the code in my class. indicator is object of TabPageIndicator.
public void onPageScrolled(int pageNo, float arg1, final int arg2) {
// TODO Auto-generated method stub
indicator.scrollTo(arg2, 0);
}
This is the code in TabPageIndicator class.
private void animateToTab(final int x) {
if (mTabSelector != null) {
removeCallbacks(mTabSelector);
}
mTabSelector = new Runnable() {
public void run() {
// final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2;
smoothScrollTo(x, 0);
mTabSelector = null;
}
};
post(mTabSelector);
}
#Override
public void scrollTo(int x, int y) {
// TODO Auto-generated method stub
super.scrollTo(x, y);
//Log.i("Hi", Integer.toString(x));
animateToTab(x);
}
Here animateToTab() function is called infinite times. Why?

pan 3D model using libgdx

I am trying to pan a 3d object but it does not seem to work. I make a swipe gesture towards the left and right to pan the object along the x-axis. I have added a Log statement and that clearly shows me the pan values in the logcat but still the object doesnt move.
Here is my code
public class 3DTest implements ApplicationListener, GestureListener {
public ModelBatch modelBatch;
public Model model;
public ModelInstance instance;
public Environment environment;
public OrthographicCamera camera;
public CameraInputController camController;
public PerspectiveCamera cam;
public ModelLoader loader;
#Override
public void create() {
// TODO Auto-generated method stub
InputMultiplexer im = new InputMultiplexer();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
camera = new OrthographicCamera(1280, 720);
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(1f, 1f, 1f);
cam.lookAt(0,0,0);
cam.near = 0.1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
loader = new ObjLoader();
model = loader.loadModel(Gdx.files.internal("data/cube.obj"));
instance = new ModelInstance(model);
im.addProcessor(new GestureDetector(this));
im.addProcessor(camController);
Gdx.input.setInputProcessor(im);
}
#Override
public void dispose() {
// TODO Auto-generated method stub
modelBatch.dispose();
model.dispose();
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void render() {
// TODO Auto-generated method stub
camController.update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instance, environment);
modelBatch.end();
}
#Override
public void resize(int arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public boolean fling(float arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean longPress(float arg0, float arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean pan(float arg0, float arg1, float arg2, float arg3) {
// TODO Auto-generated method stub
Log.i("App","pan" +arg2);
camera.translate(arg2, 0);
camera.update();
return false;
}
#Override
public boolean panStop(float arg0, float arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean pinch(Vector2 arg0, Vector2 arg1, Vector2 arg2, Vector2 arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean tap(float arg0, float arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(float arg0, float arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean zoom(float arg0, float arg1) {
// TODO Auto-generated method stub
return false;
}
}
cam.position.set(1f, 1f, -10f);
Change your "z" (the third parameter) in cam.
It works fine.

Killing a Sprite in AndEngine

Hi im having a bit of problems getting my sprite to fade back in. Im using paralell entity modifiers, scaling and fading after which the sprite gets new X and Y cordinates and fades in and scales back up. It doesnt work and i think it might have something to do with the onUpdate method.
XOsprite = new Sprite(x, y, XO, engine.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent te, final float xVal,
final float yVal) {
XOsprite.registerEntityModifier(downOut); //kill sprite
isKilled = true;
XOsprite.registerUpdateHandler(new IUpdateHandler() {
#Override
public void reset() {
// TODO Auto-generated method stub
}
#Override
public void onUpdate(float pSecondsElapsed) {
// TODO Auto-generated method stub
totalElapsedTime += pSecondsElapsed;
if(totalElapsedTime >= 3.0f){
BaseGameActivity gameActivity = (BaseGameActivity) activity;
gameActivity.runOnUpdateThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(isKilled){
reviveSprite();
isKilled = false;
}
}
});
}
//reset();
}
});
return true;
}
};
XOsprite.registerEntityModifier(inUp);
gameScene.attachChild(XOsprite);
gameScene.registerTouchArea(XOsprite);
return gameScene;
}
-edit- more code
public void reviveSprite(){
setSprites();
XOsprite.unregisterEntityModifier(downOut);
XOsprite.registerEntityModifier(inUp);
}
public void setSprites(){
if (rand.nextInt(2) == 0) {
XO = X;
} else {
XO = O;
}
x = rand.nextInt(MainActivity.CAM_WIDTH);
y = rand.nextInt(MainActivity.CAM_HEIGHT);
}
you are already on the UpdateThread, so no need to do this
gameActivity.runOnUpdateThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(isKilled){
reviveSprite();
isKilled = false;
}
}
});
just do this
if(isKilled){
reviveSprite();
isKilled = false;
}

NullPointerException when trying to get information

I am trying to do a basic game.I have classes named Ball.java , Scratch.java and Panel.java
In Panel,I am trying to get information from Ball.java class but I am getting NullPointerException.Where is the mistake in my code?
Getting exceiption in this code in Panel.java
public Rect getBoundsBall(){
return new Rect (top.getX(), top.getY(),top.getX()+ball.getWidth() ,top.getY()+ball.getHeight() );
}
Error Log
10-13 12:57:28.746: E/AndroidRuntime(367): FATAL EXCEPTION: Thread-10
10-13 12:57:28.746: E/AndroidRuntime(367): java.lang.NullPointerException
10-13 12:57:28.746: E/AndroidRuntime(367): at com.emredavarci.denemeler.Panel.getBoundsBall(Panel.java:44)
10-13 12:57:28.746: E/AndroidRuntime(367): at com.emredavarci.denemeler.Panel.update(Panel.java:70)
10-13 12:57:28.746: E/AndroidRuntime(367): at com.emredavarci.denemeler.TutorialThread.run(TutorialThread.java:30)
Panel.java
public class Panel extends SurfaceView implements SurfaceHolder.Callback {
private TutorialThread _thread;
Scratch raket=new Scratch();
Ball top=new Ball();
Bitmap ball;
Bitmap _scratch;
public Panel(Context context) {
super(context);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this); /
setFocusable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) { // to
switch (event.getAction()){
case MotionEvent.ACTION_MOVE: //
raket.setX((int)(event.getX()));
break;
}
return true;
}
public Rect getBoundsBall(){
return new Rect (top.getX(), top.getY(),top.getX()+ball.getWidth() ,top.getY()+ball.getHeight() );
}
public Rect getBoundsScratch(){
return new Rect (raket.getX(), raket.getY(),raket.getX()+_scratch.getWidth() ,raket.getY()+_scratch.getHeight() );
}
public void update(){ /
if((top.getX()<480) && (top.getX()>0)){
top.setX(top.getX()+top.getxdirection());
}
if((top.getX()==480) || (top.getX()==0)){
top.setxdirection(-1);
top.setX(top.getX()+top.getxdirection());
}
if((top.getY()<780) && (top.getY()>0)){
top.setY(top.getY()+top.getydirection());
}
if((top.getY()==780) || (top.getY()==0)){
top.setydirection(-1);
top.setY(top.getY()+top.getydirection());
}
Rect BallBounds = getBoundsBall();
Rect ScratchBounds = getBoundsScratch();
if( BallBounds.intersect(ScratchBounds) ){
top.setydirection(-1);
//top.setY(top.getY()); !!!!
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
_thread.setRunning(true);
_thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// simply copied from sample application LunarLander:
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
#Override
public void onDraw(Canvas canvas) {
_scratch = BitmapFactory.decodeResource(getResources(), R.drawable.red2);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(_scratch, raket.getX() - (_scratch.getWidth() / 2), raket.getY() - (_scratch.getHeight() / 2), null);
canvas.drawBitmap(ball, top.getX() - (ball.getWidth() / 2), top.getY() - (ball.getHeight() / 2), null);
}
}
Ball.java
public class Ball {
private int x=100; // the X coordinate
private int y=100; // the Y coordinate
int xdirection=10;
int ydirection=10;
public Ball() {
// TODO Auto-generated constructor stub
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setX(int a){
x=a;
}
public void setY(int b){
y=b;
}
public int getxdirection(){
return xdirection;
}
public int getydirection(){
return ydirection;
}
public void setxdirection(int a){
xdirection=xdirection*a;
}
public void setydirection(int b){
ydirection=ydirection*b;
}
//while ile ball u hareket ettir
//ball un koordinatlarını sakla
}
Scratch.java
public class Scratch {
private int x = 250;
private int y = 600;
public Scratch() {
// TODO Auto-generated constructor stub
}
public void setX(int a){
x=a;
}
public void setY(int b){
y=b;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
You are missing something like:
Ball top = new Ball();
i.e. the variable top is not initialized, but used in the update method.
Also, initialize the ball object outsite of onDraw. Who knows if update will be called before onDraw?
Adding to #Rudolph's answer, are you sure Bitmap ball is initialized? To be sure, try logging ball as:
public Rect getBoundsBall(){
log.v("ball",""+ball);
return new Rect (top.getX(), top.getY(),top.getX()+ball.getWidth() ,top.getY()+ball.getHeight() );
}
Either ball or top is the culprit. Find out which one is uninitialized and tackle it accordingly.

Rotate Mapview error on debug

i developed a map who can rotate the direction view depend where the user face (example, if the user turn into south,than map will rotating to south direction, like compass). I already tried this project with minimal success for a couple week. I have no error message on eclipse,but when i debug the code, the application always crash.
Thanks,i really need all the help
private class RotateView extends ViewGroup {
private Matrix mMatrix = new Matrix();
private float[] mTemp = new float [2];
private static final float SQ2 = 1.414213562373095f;
public RotateView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void dispatchDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.rotate(-mHeading,getWidth()*0.5f , getHeight()*0.5f);
canvas.getMatrix(mMatrix);
super.dispatchDraw(canvas);
canvas.restore();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
final int width = getWidth();
final int height = getHeight();
final int count = getChildCount();
for (int i=0; i<=count; i++){
final View view = getChildAt(i);
final int childWidth = view.getMeasuredWidth();
final int childHeight = view.getMeasuredHeight();
final int childLeft = ((width - childWidth)/2);
final int childTop = ((height-childHeight)/2);
view.layout(childLeft, childTop, childLeft+childWidth, childTop+childHeight);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int mW = getDefaultSize(getMeasuredWidth(), widthMeasureSpec);
int mH = getDefaultSize(getMeasuredHeight(), heightMeasureSpec);
int sizeSpec;
if(mW > mH){
sizeSpec = MeasureSpec.makeMeasureSpec((int)(mW*SQ2), MeasureSpec.EXACTLY);
} else {
sizeSpec = MeasureSpec.makeMeasureSpec((int) (mH*SQ2), MeasureSpec.EXACTLY);
}
final int count = getChildCount();
for(int i = 0; i<count; i++){
getChildAt(i).measure(sizeSpec, sizeSpec);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
public boolean dispatchTouchEvent(MotionEvent e) {
// TODO Auto-generated method stub
return super.dispatchTouchEvent(e);
}
}
// End of class RotateView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensormanager =(SensorManager)getSystemService(SENSOR_SERVICE);
rotateview = new RotateView(this);
map = new MapView (this,"Map Key");
rotateview.addView(map);
setContentView(rotateview);
controll();
}
public void controll () {
controller = map.getController();
//Zoom
map.setBuiltInZoomControls(true);
controller.setZoom(19);
overlayList = map.getOverlays();
map.setClickable(true);
map.setEnabled(true);
//compass
compass = new MyLocationOverlay(MapIpbActivity.this, map);
overlayList.add(compass);
myLocation();
Touchy t = new Touchy();
overlayList.add(t);
}
public void myLocation() {
ourLocation = new MyLocationOverlay(MapIpbActivity.this, map);
map.getOverlays().add(ourLocation);
ourLocation.runOnFirstFix(new Runnable() {
public void run(){
controller.animateTo(ourLocation.getMyLocation());
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
ourLocation.disableMyLocation();
sensormanager.unregisterListener(orientListener);
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
compass.enableCompass();
ourLocation.enableMyLocation();
sensormanager.registerListener(orientListener,
sensormanager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
sensormanager.SENSOR_DELAY_NORMAL);
}
final SensorEventListener orientListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType() == Sensor.TYPE_ORIENTATION){
mHeading = event.values[0];
rotateview.invalidate();
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
class Touchy extends Overlay {
long start;
long stop;
int x;
int y;
GeoPoint TouchedPoint;
#Override
public boolean onTouchEvent(MotionEvent e, MapView m) {
// TODO Auto-generated method stub
if(e.getAction() == MotionEvent.ACTION_DOWN) {
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
TouchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop = e.getEventTime();
}if (stop - start > 2000){
box();
return true;
}
return false;
}
Solved this, just change i<=count into i<count, and everything will work! But my zoom and compass didn't show.

Categories

Resources