I have a code module which implements viewpager with navigation drawer, however, when I run the code I get the following error
01-26 09:20:02.958: D/AndroidRuntime(18779): Shutting down VM
01-26 09:20:02.959: E/AndroidRuntime(18779): FATAL EXCEPTION: main
01-26 09:20:02.959: E/AndroidRuntime(18779): Process: com.example.tabwithslidingdrawer, PID: 18779
01-26 09:20:02.959: E/AndroidRuntime(18779): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tabwithslidingdrawer/com.example.tabwithslidingdrawer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.ActivityThread.access$800(ActivityThread.java:148)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.os.Looper.loop(Looper.java:135)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.ActivityThread.main(ActivityThread.java:5312)
01-26 09:20:02.959: E/AndroidRuntime(18779): at java.lang.reflect.Method.invoke(Native Method)
01-26 09:20:02.959: E/AndroidRuntime(18779): at java.lang.reflect.Method.invoke(Method.java:372)
01-26 09:20:02.959: E/AndroidRuntime(18779): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
01-26 09:20:02.959: E/AndroidRuntime(18779): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
01-26 09:20:02.959: E/AndroidRuntime(18779): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
01-26 09:20:02.959: E/AndroidRuntime(18779): at com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.Activity.performCreate(Activity.java:5953)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
01-26 09:20:02.959: E/AndroidRuntime(18779): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
01-26 09:20:02.959: E/AndroidRuntime(18779): ... 10 more
09:20:02.959: E/AndroidRuntime(18779): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference 01-26 09:20:02.959: E/AndroidRuntime(18779): at com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95)
points to this line
// enabling action bar app icon and behaving it as a toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
entire code
http://pastebin.com/u1K72fr7
My manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tabwithslidingdrawer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.Tabwithpager" >
<activity
android:name="com.example.tabwithslidingdrawer.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>
android:theme=»@style/Theme.Tabwithpager»
code
http://pastebin.com/EFQLzRej
==================================================================
EDIT/UPDATE:
What I learnt from this
Whenever such an error occurs
1. Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.
2. Check if your activity type which is extended falls under the compat category
example android.app based Activity/Fragment are non appCompat types,
whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat
are appCompat based
if it falls under appCompat we use getSupportActionBar()
else for android.app types we can use getActionBar()
3. Check the theme applied to the activity in question in the manifest file
example:
In the manifest file if theme applied is say
android:theme=»@android:style/Theme.Holo.Dialog»
getActionBar() will work
but if theme applied for the activity in the manifest is as follows
android:theme=»@style/Theme.AppCompat.Light»
then you have to use
getSupportActionBar()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
name_home = (TextView) findViewById(R.id.name_home);
name_home.setText("abc");
06-03 23:31:03.847 25033-25033/dmitribak.clienttaxi.clienttaxi E/AndroidRuntime: FATAL EXCEPTION: main
Process: dmitribak.clienttaxi.clienttaxi, PID: 25033
java.lang.RuntimeException: Unable to start activity ComponentInfo{dmitribak.clienttaxi.clienttaxi/dmitribak.clienttaxi.clienttaxi.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ on a null object reference
at dmitribak.clienttaxi.clienttaxi.HomeActivity.onCreate(HomeActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
-
Вопрос заданболее трёх лет назад
-
7113 просмотров
Пригласить эксперта
Твой TextView name_home не нашелся в файле с разметкой. Ему присвоили null, вот иошибка. Проверь, что в файле с разметкой activity_home.xml есть TextView и ему назначен id как «@+id/name_home»
-
Показать ещё
Загружается…
09 июн. 2023, в 22:45
1000 руб./за проект
09 июн. 2023, в 22:39
500 руб./в час
09 июн. 2023, в 22:19
8000 руб./за проект
Минуточку внимания

This tutorial demonstrates how to solve the Attempt to invoke virtual method on a null object reference
error in Java.
the Attempt to invoke virtual method on a null object reference
Error in Java
While working on an Android application, the error Attempt to invoke virtual method on a null object reference
can occur, a type of NullPointerException
. Whenever we try to invoke a method using a null object, it will throw this error.
Here is a system based on the Android platform, which throws the NullPointerException
with the attempt to invoke virtual method on a null object reference
description.
This example has three different Java classes.
Main_Player.java
:
package delftstack;
import javax.naming.Context;
public class Main_Player {
private Context AppContext;
private SharedPreferences SharedPreferencesSettingsU;
private SharedPreferences.Editor PreferencesEditorU;
private static final int PREFERENCE_MODE = 0;
private static final String UNIQUE_PREFERENCES_FILE = "DemoApp";
public Player(Context AppContext, String Player_Name) {
this.AppContext = AppContext;
Save_Name(Player_Name);
}
public void Save_Name(String nValue) {
SharedPreferencesSettingsU = AppContext.getSharedPreferences(UNIQUE_PREFERENCES_FILE, PREFERENCE_MODE);
PreferencesEditorU = SharedPreferencesSettingsU.edit();
PreferencesEditorU.putString("keyName", nValue);
PreferencesEditorU.commit();
}
public String Get_Name(Context DemoContext) {
SharedPreferencesSettingsU = DemoContext.getSharedPreferences(UNIQUE_PREFERENCES_FILE, PREFERENCE_MODE);
String PlayerName = SharedPreferencesSettingsU.getString("keyName", "ANONYMOUS");
return PlayerName;
}
}
Player_Name.java
:
package delftstack;
import javax.naming.Context;
public class Player_Name extends Activity {
private EditText Player_Name;
private Player M_Player;
public static Context AppContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
AppContext = this;
Player_Name = (EditText) findViewById (R.id.etName);
}
public void onC_Confirm(View btnclick) {
M_Player = new Player(AppContext, String.valueOf(Player_Name.getText()));
//M_Player.saveName();
Intent intent = new Intent(Player_Name.this, Game_Play.class);
startActivity(intent);
}
public void onC_testShPref(View btnclick) {
Intent intent = new Intent(Player_Name.this, Game_Play.class);
startActivity(intent);
}
Game_Play.java
:
public class Game_Play extends Activity {
private TextView Welcome_Player;
private ListView Games_Created;
private Player M_Player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_game);
Welcome_Player = (TextView) findViewById (R.id.tvPlayer_Name);
Welcome_Player.setText("Welcome Back Player, " + String.valueOf(M_Player.getName(this)) + " !");
Games_Created = (ListView) findViewById (R.id.listCreatedGames);
Games_Created.setEmptyView(findViewById (R.id.tvNoGames));
}
}
We run the above system on an Android platform, which will throw an error caused by the java.lang.NullPointerException: Attempt to invoke virtual method
.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Main_Player.getName()' on a null object reference
at plp.cs4b.thesis.drawitapp.Game_Play.onCreate(Game_Play.java:20)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
The error occurs in the below code line in the class Game_Play.java
.
Welcome_Player.setText("Welcome Back Player, " + String.valueOf(M_Player.getName(this)) + " !");
This error occurs because the M_Player
comes as Null
. After all, it is not initialized. By initializing, we can solve that issue.
See the solution:
Game_Play.java
:
package delftstack;
public class Game_Play extends Activity {
private TextView Welcome_Player;
private ListView Games_Created;
//initialize the M_Player
private Player M_Player = new Main_Player(AppContext,"");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_game);
Welcome_Player = (TextView) findViewById (R.id.tvPlayer_Name);
Welcome_Player.setText("Welcome Back Player, " + String.valueOf(M_Player.getName(this)) + " !");
Games_Created = (ListView) findViewById (R.id.listCreatedGames);
Games_Created.setEmptyView(findViewById (R.id.tvNoGames));
}
}
So whenever working on a system like this, you must ensure that a method is not invoking any null
value; otherwise, it will throw this exception.
0 / 0 / 0 Регистрация: 22.02.2015 Сообщений: 43 |
|
1 |
|
12.03.2015, 21:50. Показов 38736. Ответов 8
Что исправить ошибку? java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.Text.setText(java.lang.CharSequence)’ on a null object reference
0 |
210 / 210 / 60 Регистрация: 22.08.2014 Сообщений: 644 |
|
12.03.2015, 21:56 |
2 |
Ну, так написано ж … попытка вызвать чего-то для null объекта.
0 |
0 / 0 / 0 Регистрация: 22.02.2015 Сообщений: 43 |
|
12.03.2015, 22:31 [ТС] |
3 |
А что значит инициализируйте
0 |
210 / 210 / 60 Регистрация: 22.08.2014 Сообщений: 644 |
|
12.03.2015, 22:34 |
4 |
Нуууу…выкладывайте код, где ошибка
0 |
cartman228 0 / 0 / 0 Регистрация: 12.03.2015 Сообщений: 5 |
||||
12.03.2015, 23:17 |
5 |
|||
Здравствуйте, это я Hisenberg228 вот мой код. ошибка код
0 |
Armagedo 210 / 210 / 60 Регистрация: 22.08.2014 Сообщений: 644 |
||||
12.03.2015, 23:39 |
6 |
|||
Так наставьте маяков…
1 |
344 / 236 / 33 Регистрация: 16.01.2010 Сообщений: 747 |
|
12.03.2015, 23:40 |
7 |
Судя по логу проблема у вас начинается в onClick() А дальше, соответственно все остальное тоже падает. at com.elik.ion.elik.Setting.onClick(Setting.java:44) Что у вас в коде в сроке 44?
0 |
0 / 0 / 0 Регистрация: 12.03.2015 Сообщений: 5 |
|
13.03.2015, 01:37 |
8 |
Спасибо большое, у меня появился встречный вопрос. Помогите, пожалуйста! Переводится почему то только txLang и txAb как это урегулировать?) Добавлено через 45 минут
0 |
Alex1126 28 / 25 / 8 Регистрация: 12.12.2020 Сообщений: 233 |
||||
15.02.2021, 20:25 |
9 |
|||
В 53 строке ошибка
Имя ресурса должно быть R.string.play а тут указан несуществующий вот вам и NULL
0 |
Comments
natansalda
added
triage me
I really want to be triaged.
type: bug
Error or flaw in code with unintended results or allowing sub-optimal usage patterns.
labels
Oct 21, 2021
barbeau
added
type: question
Request for information or clarification. Not an issue.
and removed
type: bug
Error or flaw in code with unintended results or allowing sub-optimal usage patterns.
triage me
I really want to be triaged.
labels
Oct 21, 2021
barbeau
changed the title
java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.hashCode()’ on a null object reference at pl.mytest.app.data.point.dto.AcceptancePoint.hashCode(Unknown Source:55) at com.google.maps.android.clustering.algo.NonHierarchicalDistanceBasedAlgorithm$QuadItem.hashCode(NonHierarchicalDistanceBasedAlgorithm.java:297)
java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.hashCode()’ on a null object reference
Oct 27, 2021