Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.90/40: Рейтинг темы: голосов - 40, средняя оценка - 4.90
0 / 0 / 0
Регистрация: 28.01.2016
Сообщений: 18
1

Unable to instantiate activity ComponentInfo

08.02.2016, 10:47. Показов 7238. Ответов 9

Author24 — интернет-сервис помощи студентам
Добрый день!
Уже все перепробовал, серверы гугла скоро в ребут уйдут...

Компилит без ошибок, но в эмуле при переходе на этот активити - выкидывает приложение.
"Unable to instantiate activity ComponentInfo Caused by: java.lang.NullPointerException at android.app.Activity.findViewById" - из лога.
Лог ошибки:
Кликните здесь для просмотра всего текста

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
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cheshire161gmail.guessthefilm/com.cheshire161gmail.guessthefilm.Main2Activity}: java.lang.NullPointerException
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                                                                                     at android.app.ActivityThread.access$600(ActivityThread.java:130)
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                     at android.os.Looper.loop(Looper.java:137)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                                                     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:786)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                                                     at dalvik.system.NativeStart.main(Native Method)
                                                                                  Caused by: java.lang.NullPointerException
                                                                                     at android.app.Activity.findViewById(Activity.java:1825)
                                                                                     at com.cheshire161gmail.guessthefilm.Main2Activity.<init>(Main2Activity.java:18)
                                                                                     at java.lang.Class.newInstanceImpl(Native Method)
                                                                                     at java.lang.Class.newInstance(Class.java:1319)
                                                                                     at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)*
                                                                                     at android.app.ActivityThread.access$600(ActivityThread.java:130)*
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)*
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:99)*
                                                                                     at android.os.Looper.loop(Looper.java:137)*
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)*
                                                                                     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:786)*
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)*
                                                                                     at dalvik.system.NativeStart.main(Native Method)*

Вот код Main2Activity :
Кликните здесь для просмотра всего текста

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
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
 
 
 
 
public class Main2Activity extends AppCompatActivity {
 
    private Toolbar toolbar;
    String strName = "q";
    int i = 1;
    TextView textQuest = (TextView) findViewById(R.id.textView2);
    public int result = 0;
    Intent intent2 = new Intent(this, Main22Activity.class);
    Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
    Intent intent3 = new Intent(Main2Activity.this, Main3Activity.class);
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        textQuest.setText(R.string.q1);
 
    }
 
    public void onY(View view) {
        if (i<40) {
            i++;
            result++;
            textQuest.setText(strName + i);
            intent2.putExtra("name", result);
            }
        else{
            intent2.putExtra("name",result);
            startActivity(intent);}
        }
 
    public void onN(View view) {
        if (i<40){
            i++;
            TextView textQuest = (TextView) findViewById(R.id.textView2);
        textQuest.setText(strName + i);
            intent2.putExtra("name", result);}
        else {
            intent2.putExtra("name",result);
            startActivity(intent);}
    }
 
    public void onBack(View view) {
        startActivity(intent3);
    }
}


Вот код Main22Activity (если нужен):
Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
 
public class Main22Activity extends AppCompatActivity {
    TextView textRes = (TextView) findViewById(R.id.textView3);
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main22);
        Intent intent2 = getIntent();
        String name = intent2.getStringExtra("name");
        textRes.setText(name);
    }
}


Вот манифест:
Кликните здесь для просмотра всего текста

XML
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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cheshire161gmail.guessthefilm">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:windowNoTitle="true">
 
        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme.Launcher">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main2Activity" />
        <activity android:name=".Main3Activity" />
        <activity android:name=".Main22Activity"/>
    </application>
 
</manifest>
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
08.02.2016, 10:47
Ответы с готовыми решениями:

Unable to instantiate activity ComponentInfo
Взял старый проект в интернете,решил переделать его под новые версии android. Чуть чуть я его...

Unable to Start Activity ComponentInfo
Добрый день! Недавно начал изучать программирование под Андроид и столкнулся с такой проблемой. В...

Unable to Start Activity ComponentInfo
Добрый день! Есть 2 активити, между ними переход слайдом.. на эмуляторе запускаю - все путем, на...

Java.lang.RuntimeException: Unable to start activity
java.lang.RuntimeException: Unable to start activity...

9
396 / 340 / 84
Регистрация: 17.10.2014
Сообщений: 1,009
08.02.2016, 10:55 2
Лог по всей видимости не соответствует коду, так как жалуется на 18 строку, и findViewById
Цитата Сообщение от Cheshire_161 Посмотреть сообщение
Caused by: java.lang.NullPointerException
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *at android.app.Activity.findViewById(Activity.java:1825)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *at com.cheshire161gmail.guessthefilm.Main2Activity.<init>(Main2Activity.java:18)
но скорее всего в разметке нет TextView c id=textView2.
0
0 / 0 / 0
Регистрация: 28.01.2016
Сообщений: 18
08.02.2016, 11:11  [ТС] 3
androbro, Есть такой TextView:
XML
1
2
3
4
5
6
7
<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:id="@+id/textView2"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
По поводу 18 строки, может я не последний свой вариант скопировал, я там менял местами строчку эту, во всяком случае суть от этого не меняется, ошибка всегда та же, лог точно отсюда
0
396 / 340 / 84
Регистрация: 17.10.2014
Сообщений: 1,009
08.02.2016, 11:17 4
Цитата Сообщение от Cheshire_161 Посмотреть сообщение
может я не последний свой вариант скопировал,
ну так приведите актуальный код, который соответствует логу.

Добавлено через 3 минуты
Cheshire_161, ааа, постойте ка, Вы строчку то эту в onCreate() перенесите:
Java
1
   TextView textQuest = (TextView) findViewById(R.id.textView2);
нельзя искать элемент вьюшку до того как будет основной лейаут привязан
0
0 / 0 / 0
Регистрация: 28.01.2016
Сообщений: 18
08.02.2016, 11:25  [ТС] 5
androbro,

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
package com.cheshire161gmail.guessthefilm;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
 
 
 
 
public class Main2Activity extends AppCompatActivity {
 
    private Toolbar toolbar;
    String strName = "q";
    int i = 1;
    TextView textQuest = (TextView) findViewById(R.id.textView2);
    public int result = 0;
    Intent intent2 = new Intent(this, Main22Activity.class);
    Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
    Intent intent3 = new Intent(Main2Activity.this, Main3Activity.class);
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        textQuest.setText(R.string.q1);
 
    }
 
    public void onY(View view) {
        if (i<40) {
            i++;
            result++;
            textQuest.setText(strName + i);
            intent2.putExtra("name", result);
        }
        else{
            intent2.putExtra("name",result);
            startActivity(intent);}
    }
 
    public void onN(View view) {
        if (i<40){
            i++;
            TextView textQuest = (TextView) findViewById(R.id.textView2);
            textQuest.setText(strName + i);
            intent2.putExtra("name", result);}
        else {
            intent2.putExtra("name",result);
            startActivity(intent);}
    }
 
    public void onBack(View view) {
        startActivity(intent3);
    }
}
Теперь это 18ая строка))

Добавлено через 3 минуты
androbro, так а если я перенесу в onCreate у меня дальше в обработчиках кнопки не будет работать textQuest
0
2884 / 2296 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
08.02.2016, 11:27 6
так же ка и тулбар - объявление в шапке, а инициализация в onCreate()
что тут непонятного?
1
396 / 340 / 84
Регистрация: 17.10.2014
Сообщений: 1,009
08.02.2016, 11:30 7
Лучший ответ Сообщение было отмечено Cheshire_161 как решение

Решение

Цитата Сообщение от Cheshire_161 Посмотреть сообщение
androbro, так а если я перенесу в onCreate у меня дальше в обработчиках кнопки не будет работать textQuest
ну так объявление оставьте там же:
Java
1
TextView textQuest;
а инициализируйте в onCreate():
Java
1
textQuest = (TextView) findViewById(R.id.textView2);
1
0 / 0 / 0
Регистрация: 28.01.2016
Сообщений: 18
08.02.2016, 11:40  [ТС] 8
androbro, теперь жалуется на Intent...

Java
1
2
3
4
5
Caused by: java.lang.NullPointerException
                                                                                     at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
                                                                                     at android.content.ComponentName.<init>(ComponentName.java:75)
                                                                                     at android.content.Intent.<init>(Intent.java:3301)
                                                                                     at com.cheshire161gmail.guessthefilm.Main2Activity.<init>(Main2Activity.java:20)
0
396 / 340 / 84
Регистрация: 17.10.2014
Сообщений: 1,009
08.02.2016, 11:43 9
Цитата Сообщение от Cheshire_161 Посмотреть сообщение
теперь жалуется на Intent...
ну так если жалуется, поступаем и с интентом аналогичным образом.
0
0 / 0 / 0
Регистрация: 28.01.2016
Сообщений: 18
08.02.2016, 11:49  [ТС] 10
androbro, Паблито, такая ошибка глупая оказывается))) Спасибо, помогло!
0
08.02.2016, 11:49
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
08.02.2016, 11:49
Помогаю со студенческими работами здесь

UnityException: Unable to start activity!
ку всем :jokingly: При билде появляется такой ексепшион : Error building Player:...

Как исправить ошибку "Unable to add window -- token null is not valid; is your activity running?"
Пишу приложение Android Studio. Надо добавить MusicController в приложении. При нажатии на кнопку...

Unable to create debug bridge unable to start adb server
Хочу отлаживать с телефона, не получается подцепиться к телефону. Телефон HTC. HTC Sync...

Как изменить кнопку на втором Activity с первого Activity в Android Studio?
Общая задача сделать уровни для игры, по окончанию первого уровня, появляется кнопка &quot;выбор уровня&quot;...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru