java.lang.RuntimeException: не удается создать экземпляр activity ComponentInfo в Android Studio

#java #android #android-studio

#java — язык #Android #android-студия #java #android-studio

Вопрос:

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

К сожалению, приложение было остановлено

Вот ошибка, отображаемая в Logcat android monitor.

 10-23 23:19:25.882 18014-18014/com.example.dhara.codesprint E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dhara.codesprint, PID: 18014
java.lang.RuntimeException: Unable to start activity ComponentInfo

{com.example.dhara.codesprint/com.example.dhara.codesprint.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2299)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5372)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:970)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.dhara.codesprint.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5258)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1099)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2239)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5372) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:970) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786) 
at dalvik.system.NativeStart.main(Native Method)
  

Ниже приведен код для MainActivity.java

 package com.example.dhara.codesprint;

import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    TextView text1;
    TextView text2;
    TextView text3;
    TextView text4;
    TextView text5;
    TextView text6;
    EditText text7;
    Button checkAnswer;
    Button reset;

    //private WordDictionary dictionary;
    private String currentWord;
    private ArrayList<String> words;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        AssetManager assetManager = getAssets();
        try {
            InputStream inputStream = assetManager.open("words.txt");
        } catch (IOException e) {
            Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
            toast.show();
        }

        text1 = (TextView) findViewById(R.id.textView1);
        text2 = (TextView) findViewById(R.id.textView2);
        text3 = (TextView) findViewById(R.id.textView3);
        text4 = (TextView) findViewById(R.id.textView4);
        text5 = (TextView) findViewById(R.id.textView5);
        text6 = (TextView) findViewById(R.id.textView6);
        text7 = (EditText) findViewById(R.id.edittext);
        checkAnswer = (Button) findViewById(R.id.button);
        reset = (Button) findViewById(R.id.button2);


        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });



        checkAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }





}
  

AndroidMainfest.xml:

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dhara.codesprint">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Codesprint"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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>
  

activity_main.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@ id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/background"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/circle"
        android:layout_marginLeft="13dp"
        android:layout_marginStart="13dp"
        android:layout_marginTop="14dp"
        android:id="@ id/imageView1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/circle"
        android:id="@ id/imageView2"
        android:layout_alignTop="@ id/imageView3"
        android:layout_alignLeft="@ id/imageView5"
        android:layout_alignStart="@ id/imageView5" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/circle"
        android:id="@ id/imageView3"
        android:layout_alignTop="@ id/imageView1"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/circle"
        android:layout_marginTop="27dp"
        android:id="@ id/imageView4"
        android:layout_below="@ id/imageView1"
        android:layout_alignLeft="@ id/imageView1"
        android:layout_alignStart="@ id/imageView1" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/circle"
        android:id="@ id/imageView5"
        android:layout_alignTop="@ id/imageView4"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/circle"
        android:id="@ id/imageView6"
        android:layout_alignTop="@ id/imageView5"
        android:layout_alignLeft="@ id/imageView3"
        android:layout_alignStart="@ id/imageView3" />

    <EditText
        android:text="Your Answer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@ id/imageView5"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="55dp"
        android:id="@ id/edittext"
        android:textSize="20sp"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:textColorLink="?attr/actionMenuTextColor" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="31dp"
        android:id="@ id/textView2"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:layout_alignTop="@ id/imageView2"
        android:layout_alignLeft="@ id/imageView2"
        android:layout_alignStart="@ id/imageView2"
        android:layout_alignRight="@ id/imageView2"
        android:layout_alignEnd="@ id/imageView2"
        android:textColor="@android:color/background_light" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@ id/textView2"
        android:layout_alignRight="@ id/imageView3"
        android:layout_alignEnd="@ id/imageView3"
        android:id="@ id/textView3"
        android:layout_alignLeft="@ id/imageView3"
        android:layout_alignStart="@ id/imageView3"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:textColor="@android:color/background_light" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@ id/imageView4"
        android:layout_alignRight="@ id/imageView4"
        android:layout_alignEnd="@ id/imageView4"
        android:layout_marginTop="30dp"
        android:id="@ id/textView4"
        android:layout_alignLeft="@ id/imageView4"
        android:layout_alignStart="@ id/imageView4"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:textColor="@android:color/background_light" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@ id/textView4"
        android:layout_alignRight="@ id/imageView5"
        android:layout_alignEnd="@ id/imageView5"
        android:id="@ id/textView5"
        android:layout_alignLeft="@ id/imageView5"
        android:layout_alignStart="@ id/imageView5"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:textColor="@android:color/background_light" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@ id/textView5"
        android:layout_alignRight="@ id/imageView6"
        android:layout_alignEnd="@ id/imageView6"
        android:id="@ id/textView6"
        android:layout_alignLeft="@ id/imageView6"
        android:layout_alignStart="@ id/imageView6"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:textColor="@android:color/background_light" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@ id/textView2"
        android:layout_alignRight="@ id/imageView1"
        android:layout_alignEnd="@ id/imageView1"
        android:id="@ id/textView1"
        android:layout_alignLeft="@ id/imageView1"
        android:layout_alignStart="@ id/imageView1"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:textColor="@android:color/background_light" />

    <Button
        android:text="Check Your Answer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:id="@ id/button"
        android:textAlignment="center"
        android:textStyle="normal|bold"
        android:textColor="@android:color/background_light"
        android:background="@color/colorPrimary"
        android:layout_below="@ id/edittext"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="Reset"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="27dp"
        android:id="@ id/button2"
        android:background="@color/colorPrimary"
        android:textSize="14sp"
        tools:textColor="@android:color/background_light" />

</RelativeLayout>
  

Я попробовал какое-то решение из Интернета, но оно не работает.

Комментарии:

1. Caused by: java.lang.NullPointerException

Ответ №1:

В вашем макете нет Toolbar , и все же вы вызываете следующее:

 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
  

Либо удалите эти вызовы, либо добавьте Toolbar в свой макет.

Для работы последнего вам также необходимо использовать (или производную от) одну из тем AppCompat, у которых нет ActionBar , Theme.AppCompat.Light.NoActionBar например.

Итак, в вашем styles.xml у вас было бы что-то вроде этого:

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
  

Ответ №2:

Вы не можете инициировать элементы просмотра (TextView, кнопки и т.д.) Перед настройкой XML-макета, который в вашем случае является R.layout.activity_main файлом.

 package com.example.dhara.codesprint;

import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


    //private WordDictionary dictionary;
    private String currentWord;
    private ArrayList<String> words;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView text1 = (TextView) findViewById(R.id.textView1);
        TextView text2 = (TextView) findViewById(R.id.textView2);
        TextView text3 = (TextView) findViewById(R.id.textView3);
        TextView text4 = (TextView) findViewById(R.id.textView4);
        TextView text5 = (TextView) findViewById(R.id.textView5);
        TextView text6 = (TextView) findViewById(R.id.textView6);
        TextView text7 = (TextView) findViewById(R.id.edittext);
        Button checkAnswer = (Button) findViewById(R.id.button);
        Button reset = (Button) findViewById(R.id.button2);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        AssetManager assetManager = getAssets();
        try {
            InputStream inputStream = assetManager.open("words.txt");
        } catch (IOException e) {
            Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
            toast.show();
        }


        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });



        checkAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }
}
  

Ответ №3:

Пожалуйста, инициализируйте свой элемент layouts в onCreate () , потому что, когда ваша activity запускается, она вызывает метод onCreate () , но здесь вы вызываете свой макет из своего метода onCreate () , но после этого вы не инициализируете свои элементы, также проверьте, добавили ли вы имя activity в свой манифест или нет, пожалуйста, внимательно прочитайте и реализуйте, надеюсь, это вам поможет.