Я новичок, и я делаю игру для 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)
ОБНОВЛЕНИЕ:
Я решил свою проблему, мне просто нужно было объявить приложение в манифесте, спасибо за вашу помощь!




В третьей последней строке вашего трассировки стека указано, что вы не можете привести заявление к экземпляру вашего класса игра.
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to e.khoig.test2.Game
В вашем основная деятельность после setContentView вы могли бы использовать получитьактивность без это, т.е.
gam = (Game) getActivity();
Я считаю, что сейчас проблема может заключаться в том, что вы пытаетесь преобразовать экземпляр заявление в экземпляр деятельность.
Просто мои два цента.
Я не могу выполнить getActivity().
Трассировка стека говорит -
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.
Этот отвечать дает лучшую картину.
Надеюсь, поможет.
Здравствуйте, спасибо за вашу помощь, тогда что мне делать, чтобы получить приложение?
Эта трассировка стека показывает это
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
Вы не можете привести экземпляр суперкласса к подклассу.
Добро пожаловать в Stack Overflow! Пожалуйста, не помечайте вопросы тегом android-studio только потому, что вы его используете: тег Android Studio Только следует использовать, когда у вас есть вопросы о самой IDE, а не о коде, который вы пишете (или хотите написать) в ней. См. когда уместно удалить тег IDE, Как избежать неправильного использования тегов? и руководство по тегам.