This question already has answers here:
Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
(2 answers)
Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
(9 answers)
Closed 5 years ago.
So I'm relatively new to Android and trying to build a Camera App. But I'm allready stuck with catching the Camera IDs.
I have my public CameraManager, a public String array and a public TextView and I was just trying to get the CameraIDs from my CameraManager and display the first of my IDs in my textview. And the App builds without errors but as soon as I try to execute it on my phone, it just crashes. Where is my mistake?
public CameraManager mCamera;
public String[] cameraIDs;
public TextView text = (TextView)findViewById(R.id.text);
And in my onCreate function:
try {
cameraIDs = mCamera.getCameraIdlist();
text.setText(cameraIDs[0]);
} catch (CameraAccessExeption e) {
text.setText("Sorry, couldn't find camera device.");
}
And, as requested, the error log from my phone:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test/com.example.test.ThrowActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
at android.app.ActivityThread.access$1000(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.test.ThrowActivity.<init>(ThrowActivity.java:26)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2350)
... 9 more
line ThrowActivity.java:26
public TextView text = (TextView)findViewById(R.id.text);
you need to initialise views inside the Activity onCreate method. Before setContentView is called you cannot look up views by id.
So replace this:
public TextView text = (TextView)findViewById(R.id.text);
with:
public TextView text;
//....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
text = (TextView)findViewById(R.id.text);
//...
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
When the register button is clicked the app should load another activity however it just crashes. Tried looking here and here for help but I still couldn't fix it. I also tried removing 'implements View.OnClickListner' and using it how its shown in the examples and it didn't work. Also tried changing the xml file to a LinearLayout and that didn't work either. Thanks in advance!
public class LogInActivity extends AppCompatActivity implements View.OnClickListener {
//user input variables
EditText emailAddressInput;
EditText passwordInput;
Button logInButton;
Button registerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout to activity_login.xml
setContentView(R.layout.activity_login);
//get user inputs and set to the variables
emailAddressInput = (EditText)findViewById(R.id.emailAddressInput);
passwordInput = (EditText)findViewById(R.id.passwordInput);
logInButton = (Button)findViewById(R.id.logInButton);
registerButton = (Button)findViewById(R.id.registerButton);
logInButton.setOnClickListener(this);
registerButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent registerIntent = new Intent (LogInActivity.this,RegisterActivity.class);
switch (view.getId())
{
case R.id.logInButton:
break;
case R.id.registerButton:
startActivity(registerIntent);
break;
}
}
}
EDIT:
the logcat:
2020-04-04 16:02:10.759 12718-12718/com.example.blooddonorsystem E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.blooddonorsystem, PID: 12718
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.blooddonorsystem/com.example.blooddonorsystem.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at com.example.blooddonorsystem.RegisterActivity.onCreate(RegisterActivity.java:56)
at android.app.Activity.performCreate(Activity.java:7825)
at android.app.Activity.performCreate(Activity.java:7814)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
In your RegisterActivity, seems like the Spinner you are setting the adapter to is null. Make sure it has correct value, usually its an ArrayAdapter of String.
The error is not in LoginActivity but in RegisterActivity.There is a null pointer exception in RegisterActivity when you are setting adapter to a spinner.
ERROR
**2020-03-01 17:36:58.959 6589-6589/com.studenthelper.bscit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.studenthelper.bscit, PID: 6589
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.studenthelper.bscit/com.studenthelper.bscit.MainActivity}: 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:2914)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:4785)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4694)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.studenthelper.bscit.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:7140)
at android.app.Activity.performCreate(Activity.java:7131)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2894)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:4785)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4694)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) **
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
TextView textView=findViewById(R.id.logotext);
int unicode=0x1F4A1;
String emoji=getEmoji(unicode);
String Text="Bsc"+emoji+"T";
textView.setText(Text);
}
public String getEmoji(int uni)
{
return new String(Character.toChars(uni));
}
As per your crash logs:
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at
com.studenthelper.bscit.MainActivity.onCreate(MainActivity.java:20)
It means your textView
TextView textView=findViewById(R.id.logotext);
Is not found from the layout R.layout.activity_main due to which when you try to textView.setText(Text); it's actually null and exception occurs.
So, I'll suggest to
Verify textVIew Id is same in the layout? and
Set the getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
before the setContentView(R.layout.activity_main);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView textView=findViewById(R.id.logotext);
int unicode=0x1F4A1;
String emoji=getEmoji(unicode);
String Text="Bsc"+emoji+"T";
textView.setText(Text);
}
To summarise the problem: You have defined two layouts, which one of them does not have a TextView. From your code obviously the crash is caused by calling .setText() on a null object.
The best way is always to add back the missing TextView back to your another layout, so all your layouts contains the same set of IDs. This can avoid bugs caused by findViewById(). In the layout which you do not need the TextView, you can simply set its android:visibility="gone" to hide it.
Alternatively back to your code, if you know the TextView is not always there, you can simply check if your textView variable is null or not, before calling .setText(). This can also avoid the NullPointerException.
I have an app with a login page.
First, I have my MainActivity where everything starts:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// here i launch LoginActivity
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE){
if(resultCode != Activity.RESULT_OK) {
finish();
}
// if login succesful, i attach to variable instance of
// logged user class.
// that part works correct, in object vars exist
loggedUser = loggedUser.getInstance();
// i want to attach strings after succesful login
emailText.setText(loggedUser.getEmail());
usernameText.setText(loggedUser.getUsername());
}
}
When run the app with the code above, after succesful LoginActivity app crashes with this exception:
2019-01-26 20:46:48.015 13071-13071/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 13071
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: 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.performResumeActivity(ActivityThread.java:3586)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:89)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
at android.app.Activity.performResume(Activity.java:7022)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
When I deleted the setText() methods from `onActivityResult(), I don't get that exception. The error appears when I click the Login button and the app crashes.
While debugging, compiler not even go in lines with setText()
My question is, how to set texts in textviews in the scenario that I coded above?
UPDATE
Even if i popualte strings in loggedUser in constructor as empty, move loggedUser = loggedUser.getInstance() and move setText() to onCreat, i still get that NPE.
EDIT:
I added onResume method:
#Override
protected void onResume()
{
if(isLogged) {
emailText.setText(loggedUser.getEmail());
usernameText.setText(loggedUser.getUsername());
}
super.onResume();
}
And edited onActivityResult():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE){
if(resultCode != Activity.RESULT_OK) {
finish();
}
isLogged = true; //var for if statement in onResume()
loggedUser = loggedUser.getInstance();
}
}
And i still get the same error on onResume() method when i setting up TextViews.
2019-01-26 21:21:57.752 18262-18262/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 18262
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: 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.performResumeActivity(ActivityThread.java:3586)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:90)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
at android.app.Activity.performResume(Activity.java:7022)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
A null view is usually a result of your layout not containing a view with the id you specified in findViewById(). Therefore findViewById() returns null and the variables are remaining null when onResume() is called. Double check your view ids in main_activity.xml.
It's also possible that the full content view is not available in onCreate() if you are using a more complicated layout. If you find that your views are null in onCreate(), try moving findViewById() to a later point in the lifecycle.
Try reordering the code like this
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
Try initializing the variables before accessing them.
public class MainActivity extends AppCompatActivity {
TextView emailText;
TextView usernameText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// here i launch LoginActivity
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
}
Could fit in a comment
You need to access the NavigationView from the activity
Update
NavigationView navigationView = findViewById(R.id.nav_id)
View header = navigationView.getHeaderView(0)
TextView usernameText = header.findViewById(R.id.username_text_view_id);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When clicking a Button to switch from the main Activity to my "ColoursGame" Activity the app crashes.
I'm still a beginner so not an expert at debugging.
The main activity code
Button colorsGame = (Button) findViewById(R.id.colours);
colorsGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ColoursGame.class));
}
});
Manifest new activity
<activity android:name=".ColoursGame"
android:label="ColourGame"
android:theme="#style/AppTheme.NoActionBar"></activity>
ColoursGame Activity OnCreate code
public class ColoursGame extends Activity {
int livesCount = 3;
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colours_game);
Button start = (Button) findViewById(R.id.startColors);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vSwitch.showNext();
x = String.valueOf(livesCount);
lives.setText(x);
text();
textColor();
backgroundColor();
start();
}
});
}
The Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aynaar.numbersgameforkids, PID: 3278
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.aynaar.numbersgameforkids/com.aynaar.numbersgameforkids.ColoursGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2323)
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
Don't call findViewById outside of onCreate, there's no Window to call findViewById at that point.
If you still get a NullPointer, then you must have #+id/startColors in activity_colours_game.xml
Answer explanation here
Button start = (Button) findViewById(R.id.startColors);
According to the error you are trying to reach a button that doesnt exist in your activity layout file (whatever it is). Check the id of your button and make sure it is placed on the layout page that related with your "ColoursGame" Activity.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm currently working on an android app to fetch data from the server. It crashes and I get a NullPointerException. Can anyone help me edit my code/ list out my error?
Here is my code (I have read a through few of the forums but did not really understand how to solve my problem)
public class MainActivity extends AppCompatActivity {
ListView lvPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPost = (ListView)findViewById(R.id.lvPost);
String url2 = "http://192.168.0.146/client/login.php?format=json";
PostResponseAsyncTask task2 = new PostResponseAsyncTask(MainActivity.this, new AsyncResponse() {
#Override
public void processFinish(String s) {
ArrayList<Post> postList =
new JsonConverter<Post>().toArrayList(s, Post.class);
ArrayList<String> titles = new ArrayList<String>();
for (Post value:postList) {
titles.add(value.post_title);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, titles);
lvPost.setAdapter(adapter);
}
});
task2.execute(url2);
}
}
Here is my logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.1231.t12.MainActivity$1.processFinish(MainActivity.java:40)
at com.kosalgeek.genasync12.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:188)
at com.kosalgeek.genasync12.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:27)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6075)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
It looks like String s parameter is null, use logging to confirm. In such case Gson.fromJson() returns null as a result. Then you're trying to iterate through the list postList which is null and this results to NullPointerException.