Android Studio: java.lang.RuntimeException: невозможно запустить действие - PullRequest
0 голосов
/ 07 марта 2019

Я новичок и делаю игру для 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);
            }
        }
    }
}

И, наконец, мой MainActivity:

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)

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

Ответы [ 3 ]

0 голосов
/ 08 марта 2019

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

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.

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

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

0 голосов
/ 08 марта 2019

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

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

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

0 голосов
/ 08 марта 2019

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

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

В вашей основной деятельности после setContentView могли бы вы использовать getActivity без this , т.е.

gam = (Game) getActivity();

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

Только мои два цента.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...