Frage

I have come to some errors in my Android Application, and I simply can't seem to fix it.

Honestly, I don't know a lot about the logcat, since I haven't really recieved errors before. I hope some of your sharp eyes can stop the problem.

My Activity:

package com.comrades.splashscreen;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.plambech.splashscreen.R;


public class GameActivity extends Activity {

    BallView mBallView = null;
    Handler RedrawHandler = new Handler(); //so redraw occurs in main thread
    Timer mTmr = null;
    TimerTask mTsk = null;
    int mScrWidth, mScrHeight;
    android.graphics.PointF mBallPos, mBallSpd;

    AsteroidView mAsteroidView = null;

    private Button startButton;
    private TextView timerValue;

    private long startTime = 0L;

    private Handler customHandler = new Handler();

    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);
        //create pointer to main screen
        final FrameLayout mainView = 
        (android.widget.FrameLayout)findViewById(R.id.game_view);

        //get screen dimensions
        Display display = getWindowManager().getDefaultDisplay();  
        mScrWidth = display.getWidth(); 
        mScrHeight = display.getHeight();
        mBallPos = new android.graphics.PointF();
        mBallSpd = new android.graphics.PointF();

        //create variables for ball position and speed
        mBallPos.x = (mScrWidth/2)-34; 
        mBallPos.y = mScrHeight - 170; 
        mBallSpd.x = 2;

        //create initial ball
        mBallView = new BallView(this, mBallPos.x, mBallPos.y);
        mAsteroidView = new AsteroidView(this, 50, 50);                

        mainView.addView(mBallView); //add ball to main screen
        mainView.addView(mAsteroidView);
        mBallView.invalidate(); //call onDraw in BallView

        //listener for accelerometer, use anonymous class for simplicity
        ((SensorManager)getSystemService(Context.SENSOR_SERVICE)).registerListener(
             new SensorEventListener() {    
                @Override  
                public void onSensorChanged(SensorEvent event) {  
                   //set ball speed based on phone tilt (ignore Z axis)
                   mBallSpd.x = -event.values[0];
                   //timer event will redraw ball
                }
                @Override  
                public void onAccuracyChanged(Sensor sensor, int accuracy) {} //ignore
            },
            ((SensorManager)getSystemService(Context.SENSOR_SERVICE))
            .getSensorList(Sensor.TYPE_ACCELEROMETER).get(0),   
             SensorManager.SENSOR_DELAY_NORMAL);

        timerValue = (TextView) findViewById(R.id.score);

        startButton = (Button) findViewById(R.id.startButton);

        startButton.setOnClickListener(new View.OnClickListener() {     
            public void onClick(View view) {
                startTime = SystemClock.uptimeMillis();
                customHandler.postDelayed(updateTimerThread, 0);

            }
        });

    } //OnCreate

    private Runnable updateTimerThread = new Runnable() {

        public void run() {

            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;
            int milliseconds = (int) (updatedTime % 1000);
            timerValue.setText("" + mins + ":"
                    + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
            customHandler.postDelayed(this, 0);
        }

    };

  //listener for menu button on phone
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        menu.add("Exit"); //only one menu item
        return super.onCreateOptionsMenu(menu);
    }

  //listener for menu item clicked
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection    
        if (item.getTitle() == "Go back") //user clicked Exit
            finish(); //will call onPause
        return super.onOptionsItemSelected(item);    
    }

  //For state flow see http://developer.android.com/reference/android/app/Activity.html
    @Override
    public void onPause() //app moved to background, stop background threads
    {
        mTmr.cancel(); //kill\release timer (our only background thread)
        mTmr = null;
        mTsk = null;
        super.onPause();
    }

    @Override
    public void onResume() //app moved to foreground (also occurs at app startup)
    {
        //create timer to move ball to new position
        mTmr = new Timer(); 
        mTsk = new TimerTask() {
        public void run() {

        //if debugging with external device, 
        //  a log cat viewer will be needed on the device
        android.util.Log.d("TiltBall","Timer Hit - " + mBallPos.x + ":" + mBallPos.y);

      //move ball based on current speed
        mBallPos.x += mBallSpd.x;

      //if ball goes off screen, reposition to opposite side of screen
        if (mBallPos.x > (mScrWidth-68)) {mBallPos.x=mScrWidth-68;}
        if (mBallPos.x < 0) {mBallPos.x=0;}

      //update ball class instance
        mBallView.x = mBallPos.x;
        mBallView.y = mBallPos.y;
        //redraw ball. Must run in background thread to prevent thread lock.
        RedrawHandler.post(new Runnable() {
            public void run() {    
            mBallView.invalidate();
            }});
        }}; // TimerTask

        mTmr.schedule(mTsk,10,10); //start timer
        super.onResume();
        } // onResume

    //listener for config change. 
    //This is called when user tilts phone enough to trigger landscape view
    //we want our app to stay in portrait view, so bypass event 
    @Override 
    public void onConfigurationChanged(Configuration newConfig)
    {
       super.onConfigurationChanged(newConfig);
    }

    public void HighScores () 
    {
        int i = 99999999;
        TextView t = new TextView(this);
        t=(TextView)findViewById(R.id.score);
        t.setText("SCORE: "+i);
    }

} //TiltBallActivity

My XML:

<?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:orientation="vertical"
    android:layout_width="match_parent"
     android:layout_height="match_parent"
    android:id="@+id/game_view"
    android:background="@drawable/space_background">


<TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="37dp"
        android:textSize="40sp"
        android:textColor="@color/yellow"
        android:text="@string/timerVal" 
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <Button
        android:id="@+id/startButton"
        android:layout_width="90dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="191dp"
        android:text="@string/startButtonLabel" />

</RelativeLayout>

And the LOG:

02-24 15:23:03.201: E/AndroidRuntime(1404): FATAL EXCEPTION: main
02-24 15:23:03.201: E/AndroidRuntime(1404): Process: com.plambech.splashscreen, PID: 1404
02-24 15:23:03.201: E/AndroidRuntime(1404): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.plambech.splashscreen/com.comrades.splashscreen.GameActivity}: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.FrameLayout
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.os.Looper.loop(Looper.java:136)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at java.lang.reflect.Method.invokeNative(Native Method)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at java.lang.reflect.Method.invoke(Method.java:515)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at dalvik.system.NativeStart.main(Native Method)
02-24 15:23:03.201: E/AndroidRuntime(1404): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.FrameLayout
02-24 15:23:03.201: E/AndroidRuntime(1404):     at com.comrades.splashscreen.GameActivity.onCreate(GameActivity.java:56)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.Activity.performCreate(Activity.java:5231)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-24 15:23:03.201: E/AndroidRuntime(1404):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-24 15:23:03.201: E/AndroidRuntime(1404):     ... 11 more

Everything happened after I tried to add this timer.

I'm sorry for the length of all the code. But I guess you need it all.

  • Thanks!
War es hilfreich?

Lösung

The log said it all - typo is here:

final FrameLayout mainView = 
    (android.widget.FrameLayout)findViewById(R.id.game_view);

Your game_view is a RelativeLayout, so it should be the following:

final RelativeLayout mainView = 
    (android.widget.RelativeLayout)findViewById(R.id.game_view);

Andere Tipps

android.widget.RelativeLayout cannot be cast to android.widget.FrameLayout

This error tells you everything change your code to this

final RelativeLayout mainView = (android.widget.RelativeLayout)findViewById(R.id.game_view);

The problem is here:

final FrameLayout mainView = 
                        (android.widget.FrameLayout)findViewById(R.id.game_view);

Looking at your LogCat (you need to learn how to read these things):

Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.FrameLayout
at com.comrades.splashscreen.GameActivity.onCreate(GameActivity.java:56)

So on line 56 of your GameActivity.java class, android.widget.RelativeLayout cannot be cast to android.widget.FrameLayout

I would assume you need to change that line to this:

final FrameLayout mainView = 
                     (android.widget.RelativeLayout)findViewById(R.id.game_view);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top