В мире программирования ошибки являются неотъемлемой частью разработки. Одна из самых распространенных ошибок, которую может встретить разработчик Android — java.lang.RuntimeException: Unable to start activity. В этой статье мы рассмотрим, что это за ошибка, почему она возникает и как её исправить.
Что такое ошибка java.lang.RuntimeException: Unable to start activity?
Ошибка java.lang.RuntimeException: Unable to start activity возникает в момент запуска приложения и указывает на то, что система не может запустить активность (activity). Сообщение об ошибке выглядит примерно так:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Главная причина ошибки — это проблемы в создании и настройке активности (activity) или фрагментов (fragment) приложения. Чаще всего ошибка возникает из-за отсутствия или неправильно настроенного макета (layout). Также это может быть связано с кодом, который вызывает и настраивает активность.
При разработке приложения на Android, каждая активность должна иметь свой макет (layout), который определяет внешний вид и содержание активности. Если макет не определен или некорректно настроен, то произойдет ошибка и приложение не будет запускаться.
Почему возникает ошибка java.lang.RuntimeException: Unable to start activity?
Ошибка java.lang.RuntimeException: Unable to start activity может возникать по многим причинам. Рассмотрим самые распространенные из них.
1. Проблемы с макетом (layout)
Как мы уже упоминали, одной из причин ошибки может быть неправильно настроенный макет. Это может произойти, например, если в макете указаны несуществующие или неправильно написанные id элементов, которые вызывают NullPointerException при попытке получить к ним доступ в коде:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
2. Ошибка в коде
Другой причиной может быть ошибка в коде, которая приводит к исключению. Например, NullPointerException может возникнуть, если вы пытаетесь выполнить операцию над переменной или объектом, который не был инициализирован:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
3. Проблемы с библиотеками
Ошибка также может быть связана с проблемами в третьесторонних библиотеках, которые использовались при разработке приложения. Иногда это может быть вызвано несовместимостью версий библиотек или неправильной настройкой Gradle.
Как исправить ошибку java.lang.RuntimeException: Unable to start activity?
Итак, мы разобрались, почему может возникнуть ошибка java.lang.RuntimeException: Unable to start activity. Теперь давайте рассмотрим, как её можно исправить.
1. Проверьте макет (layout)
Проверьте, что вы правильно настроили макет (layout) для активности (activity) или фрагментов (fragment). Убедитесь, что каждый элемент имеет правильный id и что они находятся в правильном месте в макете. Если вы нашли ошибку, исправьте её и соберите проект заново.
2. Проверьте код
Проверьте свой код на наличие ошибок и исключений. Убедитесь, что все переменные и объекты были правильно объявлены и инициализированы. Также обратите внимание на вызываемые методы и операции в коде.
3. Используйте правильные версии библиотек
Убедитесь, что используемые вами библиотеки совместимы и не конфликтуют друг с другом. Если у вас есть проблемы с версиями библиотек, то обновите их или измените настройки Gradle.
4. Отследите исключение
При возникновении ошибки java.lang.RuntimeException: Unable to start activity вам будет предоставлен стек трейс (stack trace), который поможет вам найти место, где произошло исключение. Отследите его и попытайтесь исправить его.
В заключении, когда вы столкнулись с ошибкой java.lang.RuntimeException: Unable to start activity, не паникуйте. Эта ошибка может быть вызвана различными причинами, но её можно исправить при помощи базовых методов, которые мы описали выше. На этапе разработки приложения на Android не нужно пытаться запускать все функции сразу, помаленьку, тщательно проверяя и отслеживая ошибки, так вы избежите многих проблем.
i’m trying to study how to make apps for Android.
Following a tutorial made by Google with my modification i get this error
12-26 10:42:23.848: D/dalvikvm(1302): GC_CONCURRENT freed 362K, 15% free 2737K/3216K, paused 70ms+89ms, total 204ms
12-26 10:42:23.898: D/AndroidRuntime(1302): Shutting down VM
12-26 10:42:23.898: W/dalvikvm(1302): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-26 10:42:23.928: E/AndroidRuntime(1302): FATAL EXCEPTION: main
12-26 10:42:23.928: E/AndroidRuntime(1302): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.startactivity/com.example.startactivity.DisplayMessageActivity}: java.lang.NullPointerException
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1234)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.os.Looper.loop(Looper.java:137)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-26 10:42:23.928: E/AndroidRuntime(1302): at java.lang.reflect.Method.invokeNative(Native Method)
12-26 10:42:23.928: E/AndroidRuntime(1302): at java.lang.reflect.Method.invoke(Method.java:511)
12-26 10:42:23.928: E/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-26 10:42:23.928: E/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-26 10:42:23.928: E/AndroidRuntime(1302): at dalvik.system.NativeStart.main(Native Method)
12-26 10:42:23.928: E/AndroidRuntime(1302): Caused by: java.lang.NullPointerException
12-26 10:42:23.928: E/AndroidRuntime(1302): at com.example.startactivity.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:20)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.Activity.performCreate(Activity.java:5104)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-26 10:42:23.928: E/AndroidRuntime(1302): ... 11 more
12-26 10:43:11.418: I/Process(1302): Sending signal. PID: 1302 SIG: 9
this is the code of MainActivity
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.startactivity.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText edit_nome = (EditText) findViewById(R.id.edit_nome);
EditText edit_cognome = (EditText) findViewById(R.id.edit_cognome);
Bundle bundle = new Bundle();
bundle.putString("nome", edit_nome.getText().toString());
bundle.putString("cognome", edit_cognome.getText().toString());
intent.putExtra(EXTRA_MESSAGE, bundle);
startActivity(intent);
}
}
And this is the code of DisplayMessageActivity
public class DisplayMessageActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
String nome = intent.getBundleExtra("nome").toString();
String cognome = intent.getBundleExtra("cognome").toString();
TextView textNome = new TextView(this);
TextView textCognome = new TextView(this);
textNome.setTextSize(40);
textCognome.setTextSize(40);
textNome.setText(nome);
textCognome.setText(cognome);
setContentView(textNome);
setContentView(textCognome);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks for help.
The Google Developer Console shows that my app has received two of the same errors in the past month, but this RuntimeException
doesn’t specify a class or file for which the error stems from. There’s nothing specific that I can see. Below are the error for two different devices:
Samsung Galaxy S8 Active (cruiserlteatt), 4096MB RAM, Android 7.0
Report 1 of 2
java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3045)
at android.app.ActivityThread.handleRelaunchActivity
(ActivityThread.java:4978)
at android.app.ActivityThread.-wrap21 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1648)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6781)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)
Samsung Galaxy S7 (heroqltespr), 4096MB RAM, Android 7.0
Report 2 of 2
java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2947)
at android.app.ActivityThread.handleLaunchActivity
(ActivityThread.java:3008)
at android.app.ActivityThread.handleRelaunchActivity
(ActivityThread.java:4974)
at android.app.ActivityThread.-wrap21 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1656)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6688)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1358)
What could it be causing this error? These are the only two times it happened, and the log provided doesn’t show a java class or xml file like other errors I am able to resolve.
Would greatly appreciate it if someone could help me resolve this,
many thanks.
Problem Description:
I try to get the phone number of my device, get the following error:
FATAL EXCEPTION:
main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dell.myapplication/com.example.dell.myapplication.MainActivity}: java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10035 nor current process has android.permission.READ_PHONE_STATE.
I am a new at android development. I have looked at the errors that have been generated by LogCat but do not know the problem and where to find it based on the errors I received.
Thanks for your help and sorry for the duration!
here is my code:
MainActivity.java
package com.example.dell.myapplication;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public MainActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei = tm.getDeviceId();
String phone = tm.getLine1Number();
Toast.makeText(MainActivity.this, "my IMEI: "+imei, Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,"my phone: "+phone,Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="121dp" />
</RelativeLayout>
LogCat
12-23 12:50:35.013 8789-8789/? D/dalvikvm﹕ Late-enabling CheckJNI
12-23 12:50:35.303 8789-8789/com.example.dell.myapplication I/dalvikvm﹕ Could not find method android.view.ViewGroup.onRtlPropertiesChanged, referenced from method android.support.v7.widget.Toolbar.onRtlPropertiesChanged
12-23 12:50:35.303 8789-8789/com.example.dell.myapplication W/dalvikvm﹕ VFY: unable to resolve virtual method 13332: Landroid/view/ViewGroup;.onRtlPropertiesChanged (I)V
12-23 12:50:35.303 8789-8789/com.example.dell.myapplication D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0007
12-23 12:50:35.308 8789-8789/com.example.dell.myapplication I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
12-23 12:50:35.308 8789-8789/com.example.dell.myapplication W/dalvikvm﹕ VFY: unable to resolve virtual method 408: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
12-23 12:50:35.308 8789-8789/com.example.dell.myapplication D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
12-23 12:50:35.308 8789-8789/com.example.dell.myapplication I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
12-23 12:50:35.308 8789-8789/com.example.dell.myapplication W/dalvikvm﹕ VFY: unable to resolve virtual method 430: Landroid/content/res/TypedArray;.getType (I)I
12-23 12:50:35.308 8789-8789/com.example.dell.myapplication D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
12-23 12:50:35.443 8789-8789/com.example.dell.myapplication D/AndroidRuntime﹕ Shutting down VM
12-23 12:50:35.443 8789-8789/com.example.dell.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x416f02a0)
12-23 12:50:35.468 8789-8789/com.example.dell.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dell.myapplication/com.example.dell.myapplication.MainActivity}: java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10035 nor current process has android.permission.READ_PHONE_STATE.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10035 nor current process has android.permission.READ_PHONE_STATE.
at android.os.Parcel.readException(Parcel.java:1425)
at android.os.Parcel.readException(Parcel.java:1379)
at com.android.internal.telephony.IPhoneSubInfo$Stub$Proxy.getDeviceId(IPhoneSubInfo.java:222)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:249)
at com.example.dell.myapplication.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5206)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
12-23 12:50:35.513 8789-8793/com.example.dell.myapplication D/dalvikvm﹕ GC_CONCURRENT freed 234K, 14% free 9604K/11143K, paused 3ms+3ms, total 49ms
12-23 12:50:48.168 8789-8789/com.example.dell.myapplication I/Process﹕ Sending signal. PID: 8789 SIG: 9
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dell.myapplication" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Solution – 1
Add READ_PHONE_STATE
permission
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
in your manifest file
READ_PHONE_STATE
Allows read only access to phone state.
Note: If both your minSdkVersion and targetSdkVersion values are set
to 3 or lower, the system implicitly grants your app this permission.
If you don’t need this permission, be sure your targetSdkVersion is 4
or higher.Protection level: dangerous
Constant Value:
“android.permission.READ_PHONE_STATE”
Solution – 2
Add Permission READ_PHONE_STATE
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Solution – 3
in your manifest, you need to add followong permission in order to read phone number:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
In your logCat, system tells the you the reason of the error with this line:
Caused by: java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10035 nor current process has android.permission.READ_PHONE_STATE.
Solution – 4
I have this problem and figure out that you need to add READ_PHONE_NUMBERS if your targetSdkVersion
is 31
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
You need to request that permission explicitly also
Today, we will learn about another runtime exception that says Unable to instantiate activity ComponentInfo
.
We will explore different possible reasons that result in java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
. Finally, we will have a solution to eradicate it.
Resolve the java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
Error
Example Code for Error Demonstration (MainActivity.java
file):
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//write your remaining code here
}
Example Code (AndroidManifest.xml
file):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.App"
tools:targetApi="31">
<activity
android:name="MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
When we try to run this while launching an application in the android emulator, we get the error saying java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
.
There are a few possible causes that we must consider to resolve this. All of them are listed below.
-
Make sure that your
Activity
is added to theAndroidManifest.xml
file. Why is it necessary?It is because whenever we want to make a new
Activity
, we must register in ourAndroidManifest.xml
file. Also, verify all the access modifiers. -
We also get this error when we try to view before
onCreate()
, which is incorrect and results in an error stating unable to instantiate activity component info error. -
Another reason for getting
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
is that we have added ourActivity
inAndroidManifest.xml
, which is declared asabstract
. In other words, we can say that theActivity
we are trying to access is declaredabstract
. -
Make sure that we are not missing a preceding dot before an activity path (this thing is causing an error in the example code given above).
-
We also have to face this error if we did not declare our
MainActivity.java
file aspublic
. Also, check if your file is in the right package or not.
Now, we know all the possible reasons. How can we fix it?
See the following solution.
Example Code for Solution (MainActivity.java
file):
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//write your remaining code here
}
Example Code (AndroidManifest.xml
file):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.App"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
We have added a preceding dot before an activity path. We also confirm that our MainActivity.java
file is declared as public
, and we are not trying to access an Activity
declared as abstract
.
Be careful of all the points given as causes because those points are actual solutions if we consider them.