Android Studio: java.lang.RuntimeException: невозможно начать действие

Я новичок, и я делаю игру для Android, модель которой я сделал на Java (на Eclipse).

На самом деле я пытаюсь нарисовать сетку, но когда я бегу, у меня появляется java.lang.RuntimeException: Unable to start activity

Я не очень понимаю, где проблема, пишет, что проблема от setContentView (R.layout.activity_main).

Это мой AndroidManifest.xml:

<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    package = "e.khoig.test2">

    <application
        android:allowBackup = "true"
        android:icon = "@mipmap/ic_launcher"
        android:label = "@string/app_name"
        android:roundIcon = "@mipmap/ic_launcher_round"
        android:supportsRtl = "true"
        android:theme = "@style/AppTheme"
        tools:ignore = "GoogleAppIndexingWarning">
        <activity android:name = ".MainActivity">
            <intent-filter>
                <action android:name = "android.intent.action.MAIN" />

                <category android:name = "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Здесь находится игра и ее создание:

public class Game extends Application {
    TenGame tenGame;

    public void onCreate(){
        super.onCreate();
        tenGame=new TenGame();

    }

    TenGame getTenGame(){
        return tenGame;
    }
}

Тогда это мой GameView, который я рисую и выполняю действия:

public class GameView extends SurfaceView implements SurfaceHolder.Callback{
    Game gam;
    Paint paint=new Paint();
    int canvasWidth;
    int cellSize;

    public GameView(Context context, AttributeSet attributeSet){
        super(context,attributeSet);
        getHolder().addCallback(this);
        getGam(context);
    }

    public GameView(Context context){
        super(context);
        getHolder().addCallback(this);
        this.getGam(context);
    }

    public final void getGam(Context context){
        gam=(Game)(context.getApplicationContext());
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }


    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        canvasWidth=width;
        cellSize=width/5;
        reDraw();
    }


    public void reDraw(){
        Canvas c=getHolder().lockCanvas();
        if (c!=null){
            this.onDraw(c);
            getHolder().unlockCanvasAndPost(c);

        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x=(int)event.getX();
        int y=(int)event.getY();

        int action=event.getAction();
        TenGame theGame=gam.getTenGame();
        switch(action){
            case MotionEvent.ACTION_DOWN:{
                theGame.getSelectedGroup();
            }
            default:
                return false;
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
    @Override
    public void onDraw(Canvas canvas){
        paint.reset();
        TenGame theGame=gam.getTenGame();
        canvas.drawColor(Color.GRAY);

        paint.setColor(Color.BLACK);
        for(int x=0;x<canvasWidth;x+=cellSize){
            canvas.drawLine(x,0,x,canvasWidth,paint);
        }
        for(int y=0;y<canvasWidth;y+=cellSize){
            canvas.drawLine(0,y,canvasWidth,y,paint);
        }

        paint.setTextSize(50);
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);

        for(int x=0;x<5;x++){
            for(int y=0;y<5;y++){
                canvas.drawText("1",(x*cellSize)+11,(cellSize+y*cellSize)-6,paint);
            }
        }
    }
}

И, наконец, моя основная активность:

public class MainActivity extends Activity {
    Game gam;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gam=(Game)this.getApplication();

    }
}

И мой файл activity_main.xml:

<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">

    <TextView
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text = "Hello World!"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintLeft_toLeftOf = "parent"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />

    <e.khoig.test2.GameView
        android:id = "@+id/gameView"
        android:layout_width = "150dp"
        android:layout_height = "150dp"
        android:layout_gravity = "center"
         />

</LinearLayout>

Это мое сообщение об ошибке:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: e.khoig.test2, PID: 15920
java.lang.RuntimeException: Unable to start activity ComponentInfo{e.khoig.test2/e.khoig.test2.MainActivity}: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class e.khoig.test2.GameView
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 Caused by: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class e.khoig.test2.GameView
 Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class e.khoig.test2.GameView
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance0(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
    at android.view.LayoutInflater.createView(LayoutInflater.java:647)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:461)
    at android.app.Activity.setContentView(Activity.java:2737)
    at e.khoig.test2.MainActivity.onCreate(MainActivity.java:12)
    at android.app.Activity.performCreate(Activity.java:7183)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to e.khoig.test2.Game
    at e.khoig.test2.GameView.getGam(GameView.java:34)
    at e.khoig.test2.GameView.<init>(GameView.java:24)

ОБНОВЛЕНИЕ:
Я решил свою проблему, мне просто нужно было объявить приложение в манифесте, спасибо за вашу помощь!

Добро пожаловать в Stack Overflow! Пожалуйста, не помечайте вопросы тегом android-studio только потому, что вы его используете: тег Android Studio Только следует использовать, когда у вас есть вопросы о самой IDE, а не о коде, который вы пишете (или хотите написать) в ней. См. когда уместно удалить тег IDE, Как избежать неправильного использования тегов? и руководство по тегам.

Zoe 07.03.2019 21:51
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
0
1
272
3

Ответы 3

В третьей последней строке вашего трассировки стека указано, что вы не можете привести заявление к экземпляру вашего класса игра.

Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to e.khoig.test2.Game

В вашем основная деятельность после setContentView вы могли бы использовать получитьактивность без это, т.е.

gam = (Game) getActivity();

Я считаю, что сейчас проблема может заключаться в том, что вы пытаетесь преобразовать экземпляр заявление в экземпляр деятельность.

Просто мои два цента.

Я не могу выполнить getActivity().

Rtac 08.03.2019 14:26

Трассировка стека говорит -

Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to e.khoig.test2.Game at e.khoig.test2.GameView.getGam(GameView.java:34)

Вы делаете это -

public final void getGam(Context context){ gam=(Game)(context.getApplicationContext()); }

Вы не должны преобразовывать экземпляр суперкласса в подкласс. Это ведет к вашему ClassCastException.

Этот отвечать дает лучшую картину.

Надеюсь, поможет.

Здравствуйте, спасибо за вашу помощь, тогда что мне делать, чтобы получить приложение?

Rtac 08.03.2019 14:38

Эта трассировка стека показывает это

Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to e.khoig.test2.Game

Потому что это

A extends B
A a = new B()  // this is wrong
(B)a//this is wrong
B b = new A()  // this is right
(A)b // this is right

Вы не можете привести экземпляр суперкласса к подклассу.

Другие вопросы по теме