Меню

Java lang runtimeexception ошибка андроид

I was trying to run a sample code
While launching the application in the android 1.5 emulator , I got these errors….
Any one have some hint..?

ERROR from LogCat:

01-13 02:28:08.392: ERROR/AndroidRuntime(2888): FATAL EXCEPTION: main
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.s.android.test/com.s.android.test.MainActivity}: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1544)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Looper.loop(Looper.java:123)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invoke(Method.java:507)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.NativeStart.main(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): Caused by: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1536)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     ... 11 more
01-13 02:28:08.407: WARN/ActivityManager(112):   Force finishing activity com.s.android.test/.MainActivity

Edit
This error happens to most of the beginners, the thing is that you have to add all your activities in the Manifest file.

Braiam's user avatar

asked Jan 14, 2011 at 5:37

rahul's user avatar

4

It is a problem of your Intent.

Please add your Activity in your AndroidManifest.xml.

When you want to make a new activity, you should register it in your AndroidManifest.xml.

Mohsen Kamrani's user avatar

answered Jan 14, 2011 at 6:45

Tanmay Mandal's user avatar

Tanmay MandalTanmay Mandal

39.6k12 gold badges51 silver badges48 bronze badges

5

You may be trying to find the view before onCreate() which is incorrect.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect

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

answered Nov 18, 2013 at 13:50

SMUsamaShah's user avatar

SMUsamaShahSMUsamaShah

7,47722 gold badges88 silver badges129 bronze badges

3

There is another way to get an java.lang.RuntimeException: Unable to instantiate activity ComponentInfo exception and that is the activity that you are trying to start is abstract. I made this stupid mistake once and its very easy to overlook.

answered Dec 6, 2011 at 15:38

Kevin's user avatar

KevinKevin

1,68613 silver badges16 bronze badges

5

In my case I forgot to add the google maps library

<application>
    ....

    <uses-library android:name="com.google.android.maps" />
</application>

Also, check that you’re not missing the preceding dot before the activity path

<activity android:name=".activities.MainActivity"/>

answered Apr 29, 2011 at 10:43

Maragues's user avatar

MaraguesMaragues

37.4k14 gold badges94 silver badges96 bronze badges

1

Image

It also happens because of this issue. I unchecked the jars that needed be exported to the apk and this same thing happened. Please tick the jars that your app Needs to run.

answered Jul 2, 2013 at 11:35

meowmeowbeans's user avatar

1

This might not be relevant to the actual question, but in my instance, I tried to implement Kotlin and left out apply plugin: 'kotlin-android'. The error happened because it could not recognize the MainActivity in as a .kt file.

Hope it helps someone.

answered Dec 13, 2016 at 18:08

Muz's user avatar

MuzMuz

5,7773 gold badges47 silver badges64 bronze badges

2

I encountered this problem too, but in a slightly different way. Here was my scenario:

App detail:

  • Using ActionBarSherlock as a library
  • Using android-support-v4-r7-googlemaps.jar in the ActionBarSherlock library so I could use a «map fragment» in my primary project
  • Added the jar to the build path of my primary project
  • Included the <uses-library android:name="com.google.android.maps" /> in the manifests of both the library project and my primary project (this may not be necessary in the library?)
  • The manifest in the primary project had the proper activity definition and all of the appropriate properties
  • I didn’t have an abstract activity or any of the other gotchas I’ve seen on Stack Overflow pertaining to this problem.

However, I still encountered the error described in the original post and could not get it to go away. The problem though, was slightly different in one regard:

  • It only affected a fresh install of the application to my device. Any time the app installed for the first time, I would get the error preceded by several «warnings» of: Unable to resolve superclass of FragmentActivity
  • Those warnings traced back to the ActionBarSherlock library
  • The app would force close and crash.
  • If I immediately rebuilt and redeployed the app, it worked fine.
  • The only time it crashed was on a totally fresh install. If I uninstalled the app, built and deployed again from Eclipse, it would crash. Build/deploy a second time, it would work fine.

How I fixed it:

  • In the ActionBarSherlock library project, I added the android-support-v4-r7-googlemaps.jar to the build path
  • This step alone did not fix the problem

  • Once the jar was added to the build path, I had change the order on the Java Build Path > Order and Export tab — I set the JAR to the first item in the list (it was the last after the /src and /gen items).

  • I then rebuilt and redeployed the app to my device — it worked as expected on a fresh install. Just to be certain, I uninstalled it again 2-3 times and reinstalled — still worked as expected.

This may be a total rookie mistake, but I spent quite a while digging through posts and my code to figure it out, so hopefully it can be helpful to someone else. May not fix all situations, but in this particular case, that ended up being the solution to my problem.

answered Oct 12, 2012 at 12:29

Kyle's user avatar

KyleKyle

6065 silver badges16 bronze badges

1

This error can also be the ultimate sign of a dumb mistake (like when I — I mean, cough, like when a friend of mine who showed me their code once) where they try to execute code outside of a method like trying to do this:

SQLiteDatabase db = openOrCreateDatabase("DB", MODE_PRIVATE, null); //trying to perform function where you can only set up objects, primitives, etc

@Override
public void onCreate(Bundle savedInstanceState) {
....
}

rather than this:

SQLiteDatabase db;

@Override
public void onCreate(Bundle savedInstanceState) {
db = openOrCreateDatabase("DB", MODE_PRIVATE, null);
....
}

answered Oct 29, 2013 at 20:15

Chris Klingler's user avatar

Chris KlinglerChris Klingler

5,2282 gold badges37 silver badges43 bronze badges

1

For me, my package string in AndroidManifest.xml was incorrect (copied from a tutorial).
Make sure the package string in this file is the same as where your main activity is, e.g.

 package="com.example.app"

An easy way to do this is to open the AndroidManifest.xml file in the «Manifest» tab, and type it in the text box next to Package, or use the Browse button.

Also, the package string for my activity was wrong, e.g.

<activity android:name="com.example.app.MainActivity" android:label="@string/app_name">

I (stupidly) got the same error weeks later when I renamed my package name. If you do this, make sure you update the AndroidManifest.xml file too.

Jared Burrows's user avatar

Jared Burrows

53.8k23 gold badges151 silver badges185 bronze badges

answered Aug 27, 2012 at 8:36

satyrFrost's user avatar

satyrFrostsatyrFrost

3938 silver badges17 bronze badges

1

I got rid of this problem by deleting the Bin and Gen folder from project(which automatically come back when the project will build) and then cleaning the project from ->Menu -> Project -> clean.

Thanks.

answered Apr 6, 2013 at 10:07

Jagdeep Singh's user avatar

Jagdeep SinghJagdeep Singh

1,1901 gold badge16 silver badges34 bronze badges

Simply Clean your working project or restart eclipse. Then run your project. it will work.

answered Jul 16, 2014 at 6:01

Emran Hamza's user avatar

Emran HamzaEmran Hamza

3,8091 gold badge24 silver badges20 bronze badges

1

In my case I haven’t set the setContentView(R.layout.main);

If you create a new class do not foget to set this in on onCreate(Bundle savedInstanceState) method.

I have done this stupid mistake several times.

answered Jan 25, 2012 at 6:59

saji159's user avatar

saji159saji159

3287 silver badges14 bronze badges

For me it was different from any of the above,

The activity was declared as abstract, That is why giving the error.
Once it removed it worked.

Earlier

     public abstract class SampleActivity extends AppcompatActivity{
     }

After removal

     public class SampleActivity extends AppcompatActivity{
     }

answered Jan 9, 2020 at 12:30

Thriveni's user avatar

ThriveniThriveni

7328 silver badges11 bronze badges

0

Ok, I am fairly experienced on the iPhone but new to android. I got this issue when I had:

Button infoButton = (Button)findViewById(R.id.InfoButton);

this line of code above:

@Override
public void onCreate (Bundle savedInstanceState) {
}

May be I am sleep deprived 😛

answered Jun 19, 2012 at 15:09

iSee's user avatar

iSeeiSee

6041 gold badge14 silver badges31 bronze badges

1

In my case, I was trying to initialize the components(UI) even before the onCreate is called for the Activity.

Make sure your UI components are initialized/linked in the onCreate method after setContentView

NB: This is my first mistake while learning Android programming.

answered Apr 12, 2019 at 16:20

Anup H's user avatar

Anup HAnup H

5096 silver badges10 bronze badges

1

I recently encountered this with fresh re-install of Eclipse. Turns out my Compiler compliance level was set to Java 1.7 and project required 1.6.

In Eclipse:
Project -> Properties -> Java Compiler -> JDK Compliance

answered Oct 24, 2012 at 7:24

J.G.Sebring's user avatar

J.G.SebringJ.G.Sebring

5,8841 gold badge30 silver badges42 bronze badges

Whow are there lots of ways to get this error!.

I will add another given none of the others either applied or were the cause.

I forgot the ‘public‘ in the declaration of my activity class! It was package private.

I had been writing so much Bluetooth code that habit caused me to create an activity class that was package private.

Says something about the obscurity of this error message.

answered Jul 25, 2020 at 0:40

Brian Reinhold's user avatar

Brian ReinholdBrian Reinhold

2,3113 gold badges25 silver badges44 bronze badges

Make sure MainActivity is not «abstract».

abstract class MainActivity : AppCompatActivity()

just remove the abstract

class MainActivity : AppCompatActivity() {

answered Sep 29, 2021 at 11:54

Amit Singh's user avatar

Amit SinghAmit Singh

5094 silver badges6 bronze badges

Got this problem, and fixed it by setting the «launch mode» property of the activity.

answered Apr 6, 2012 at 13:28

Zorglube's user avatar

Another reason of this problem may be a missing library.

Go to Properties -> Android and check that you add the libraries correctly

answered Mar 7, 2013 at 10:39

ayalcinkaya's user avatar

ayalcinkayaayalcinkaya

3,24328 silver badges25 bronze badges

1

I had the same problem, but I had my activity declared in the Manifest file, with the correct name.

My problem was that I didn’t have to imported a third party libraries in a «libs» folder, and I needed reference them in my proyect (Right-click, properties, Java Build Path, Libraries, Add Jar…).

answered Jun 11, 2013 at 16:49

Maria Mercedes Wyss Alvarez's user avatar

This can happen if your activity class is inside a default package. I fixed it by moving the activity class to a new package. and changing the manifest.xml

before

activity android:name=".MainActivity" 

after

activity android:name="new_package.MainActivity"

Rohit5k2's user avatar

Rohit5k2

17.8k8 gold badges46 silver badges57 bronze badges

answered Jun 7, 2014 at 18:02

Satthy's user avatar

SatthySatthy

1091 gold badge3 silver badges10 bronze badges

1

As suggested by djjeck in comment in this answer I missed to put public modifier for my class.

It should be

public class MyActivity extends AppCompatActivity {

It may help some like me.

answered Nov 13, 2017 at 12:36

Shailendra Madda's user avatar

Shailendra MaddaShailendra Madda

20.1k15 gold badges94 silver badges136 bronze badges

This happens to me fairly frequently when using the NDK. I found that it is necessary for me to do a «Clean» in Eclipse after every time I do a ndk-build. Hope it helps anyone 🙂

answered Jan 23, 2012 at 17:04

kizzx2's user avatar

kizzx2kizzx2

18.6k14 gold badges75 silver badges81 bronze badges

This error also occurs when you use of ActionBarActivity but assigned a non AppCompat style.

To fix this just set your apps style parent to an Theme.AppCompat one like this.:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
</style>

answered Dec 5, 2013 at 9:14

Ostkontentitan's user avatar

OstkontentitanOstkontentitan

6,8605 gold badges52 silver badges71 bronze badges

1

Right click on project > properties > android > and try with different version of the android earlier i was doing with android 4.4 then i changed to android 4.3 and it worked !

answered Mar 9, 2014 at 10:51

nikhilgotan's user avatar

I had the same issue (Unable to instantiate Activity) :

FIRST reason :

I was accessing

Camera mCamera;
Camera.Parameters params = mCamera.getParameters();

before

mCamera = Camera.open();

So right way of doing is, open the camera first and then access parameters.

SECOND reason : Declare your activity in the manifest file

<activity android:name=".activities.MainActivity"/>

THIRD reason :
Declare Camera permission in your manifest file.

<uses-feature android:name="android.hardware.Camera"></uses-feature>
<uses-permission android:name="android.permission.CAMERA" />

Hope this helps

answered May 11, 2016 at 20:17

Sdembla's user avatar

SdemblaSdembla

1,60913 silver badges13 bronze badges

In my case, I was trying to embed the Facebook SDK and I was having the wrong Application ID; thus the error was popping up. In your manifest file, you should have the proper meta data:

<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />

answered Jul 9, 2016 at 14:52

Menelaos Kotsollaris's user avatar

0

If you have Android Studio 2.3.3 and Android Studio 3.0.0 installed, then switching between the two programs for development will cause this error. This is because there exist situations where classes supported in one program is not supported by the other and vice versa. It is important to maintain consistency in which version of Android Studio is being used to develop a project.

answered Oct 7, 2017 at 14:15

hexicle's user avatar

hexiclehexicle

2,0432 gold badges23 silver badges31 bronze badges

I have tried all above solution but nothing work for me. after I have just add extend activity instead of AppCompatActivity and working fine.

used

public class MainActivity extends Activity  

instead of

public class MainActivity extends AppCompatActivity 

i dont know what real issue was that.

answered Feb 15, 2018 at 18:13

Sagar Jethva's user avatar

I was trying to run a sample code
While launching the application in the android 1.5 emulator , I got these errors….
Any one have some hint..?

ERROR from LogCat:

01-13 02:28:08.392: ERROR/AndroidRuntime(2888): FATAL EXCEPTION: main
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.s.android.test/com.s.android.test.MainActivity}: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1544)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Looper.loop(Looper.java:123)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invoke(Method.java:507)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.NativeStart.main(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): Caused by: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1536)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     ... 11 more
01-13 02:28:08.407: WARN/ActivityManager(112):   Force finishing activity com.s.android.test/.MainActivity

Edit
This error happens to most of the beginners, the thing is that you have to add all your activities in the Manifest file.

Braiam's user avatar

asked Jan 14, 2011 at 5:37

rahul's user avatar

4

It is a problem of your Intent.

Please add your Activity in your AndroidManifest.xml.

When you want to make a new activity, you should register it in your AndroidManifest.xml.

Mohsen Kamrani's user avatar

answered Jan 14, 2011 at 6:45

Tanmay Mandal's user avatar

Tanmay MandalTanmay Mandal

39.6k12 gold badges51 silver badges48 bronze badges

5

You may be trying to find the view before onCreate() which is incorrect.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect

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

answered Nov 18, 2013 at 13:50

SMUsamaShah's user avatar

SMUsamaShahSMUsamaShah

7,47722 gold badges88 silver badges129 bronze badges

3

There is another way to get an java.lang.RuntimeException: Unable to instantiate activity ComponentInfo exception and that is the activity that you are trying to start is abstract. I made this stupid mistake once and its very easy to overlook.

answered Dec 6, 2011 at 15:38

Kevin's user avatar

KevinKevin

1,68613 silver badges16 bronze badges

5

In my case I forgot to add the google maps library

<application>
    ....

    <uses-library android:name="com.google.android.maps" />
</application>

Also, check that you’re not missing the preceding dot before the activity path

<activity android:name=".activities.MainActivity"/>

answered Apr 29, 2011 at 10:43

Maragues's user avatar

MaraguesMaragues

37.4k14 gold badges94 silver badges96 bronze badges

1

Image

It also happens because of this issue. I unchecked the jars that needed be exported to the apk and this same thing happened. Please tick the jars that your app Needs to run.

answered Jul 2, 2013 at 11:35

meowmeowbeans's user avatar

1

This might not be relevant to the actual question, but in my instance, I tried to implement Kotlin and left out apply plugin: 'kotlin-android'. The error happened because it could not recognize the MainActivity in as a .kt file.

Hope it helps someone.

answered Dec 13, 2016 at 18:08

Muz's user avatar

MuzMuz

5,7773 gold badges47 silver badges64 bronze badges

2

I encountered this problem too, but in a slightly different way. Here was my scenario:

App detail:

  • Using ActionBarSherlock as a library
  • Using android-support-v4-r7-googlemaps.jar in the ActionBarSherlock library so I could use a «map fragment» in my primary project
  • Added the jar to the build path of my primary project
  • Included the <uses-library android:name="com.google.android.maps" /> in the manifests of both the library project and my primary project (this may not be necessary in the library?)
  • The manifest in the primary project had the proper activity definition and all of the appropriate properties
  • I didn’t have an abstract activity or any of the other gotchas I’ve seen on Stack Overflow pertaining to this problem.

However, I still encountered the error described in the original post and could not get it to go away. The problem though, was slightly different in one regard:

  • It only affected a fresh install of the application to my device. Any time the app installed for the first time, I would get the error preceded by several «warnings» of: Unable to resolve superclass of FragmentActivity
  • Those warnings traced back to the ActionBarSherlock library
  • The app would force close and crash.
  • If I immediately rebuilt and redeployed the app, it worked fine.
  • The only time it crashed was on a totally fresh install. If I uninstalled the app, built and deployed again from Eclipse, it would crash. Build/deploy a second time, it would work fine.

How I fixed it:

  • In the ActionBarSherlock library project, I added the android-support-v4-r7-googlemaps.jar to the build path
  • This step alone did not fix the problem

  • Once the jar was added to the build path, I had change the order on the Java Build Path > Order and Export tab — I set the JAR to the first item in the list (it was the last after the /src and /gen items).

  • I then rebuilt and redeployed the app to my device — it worked as expected on a fresh install. Just to be certain, I uninstalled it again 2-3 times and reinstalled — still worked as expected.

This may be a total rookie mistake, but I spent quite a while digging through posts and my code to figure it out, so hopefully it can be helpful to someone else. May not fix all situations, but in this particular case, that ended up being the solution to my problem.

answered Oct 12, 2012 at 12:29

Kyle's user avatar

KyleKyle

6065 silver badges16 bronze badges

1

This error can also be the ultimate sign of a dumb mistake (like when I — I mean, cough, like when a friend of mine who showed me their code once) where they try to execute code outside of a method like trying to do this:

SQLiteDatabase db = openOrCreateDatabase("DB", MODE_PRIVATE, null); //trying to perform function where you can only set up objects, primitives, etc

@Override
public void onCreate(Bundle savedInstanceState) {
....
}

rather than this:

SQLiteDatabase db;

@Override
public void onCreate(Bundle savedInstanceState) {
db = openOrCreateDatabase("DB", MODE_PRIVATE, null);
....
}

answered Oct 29, 2013 at 20:15

Chris Klingler's user avatar

Chris KlinglerChris Klingler

5,2282 gold badges37 silver badges43 bronze badges

1

For me, my package string in AndroidManifest.xml was incorrect (copied from a tutorial).
Make sure the package string in this file is the same as where your main activity is, e.g.

 package="com.example.app"

An easy way to do this is to open the AndroidManifest.xml file in the «Manifest» tab, and type it in the text box next to Package, or use the Browse button.

Also, the package string for my activity was wrong, e.g.

<activity android:name="com.example.app.MainActivity" android:label="@string/app_name">

I (stupidly) got the same error weeks later when I renamed my package name. If you do this, make sure you update the AndroidManifest.xml file too.

Jared Burrows's user avatar

Jared Burrows

53.8k23 gold badges151 silver badges185 bronze badges

answered Aug 27, 2012 at 8:36

satyrFrost's user avatar

satyrFrostsatyrFrost

3938 silver badges17 bronze badges

1

I got rid of this problem by deleting the Bin and Gen folder from project(which automatically come back when the project will build) and then cleaning the project from ->Menu -> Project -> clean.

Thanks.

answered Apr 6, 2013 at 10:07

Jagdeep Singh's user avatar

Jagdeep SinghJagdeep Singh

1,1901 gold badge16 silver badges34 bronze badges

Simply Clean your working project or restart eclipse. Then run your project. it will work.

answered Jul 16, 2014 at 6:01

Emran Hamza's user avatar

Emran HamzaEmran Hamza

3,8091 gold badge24 silver badges20 bronze badges

1

In my case I haven’t set the setContentView(R.layout.main);

If you create a new class do not foget to set this in on onCreate(Bundle savedInstanceState) method.

I have done this stupid mistake several times.

answered Jan 25, 2012 at 6:59

saji159's user avatar

saji159saji159

3287 silver badges14 bronze badges

For me it was different from any of the above,

The activity was declared as abstract, That is why giving the error.
Once it removed it worked.

Earlier

     public abstract class SampleActivity extends AppcompatActivity{
     }

After removal

     public class SampleActivity extends AppcompatActivity{
     }

answered Jan 9, 2020 at 12:30

Thriveni's user avatar

ThriveniThriveni

7328 silver badges11 bronze badges

0

Ok, I am fairly experienced on the iPhone but new to android. I got this issue when I had:

Button infoButton = (Button)findViewById(R.id.InfoButton);

this line of code above:

@Override
public void onCreate (Bundle savedInstanceState) {
}

May be I am sleep deprived 😛

answered Jun 19, 2012 at 15:09

iSee's user avatar

iSeeiSee

6041 gold badge14 silver badges31 bronze badges

1

In my case, I was trying to initialize the components(UI) even before the onCreate is called for the Activity.

Make sure your UI components are initialized/linked in the onCreate method after setContentView

NB: This is my first mistake while learning Android programming.

answered Apr 12, 2019 at 16:20

Anup H's user avatar

Anup HAnup H

5096 silver badges10 bronze badges

1

I recently encountered this with fresh re-install of Eclipse. Turns out my Compiler compliance level was set to Java 1.7 and project required 1.6.

In Eclipse:
Project -> Properties -> Java Compiler -> JDK Compliance

answered Oct 24, 2012 at 7:24

J.G.Sebring's user avatar

J.G.SebringJ.G.Sebring

5,8841 gold badge30 silver badges42 bronze badges

Whow are there lots of ways to get this error!.

I will add another given none of the others either applied or were the cause.

I forgot the ‘public‘ in the declaration of my activity class! It was package private.

I had been writing so much Bluetooth code that habit caused me to create an activity class that was package private.

Says something about the obscurity of this error message.

answered Jul 25, 2020 at 0:40

Brian Reinhold's user avatar

Brian ReinholdBrian Reinhold

2,3113 gold badges25 silver badges44 bronze badges

Make sure MainActivity is not «abstract».

abstract class MainActivity : AppCompatActivity()

just remove the abstract

class MainActivity : AppCompatActivity() {

answered Sep 29, 2021 at 11:54

Amit Singh's user avatar

Amit SinghAmit Singh

5094 silver badges6 bronze badges

Got this problem, and fixed it by setting the «launch mode» property of the activity.

answered Apr 6, 2012 at 13:28

Zorglube's user avatar

Another reason of this problem may be a missing library.

Go to Properties -> Android and check that you add the libraries correctly

answered Mar 7, 2013 at 10:39

ayalcinkaya's user avatar

ayalcinkayaayalcinkaya

3,24328 silver badges25 bronze badges

1

I had the same problem, but I had my activity declared in the Manifest file, with the correct name.

My problem was that I didn’t have to imported a third party libraries in a «libs» folder, and I needed reference them in my proyect (Right-click, properties, Java Build Path, Libraries, Add Jar…).

answered Jun 11, 2013 at 16:49

Maria Mercedes Wyss Alvarez's user avatar

This can happen if your activity class is inside a default package. I fixed it by moving the activity class to a new package. and changing the manifest.xml

before

activity android:name=".MainActivity" 

after

activity android:name="new_package.MainActivity"

Rohit5k2's user avatar

Rohit5k2

17.8k8 gold badges46 silver badges57 bronze badges

answered Jun 7, 2014 at 18:02

Satthy's user avatar

SatthySatthy

1091 gold badge3 silver badges10 bronze badges

1

As suggested by djjeck in comment in this answer I missed to put public modifier for my class.

It should be

public class MyActivity extends AppCompatActivity {

It may help some like me.

answered Nov 13, 2017 at 12:36

Shailendra Madda's user avatar

Shailendra MaddaShailendra Madda

20.1k15 gold badges94 silver badges136 bronze badges

This happens to me fairly frequently when using the NDK. I found that it is necessary for me to do a «Clean» in Eclipse after every time I do a ndk-build. Hope it helps anyone 🙂

answered Jan 23, 2012 at 17:04

kizzx2's user avatar

kizzx2kizzx2

18.6k14 gold badges75 silver badges81 bronze badges

This error also occurs when you use of ActionBarActivity but assigned a non AppCompat style.

To fix this just set your apps style parent to an Theme.AppCompat one like this.:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
</style>

answered Dec 5, 2013 at 9:14

Ostkontentitan's user avatar

OstkontentitanOstkontentitan

6,8605 gold badges52 silver badges71 bronze badges

1

Right click on project > properties > android > and try with different version of the android earlier i was doing with android 4.4 then i changed to android 4.3 and it worked !

answered Mar 9, 2014 at 10:51

nikhilgotan's user avatar

I had the same issue (Unable to instantiate Activity) :

FIRST reason :

I was accessing

Camera mCamera;
Camera.Parameters params = mCamera.getParameters();

before

mCamera = Camera.open();

So right way of doing is, open the camera first and then access parameters.

SECOND reason : Declare your activity in the manifest file

<activity android:name=".activities.MainActivity"/>

THIRD reason :
Declare Camera permission in your manifest file.

<uses-feature android:name="android.hardware.Camera"></uses-feature>
<uses-permission android:name="android.permission.CAMERA" />

Hope this helps

answered May 11, 2016 at 20:17

Sdembla's user avatar

SdemblaSdembla

1,60913 silver badges13 bronze badges

In my case, I was trying to embed the Facebook SDK and I was having the wrong Application ID; thus the error was popping up. In your manifest file, you should have the proper meta data:

<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />

answered Jul 9, 2016 at 14:52

Menelaos Kotsollaris's user avatar

0

If you have Android Studio 2.3.3 and Android Studio 3.0.0 installed, then switching between the two programs for development will cause this error. This is because there exist situations where classes supported in one program is not supported by the other and vice versa. It is important to maintain consistency in which version of Android Studio is being used to develop a project.

answered Oct 7, 2017 at 14:15

hexicle's user avatar

hexiclehexicle

2,0432 gold badges23 silver badges31 bronze badges

I have tried all above solution but nothing work for me. after I have just add extend activity instead of AppCompatActivity and working fine.

used

public class MainActivity extends Activity  

instead of

public class MainActivity extends AppCompatActivity 

i dont know what real issue was that.

answered Feb 15, 2018 at 18:13

Sagar Jethva's user avatar

I was trying to run a sample code
While launching the application in the android 1.5 emulator , I got these errors….
Any one have some hint..?

ERROR from LogCat:

01-13 02:28:08.392: ERROR/AndroidRuntime(2888): FATAL EXCEPTION: main
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.s.android.test/com.s.android.test.MainActivity}: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1544)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Looper.loop(Looper.java:123)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invoke(Method.java:507)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.NativeStart.main(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): Caused by: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1536)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     ... 11 more
01-13 02:28:08.407: WARN/ActivityManager(112):   Force finishing activity com.s.android.test/.MainActivity

Edit
This error happens to most of the beginners, the thing is that you have to add all your activities in the Manifest file.

Braiam's user avatar

asked Jan 14, 2011 at 5:37

rahul's user avatar

4

It is a problem of your Intent.

Please add your Activity in your AndroidManifest.xml.

When you want to make a new activity, you should register it in your AndroidManifest.xml.

Mohsen Kamrani's user avatar

answered Jan 14, 2011 at 6:45

Tanmay Mandal's user avatar

Tanmay MandalTanmay Mandal

39.6k12 gold badges51 silver badges48 bronze badges

5

You may be trying to find the view before onCreate() which is incorrect.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect

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

answered Nov 18, 2013 at 13:50

SMUsamaShah's user avatar

SMUsamaShahSMUsamaShah

7,47722 gold badges88 silver badges129 bronze badges

3

There is another way to get an java.lang.RuntimeException: Unable to instantiate activity ComponentInfo exception and that is the activity that you are trying to start is abstract. I made this stupid mistake once and its very easy to overlook.

answered Dec 6, 2011 at 15:38

Kevin's user avatar

KevinKevin

1,68613 silver badges16 bronze badges

5

In my case I forgot to add the google maps library

<application>
    ....

    <uses-library android:name="com.google.android.maps" />
</application>

Also, check that you’re not missing the preceding dot before the activity path

<activity android:name=".activities.MainActivity"/>

answered Apr 29, 2011 at 10:43

Maragues's user avatar

MaraguesMaragues

37.4k14 gold badges94 silver badges96 bronze badges

1

Image

It also happens because of this issue. I unchecked the jars that needed be exported to the apk and this same thing happened. Please tick the jars that your app Needs to run.

answered Jul 2, 2013 at 11:35

meowmeowbeans's user avatar

1

This might not be relevant to the actual question, but in my instance, I tried to implement Kotlin and left out apply plugin: 'kotlin-android'. The error happened because it could not recognize the MainActivity in as a .kt file.

Hope it helps someone.

answered Dec 13, 2016 at 18:08

Muz's user avatar

MuzMuz

5,7773 gold badges47 silver badges64 bronze badges

2

I encountered this problem too, but in a slightly different way. Here was my scenario:

App detail:

  • Using ActionBarSherlock as a library
  • Using android-support-v4-r7-googlemaps.jar in the ActionBarSherlock library so I could use a «map fragment» in my primary project
  • Added the jar to the build path of my primary project
  • Included the <uses-library android:name="com.google.android.maps" /> in the manifests of both the library project and my primary project (this may not be necessary in the library?)
  • The manifest in the primary project had the proper activity definition and all of the appropriate properties
  • I didn’t have an abstract activity or any of the other gotchas I’ve seen on Stack Overflow pertaining to this problem.

However, I still encountered the error described in the original post and could not get it to go away. The problem though, was slightly different in one regard:

  • It only affected a fresh install of the application to my device. Any time the app installed for the first time, I would get the error preceded by several «warnings» of: Unable to resolve superclass of FragmentActivity
  • Those warnings traced back to the ActionBarSherlock library
  • The app would force close and crash.
  • If I immediately rebuilt and redeployed the app, it worked fine.
  • The only time it crashed was on a totally fresh install. If I uninstalled the app, built and deployed again from Eclipse, it would crash. Build/deploy a second time, it would work fine.

How I fixed it:

  • In the ActionBarSherlock library project, I added the android-support-v4-r7-googlemaps.jar to the build path
  • This step alone did not fix the problem

  • Once the jar was added to the build path, I had change the order on the Java Build Path > Order and Export tab — I set the JAR to the first item in the list (it was the last after the /src and /gen items).

  • I then rebuilt and redeployed the app to my device — it worked as expected on a fresh install. Just to be certain, I uninstalled it again 2-3 times and reinstalled — still worked as expected.

This may be a total rookie mistake, but I spent quite a while digging through posts and my code to figure it out, so hopefully it can be helpful to someone else. May not fix all situations, but in this particular case, that ended up being the solution to my problem.

answered Oct 12, 2012 at 12:29

Kyle's user avatar

KyleKyle

6065 silver badges16 bronze badges

1

This error can also be the ultimate sign of a dumb mistake (like when I — I mean, cough, like when a friend of mine who showed me their code once) where they try to execute code outside of a method like trying to do this:

SQLiteDatabase db = openOrCreateDatabase("DB", MODE_PRIVATE, null); //trying to perform function where you can only set up objects, primitives, etc

@Override
public void onCreate(Bundle savedInstanceState) {
....
}

rather than this:

SQLiteDatabase db;

@Override
public void onCreate(Bundle savedInstanceState) {
db = openOrCreateDatabase("DB", MODE_PRIVATE, null);
....
}

answered Oct 29, 2013 at 20:15

Chris Klingler's user avatar

Chris KlinglerChris Klingler

5,2282 gold badges37 silver badges43 bronze badges

1

For me, my package string in AndroidManifest.xml was incorrect (copied from a tutorial).
Make sure the package string in this file is the same as where your main activity is, e.g.

 package="com.example.app"

An easy way to do this is to open the AndroidManifest.xml file in the «Manifest» tab, and type it in the text box next to Package, or use the Browse button.

Also, the package string for my activity was wrong, e.g.

<activity android:name="com.example.app.MainActivity" android:label="@string/app_name">

I (stupidly) got the same error weeks later when I renamed my package name. If you do this, make sure you update the AndroidManifest.xml file too.

Jared Burrows's user avatar

Jared Burrows

53.8k23 gold badges151 silver badges185 bronze badges

answered Aug 27, 2012 at 8:36

satyrFrost's user avatar

satyrFrostsatyrFrost

3938 silver badges17 bronze badges

1

I got rid of this problem by deleting the Bin and Gen folder from project(which automatically come back when the project will build) and then cleaning the project from ->Menu -> Project -> clean.

Thanks.

answered Apr 6, 2013 at 10:07

Jagdeep Singh's user avatar

Jagdeep SinghJagdeep Singh

1,1901 gold badge16 silver badges34 bronze badges

Simply Clean your working project or restart eclipse. Then run your project. it will work.

answered Jul 16, 2014 at 6:01

Emran Hamza's user avatar

Emran HamzaEmran Hamza

3,8091 gold badge24 silver badges20 bronze badges

1

In my case I haven’t set the setContentView(R.layout.main);

If you create a new class do not foget to set this in on onCreate(Bundle savedInstanceState) method.

I have done this stupid mistake several times.

answered Jan 25, 2012 at 6:59

saji159's user avatar

saji159saji159

3287 silver badges14 bronze badges

For me it was different from any of the above,

The activity was declared as abstract, That is why giving the error.
Once it removed it worked.

Earlier

     public abstract class SampleActivity extends AppcompatActivity{
     }

After removal

     public class SampleActivity extends AppcompatActivity{
     }

answered Jan 9, 2020 at 12:30

Thriveni's user avatar

ThriveniThriveni

7328 silver badges11 bronze badges

0

Ok, I am fairly experienced on the iPhone but new to android. I got this issue when I had:

Button infoButton = (Button)findViewById(R.id.InfoButton);

this line of code above:

@Override
public void onCreate (Bundle savedInstanceState) {
}

May be I am sleep deprived 😛

answered Jun 19, 2012 at 15:09

iSee's user avatar

iSeeiSee

6041 gold badge14 silver badges31 bronze badges

1

In my case, I was trying to initialize the components(UI) even before the onCreate is called for the Activity.

Make sure your UI components are initialized/linked in the onCreate method after setContentView

NB: This is my first mistake while learning Android programming.

answered Apr 12, 2019 at 16:20

Anup H's user avatar

Anup HAnup H

5096 silver badges10 bronze badges

1

I recently encountered this with fresh re-install of Eclipse. Turns out my Compiler compliance level was set to Java 1.7 and project required 1.6.

In Eclipse:
Project -> Properties -> Java Compiler -> JDK Compliance

answered Oct 24, 2012 at 7:24

J.G.Sebring's user avatar

J.G.SebringJ.G.Sebring

5,8841 gold badge30 silver badges42 bronze badges

Whow are there lots of ways to get this error!.

I will add another given none of the others either applied or were the cause.

I forgot the ‘public‘ in the declaration of my activity class! It was package private.

I had been writing so much Bluetooth code that habit caused me to create an activity class that was package private.

Says something about the obscurity of this error message.

answered Jul 25, 2020 at 0:40

Brian Reinhold's user avatar

Brian ReinholdBrian Reinhold

2,3113 gold badges25 silver badges44 bronze badges

Make sure MainActivity is not «abstract».

abstract class MainActivity : AppCompatActivity()

just remove the abstract

class MainActivity : AppCompatActivity() {

answered Sep 29, 2021 at 11:54

Amit Singh's user avatar

Amit SinghAmit Singh

5094 silver badges6 bronze badges

Got this problem, and fixed it by setting the «launch mode» property of the activity.

answered Apr 6, 2012 at 13:28

Zorglube's user avatar

Another reason of this problem may be a missing library.

Go to Properties -> Android and check that you add the libraries correctly

answered Mar 7, 2013 at 10:39

ayalcinkaya's user avatar

ayalcinkayaayalcinkaya

3,24328 silver badges25 bronze badges

1

I had the same problem, but I had my activity declared in the Manifest file, with the correct name.

My problem was that I didn’t have to imported a third party libraries in a «libs» folder, and I needed reference them in my proyect (Right-click, properties, Java Build Path, Libraries, Add Jar…).

answered Jun 11, 2013 at 16:49

Maria Mercedes Wyss Alvarez's user avatar

This can happen if your activity class is inside a default package. I fixed it by moving the activity class to a new package. and changing the manifest.xml

before

activity android:name=".MainActivity" 

after

activity android:name="new_package.MainActivity"

Rohit5k2's user avatar

Rohit5k2

17.8k8 gold badges46 silver badges57 bronze badges

answered Jun 7, 2014 at 18:02

Satthy's user avatar

SatthySatthy

1091 gold badge3 silver badges10 bronze badges

1

As suggested by djjeck in comment in this answer I missed to put public modifier for my class.

It should be

public class MyActivity extends AppCompatActivity {

It may help some like me.

answered Nov 13, 2017 at 12:36

Shailendra Madda's user avatar

Shailendra MaddaShailendra Madda

20.1k15 gold badges94 silver badges136 bronze badges

This happens to me fairly frequently when using the NDK. I found that it is necessary for me to do a «Clean» in Eclipse after every time I do a ndk-build. Hope it helps anyone 🙂

answered Jan 23, 2012 at 17:04

kizzx2's user avatar

kizzx2kizzx2

18.6k14 gold badges75 silver badges81 bronze badges

This error also occurs when you use of ActionBarActivity but assigned a non AppCompat style.

To fix this just set your apps style parent to an Theme.AppCompat one like this.:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
</style>

answered Dec 5, 2013 at 9:14

Ostkontentitan's user avatar

OstkontentitanOstkontentitan

6,8605 gold badges52 silver badges71 bronze badges

1

Right click on project > properties > android > and try with different version of the android earlier i was doing with android 4.4 then i changed to android 4.3 and it worked !

answered Mar 9, 2014 at 10:51

nikhilgotan's user avatar

I had the same issue (Unable to instantiate Activity) :

FIRST reason :

I was accessing

Camera mCamera;
Camera.Parameters params = mCamera.getParameters();

before

mCamera = Camera.open();

So right way of doing is, open the camera first and then access parameters.

SECOND reason : Declare your activity in the manifest file

<activity android:name=".activities.MainActivity"/>

THIRD reason :
Declare Camera permission in your manifest file.

<uses-feature android:name="android.hardware.Camera"></uses-feature>
<uses-permission android:name="android.permission.CAMERA" />

Hope this helps

answered May 11, 2016 at 20:17

Sdembla's user avatar

SdemblaSdembla

1,60913 silver badges13 bronze badges

In my case, I was trying to embed the Facebook SDK and I was having the wrong Application ID; thus the error was popping up. In your manifest file, you should have the proper meta data:

<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />

answered Jul 9, 2016 at 14:52

Menelaos Kotsollaris's user avatar

0

If you have Android Studio 2.3.3 and Android Studio 3.0.0 installed, then switching between the two programs for development will cause this error. This is because there exist situations where classes supported in one program is not supported by the other and vice versa. It is important to maintain consistency in which version of Android Studio is being used to develop a project.

answered Oct 7, 2017 at 14:15

hexicle's user avatar

hexiclehexicle

2,0432 gold badges23 silver badges31 bronze badges

I have tried all above solution but nothing work for me. after I have just add extend activity instead of AppCompatActivity and working fine.

used

public class MainActivity extends Activity  

instead of

public class MainActivity extends AppCompatActivity 

i dont know what real issue was that.

answered Feb 15, 2018 at 18:13

Sagar Jethva's user avatar

Resolve Java.Lang.RuntimeException: Unable to Instantiate Activity ComponentInfo

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 the AndroidManifest.xml file. Why is it necessary?

    It is because whenever we want to make a new Activity, we must register in our AndroidManifest.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 our Activity in AndroidManifest.xml, which is declared as abstract. In other words, we can say that the Activity we are trying to access is declared abstract.

  • 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 as public. 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.

В чём ошибка не понимаю?

Ошибка скажите что она имеет ввиду
java.lang.RuntimeException: Unable to resume activity {com.example.location/com.example.location.MainActivity}: java.lang.SecurityException: «gps» location provider requires ACCESS_FINE_LOCATION permission.
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3824)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3856)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6826)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.SecurityException: «gps» location provider requires ACCESS_FINE_LOCATION permission.
at android.os.Parcel.createException(Parcel.java:1953)
at android.os.Parcel.readException(Parcel.java:1921)
at android.os.Parcel.readException(Parcel.java:1871)
at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:755)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:1019)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:562)
at com.example.location.MainActivity.onResume(MainActivity.java:46)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1413)
at android.app.Activity.performResume(Activity.java:7400)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3816)
… 11 more
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.LocationManagerService.checkResolutionLevelIsSufficientForProviderUse(LocationManagerService.java:1568)
at com.android.server.LocationManagerService.requestLocationUpdates(LocationManagerService.java:2156)
at android.location.ILocationManager$Stub.onTransact(ILocationManager.java:72)
at android.os.Binder.execTransact(Binder.java:731)


  • Вопрос задан

    более двух лет назад

  • 728 просмотров

Пригласить эксперта

Все написано. Не выдано разрешение на доступ к местоположению (выдаётся пользователем по запросу или в настройках).


  • Показать ещё
    Загружается…

28 янв. 2023, в 22:48

500 руб./за проект

28 янв. 2023, в 20:58

30000 руб./за проект

28 янв. 2023, в 20:46

50000 руб./за проект

Минуточку внимания

Ежикмой

0 / 0 / 0

Регистрация: 18.09.2016

Сообщений: 7

1

23.08.2018, 14:26. Показов 2716. Ответов 2

Метки android, camera (Все метки)


Подскажите почему у меня возникает ошибка на некоторых устройствах java.lang.RuntimeException: getParameters failed (empty parameters)?

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Toast;
 
import java.io.IOException;
 
public class CameraPreview extends SurfaceView implements
        Callback {
 
    private static final String TAG = "CameraPreview";
    SurfaceHolder mHolder;
    Camera mCamera;
    Context mContext;
 
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);
        mContext = context;
        mCamera = camera;
        mHolder = getHolder();
        mHolder.addCallback(this);
 
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
 
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
 
        if (mHolder.getSurface() == null)
            return;
 
        mCamera.stopPreview();
 
        setCameraDisplayOrientation();
 
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();
        } catch (IOException e) {
            Toast.makeText(mContext, "Camera preview2 failed", Toast.LENGTH_LONG).show();
        }
    }
 
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Toast.makeText(mContext, "Camera preview3 failed", Toast.LENGTH_LONG).show();
        }
    }
 
    public void setCameraDisplayOrientation()
    {
        if (mCamera == null)
            return;
 
 
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(0, info);
        Camera.Parameters parameters = mCamera.getParameters();
 
        WindowManager winManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        int rotation = winManager.getDefaultDisplay().getRotation();
 
        int degrees = 0;
 
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }
 
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
        {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // + зеркало
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }
 
        mCamera.setDisplayOrientation(result);
 
        int rotate = (degrees + 270) % 360;
        parameters.setRotation(rotate);
        mCamera.setParameters(parameters);
    }
 
 
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        //this.getHolder().removeCallback(this);
//        mCamera.stopPreview();
 
 
        // Surface will be destroyed when we return, so stop the preview.
        if (mCamera != null) {
            // Call stopPreview() to stop updating the preview surface.
            mCamera.stopPreview();
        }
 
    }
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



1559 / 1160 / 423

Регистрация: 08.05.2012

Сообщений: 5,203

23.08.2018, 16:44

2

Лучший ответ Сообщение было отмечено Ежикмой как решение

Решение

Потому, что камера недоступна или занята другим приложением.



0



Ежикмой

0 / 0 / 0

Регистрация: 18.09.2016

Сообщений: 7

23.08.2018, 17:11

 [ТС]

3

Полный текст ошибки

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
08-23 14:30:01.792 3716-3844/? E/CameraService: setCompanionDisableSysFs : cc.disable property set to 0
08-23 14:30:01.795 3716-3844/? E/SecCameraCoreManager: initialize1
08-23 14:30:01.795 3716-3844/? E/ExynosCamera: Build Date is (__DATE__) (__TIME__)
08-23 14:30:01.803 3716-3844/? E/SecCameraCoreManager: initialize2
08-23 14:30:01.878 3716-3716/? E/SecCameraCoreManager: checkTemperature (0)
08-23 14:30:01.888 3716-4891/? E/ExynosCameraBufferManager: [CAM_ID(0)][SCP_BUF]-ERR(m_alloc[1945]):m_reqBufCount(12)
08-23 14:30:02.259 3716-5047/? E/ExynosCameraNode: [CAM_ID(0)][3AA_OUTPUT]-ERR(m_dqBuf):exynos_v4l2_dqbuf(fd:72) fail (-1)
08-23 14:30:02.259 3716-5047/? E/ExynosCameraMCPipe: [CAM_ID(0)][PIPE_3AA]-ERR(m_getBuffer[1942]):node(3AA_OUTPUT)->getBuffer() fail, index(-2), frameCount(0), ret(-1)
08-23 14:30:02.259 3716-5047/? E/ExynosCameraNode: [CAM_ID(0)][SCP_PREVIEW]-ERR(m_polling):poll[74], pollRet(1) event(0x8), cnt(-1)
    [CAM_ID(0)][SCP_PREVIEW]-ERR(polling):m_polling fail
08-23 14:30:02.259 3716-5047/? E/ExynosCameraMCPipe: [CAM_ID(0)][PIPE_3AA]-ERR(m_checkPolling[3653]):polling fail, ret(-38)
    [CAM_ID(0)][PIPE_3AA]-ERR(m_getBuffer[2062]):m_checkPolling fail, frameCount(0), ret(-1001)
08-23 14:30:02.259 3716-5047/? E/ExynosCameraNode: [CAM_ID(0)][SCP_PREVIEW]-ERR(getBuffer[1004]):m_nodeState = [4] is not valid
08-23 14:30:02.259 3716-5047/? E/ExynosCameraMCPipe: [CAM_ID(0)][PIPE_3AA]-ERR(m_getBuffer[2074]):node(SCP_PREVIEW)->getBuffer() fail, index(-2), frameCount(0), ret(-38)
08-23 14:30:02.260 3716-5047/? E/ExynosCameraNode: [CAM_ID(0)][3AA_CAPTURE]-ERR(getBuffer[1004]):m_nodeState = [4] is not valid
08-23 14:30:02.260 3716-5047/? E/ExynosCameraMCPipe: [CAM_ID(0)][PIPE_3AA]-ERR(m_getBuffer[2074]):node(3AA_CAPTURE)->getBuffer() fail, index(-2), frameCount(0), ret(-38)
    [CAM_ID(0)][PIPE_3AA]-ERR(m_getBuffer[2196]):frameCount(0)                    : captureNodeCount == 0 || checkRet(-1) != NO_ERROR.                    so, setFrameState(FRAME_STATE_SKIPPED)
08-23 14:30:02.303 3716-3844/? E/SecCameraCoreManager: checkTemperature (0)
08-23 14:30:02.308 3716-5064/? E/ExynosCameraBufferManager: [CAM_ID(0)][SCP_BUF]-ERR(m_alloc[1945]):m_reqBufCount(12)
08-23 14:30:02.375 3716-3716/? E/CameraClient: attempt to use a camera after disconnect() (pid 4549)
08-23 14:30:02.385 3716-4557/? E/CameraClient: attempt to use a camera after disconnect() (pid 4549)
08-23 14:30:02.386 3716-3716/? E/CameraClient: attempt to use a camera after disconnect() (pid 4549)
08-23 14:30:02.512 3716-5134/? E/ExynosCamera: [CAM_ID(0)][]-ERR(m_frameFactoryInitThreadFunc[2624]):wait and pop fail, ret(-110)
08-23 14:30:02.560 4549-4549/com.yauheni.kebab E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.yauheni.kebab, PID: 4549
    java.lang.RuntimeException: getParameters failed (empty parameters)
        at android.hardware.Camera.native_getParameters(Native Method)
        at android.hardware.Camera.getParameters(Camera.java:1952)
        at com.yauheni.kebab.camera.CameraPreview.setCameraDisplayOrientation(CameraPreview.java:71)
        at com.yauheni.kebab.camera.CameraPreview.surfaceChanged(CameraPreview.java:43)
        at android.view.SurfaceView.updateWindow(SurfaceView.java:668)
        at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:172)
        at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:1013)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2542)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1537)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:959)
        at android.view.Choreographer.doCallbacks(Choreographer.java:734)
        at android.view.Choreographer.doFrame(Choreographer.java:670)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:945)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)



0



0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Java lang reflect invocationtargetexception ошибка причина
  • Iw4sp exe ошибка приложения 0xc0000142