How to check which radio buttons are checked upon pressing a button - java

I'm getting this error when I click on the button that executes a method.
Process: com.example.myapplication, PID: 7757
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6304)
at android.view.View$PerformClick.run(View.java:24803)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
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:823)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6304) 
at android.view.View$PerformClick.run(View.java:24803) 
at android.os.Handler.handleCallback(Handler.java:794) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:176) 
at android.app.ActivityThread.main(ActivityThread.java:6635) 
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:823) 
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatButton cannot be cast to android.widget.RadioButton
at com.example.myapplication.MockTest.submitbtn(MockTest.java:66)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:6304) 
at android.view.View$PerformClick.run(View.java:24803) 
at android.os.Handler.handleCallback(Handler.java:794) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:176) 
at android.app.ActivityThread.main(ActivityThread.java:6635) 
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:823) 
The method is called upon by android:onClick through xml upon clicking the button.
This is the method,
public void submitbtn(View view)
{
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.q1r1: if (checked)
score++;
break;
case R.id.q2r4: if (checked)
score++;
break;
case R.id.q3r4: if (checked)
score++;
break;
case R.id.q4r2: if (checked)
score++;
break;
}
}
this is the xml entry for the button,
<Button
android:id="#+id/submitbtn"
android:layout_width="100dp"
android:layout_height="65dp"
android:layout_marginStart="150dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="150dp"
android:text="Submit"
android:onClick="submitbtn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/q4r" />
I looked at the error and noticed that it says it's caused because radiobutton widget cannot be cast to button widget, is that right? if so how can I implement this. What I'm trying to do is simply check the radio button's current state(checked or not) once the button is clicked. My previous approach, which worked, was this exact method but called from a radiobutton. I had put an android:onClick on the radiobutton's xml file. But this somehow does not work.

Found the solution, apparently I need to use radiogroups instead of directly using radiobuttons, the only change I made is in the code, here it is,
public void submitbtn(View view)
{
RadioGroup q4r = findViewById(R.id.q4r);
//Checking which radio button is checked, if any, and then executing tasks
if(q1r.getCheckedRadioButtonId() == R.id.q1r1)
{
//execute tasks
}
else if(q1r.getCheckedRadioButtonId() == -1)
{
//Nothing
}
else
{
//execute tasks
}
}

Related

NullPointerException at onClick method

I am making an app on Android Studio and I ran into the NullPointerException in my onClick method. How do I fix it?
The debugger of my app gives me this:
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.venttome.ventingPage.onClick(ventingPage.java:66)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
The code (the onClick() method) that is wrong:
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.record_btn:
if (isRecording){
//stop recording
recordButton.setImageDrawable(getResources().getDrawable(R.drawable.record_btn_stopped, null));
isRecording = false;
} else {
//start recording
recordButton.setImageDrawable(getResources().getDrawable(R.drawable.record_btn_recording, null));
isRecording = true;
}
break;
}
}
And this is my XML file for that class, and it is a constraint layout. This is what I use for my onClick method and I don't know what's wrong with it:
<ImageView
android:id="#+id/record_btn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginStart="40dp"
android:layout_marginLeft="40dp"
android:layout_marginBottom="28dp"
android:background="#android:color/white"
android:clickable="true"
android:cropToPadding="true"
android:onClick="onClick"
android:src="#drawable/record_btn_stopped"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toLeftOf="#id/final_button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/inputFeelings"
app:layout_constraintVertical_bias="1.0"
android:focusable="true"
tools:ignore="ContentDescription" />
you are not initializing the button in your method.Please first do this in your onCreate() method or if you are using fragment then in onCreateView():
ImageView record_btn= findViewById(R.id.record_btn);
Please initialize the view inside onCreate()
Here is the working code snippet
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
ImageView recordButton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recordButton = findViewById(R.id.record_btn);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.record_btn:
Toast.makeText(this, "Called", Toast.LENGTH_SHORT).show();
recordButton.setImageResource(R.drawable.ic_launcher_foreground);
break;
}
}}

Checking if RadioButtons are not checked in java

I'm learning android making a simple calculator in Java like the one in the image. my calculator
When I try the app, neither of the Radio Buttons are checked, so when I press the 'calculate' button the app shuts down.
I tried making a comprobation and if neither of the buttons are checked the app shows a Toast but the app shuts down anyway.
This is the comprobation code (where btnSumar and btnRestar are the RadioButtons):
if(!btnSumar.isChecked() && !btnRestar.isChecked()) {
Toast.makeText(MainActivity.this, "Please, select one option", Toast.LENGTH_SHORT).show();
}
It seems logic to me, but it doesn't work.
Thanks for helping!
this is logcat
2020-09-06 18:51:48.814 10245-10245/com.triopsstudio.seccion01 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.triopsstudio.seccion01, PID: 10245
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7448) 
at android.view.View.performClickInternal(View.java:7425) 
at android.view.View.access$3600(View.java:810) 
at android.view.View$PerformClick.run(View.java:28305) 
at android.os.Handler.handleCallback(Handler.java:938) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.parseInt(Integer.java:650)
at com.triopsstudio.seccion01.MainActivity.Calcular(MainActivity.java:53)
According to your stacktrace you have a NumberFormatException because you have no input yet. You try to parse number from empty string. Integer.parseInt("") leads to Exception ( lines 53 MainActivity class)
You can make one of radiobutton checked by default and it's id from radioGroup
ex:
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_female" />
</RadioGroup>
MainActivity:
//top level declaration..
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
Inside onCreate(Bundle savedInstanceState)
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);//this will have selected button id
Use the isChecked() function for every radioButton you have to check.
RadioButton maleRadioButton, femaleRadioButton;
maleRadioButton = (RadioButton) findViewById(R.id.maleRadioButton);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleRadioButton);
Then use the result for your code case consideration to check radiobutton.
if (maleRadioButton.isChecked() || femaleRadioButton.isChecked()) {
Log.d("QAOD", "Gender is Selected");
} else {
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
Log.d("QAOD", "Gender is Null");
}

Fixing error with Gridlayout casting to ImageView

I have the .xml file set up as
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:columnCount="4"
android:rowCount="6"
android:onClick="dropIn"
android:layout_alignParentEnd="true"
android:id="#+id/gridLayout">
<ImageView
android:id="#+id/imageView1"
android:layout_width="80dp"
android:layout_height="70dp"
android:layout_column="0"
tools:layout_editor_absoluteX="288dp"
tools:layout_editor_absoluteY="180dp"
android:layout_row="0"
android:onClick="dropIn"
android:contentDescription="#null"
android:tag="1"
app:srcCompat="#drawable/stone" />
Anyways, I have plenty more of ImageViews and the thing that makes them different is the id and the tag. I decided to have them recognized by code by their tag. So this is what I currently have:
int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
public void dropIn(View view) {
ImageView counter = (ImageView) view;
counter.setImageResource(R.drawable.stone);
int tappedCounter = Integer.parseInt(counter.getTag().toString());
try {
if (gameState[tappedCounter] == 2 && gameIsActive) {
gameState[tappedCounter] = 3;
countMe = countMe - 1;
counter.setVisibility(View.INVISIBLE);
} else if (gameState[tappedCounter] == 3 && gameIsActive) {
Toast.makeText(MainActivity.this, "That field is already played!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Oho!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
This all works fine, except when I click an ImageView that has already been clicked and is now invisible, it crashes the app with the following message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nedim.lastonestanding, PID: 9758
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:5374)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:5369)
at android.view.View.performClick(View.java:6294) 
at android.view.View$PerformClick.run(View.java:24770) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Caused by: java.lang.ClassCastException: android.widget.GridLayout cannot be cast to android.widget.ImageView
at com.nedim.lastonestanding.MainActivity.dropIn(MainActivity.java:32)
at java.lang.reflect.Method.invoke(Native Method) 
at android.view.View$DeclaredOnClickListener.onClick(View.java:5369) 
at android.view.View.performClick(View.java:6294) 
at android.view.View$PerformClick.run(View.java:24770) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Application terminated.
From what I understand, the Image from the ImageView disappears and now I am clicking on the GridLayout and not the ImageView which causes it to crash as it's not the thing that I want to be working with. I also suppose that the problem is that counter is making all views become ImageViews, but I am not sure how I could fix this. Any ideas? Thanks!
EDIT: The onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView winMessage = findViewById(R.id.winMessage);
winMessage.setText("Let's play! It's Player " + activePlayer + "'s turn.");
}
You have the same attribute android:onClick="dropIn" declared both for GridLayout and ImageView. The 1st one causes the ClassCastException at the line ImageView counter = (ImageView) view;
The view which is passed to dropIn function is a GirdLayout which you are trying to cast as an ImageView.
GridLayout counter = (GridLayout) view;
However, I see you are using the same function to handle the onClick of the ImageView as well, which you cannot. If you want to handle them both using the same function, you might consider doing something like this.
public void dropIn(View view) {
if(view.getId() == R.id.gridLayout) {
// Handle action for GridLayout click
} else if(view.getId() == R.id.imageView1) {
// Handle the actions for ImageView click
}
}
Personally I think, you have put your onClick in your GridLayout wrongly. So just omit the onClick attribute from the GridLayout xml.
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:columnCount="4"
android:rowCount="6"
<!-- android:onClick="dropIn" -->
android:layout_alignParentEnd="true"
android:id="#+id/gridLayout">

Setting up an avatar on android app

I'm wanting to let the user create an avatar (profile picture if you like) when they set up their user info. I've created a method for a single click/touch which would ask the user to take a picture and one for a long click which would ask the user to choose a picture from their gallery.
Below are my methods from the class file:
public void onLaunchCamera(View v) {
avatarButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strAvatarPrompt = "Take your picture to store as your avatar!";
Intent pictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(pictureIntent, strAvatarPrompt), TAKE_AVATAR_CAMERA_REQUEST);
}
});
avatarButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
String strAvatarPrompt = "Choose a picture to use as your avatar!";
Intent pickPhoto = new Intent(Intent.ACTION_PICK);
pickPhoto.setType("image/*");
startActivityForResult(Intent.createChooser(pickPhoto, strAvatarPrompt), TAKE_AVATAR_GALLERY_REQUEST);
return true;
}
});
}
And below is the XML associated with the ImageButton:
<ImageButton
android:id="#+id/ImageButton_Avatar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxHeight="#dimen/avatar_size"
android:minHeight="#dimen/avatar_size"
android:onClick="onLaunchCamera"
android:scaleType="fitXY"
android:src="#drawable/avatar"></ImageButton>
All it does is crash when I click on the ImageButton and I have no idea why. Any ideas?
Thanks
EDIT: Adding the logcat below (Sorry about the formatting. Couldn't work out how to get it all sorted properly:
[ 04-12 18:32:50.989 5901: 5901 D/ ]
HostConnection::get() New Host Connection established 0xb8a44530, tid 5901
04-12 18:32:51.039 5901-5901/cct.mad.lab D/OpenGLRenderer: Enabling debug mode 0
04-12 18:32:55.739 5901-5901/cct.mad.lab V/RenderScript: 0xb8c53300 Launching thread(s), CPUs 2
04-12 18:32:57.389 5901-5901/cct.mad.lab D/AndroidRuntime: Shutting down VM
04-12 18:32:57.389 5901-5901/cct.mad.lab W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb0d2db20)
04-12 18:32:57.399 5901-5901/cct.mad.lab E/AndroidRuntime: FATAL EXCEPTION: main
Process: cct.mad.lab, PID: 5901 java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at a android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438) 
at android.view.View$PerformClick.run(View.java:18422) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at cct.mad.lab.SettingsActivity.onLaunchCamera(SettingsActivity.java:201)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at android.view.View$1.onClick(View.java:3818) 
at android.view.View.performClick(View.java:4438) 
at android.view.View$PerformClick.run(View.java:18422) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
It looks like you might not have defined avatarButton, if you follow the Caused By path on the LogCat you see the bottom one is a NullPointerException.
Since I can't see the line numbers, the issue is happening on line 201--the only obvious null pointer I see in your code is avatarButton.
Based on what you want to do, you'll want to go about this a bit differently.
Remove the android:onClick="onLaunchCamera" from the XML.
in your onCreate() after you set the content view add the following:
View avatarButton = findViewById(R.id.ImageButton_Avatar);
avatarButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strAvatarPrompt = "Take your picture to store as your avatar!";
Intent pictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(pictureIntent, strAvatarPrompt), TAKE_AVATAR_CAMERA_REQUEST);
}
});
avatarButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
String strAvatarPrompt = "Choose a picture to use as your avatar!";
Intent pickPhoto = new Intent(Intent.ACTION_PICK);
pickPhoto.setType("image/*");
startActivityForResult(Intent.createChooser(pickPhoto, strAvatarPrompt), TAKE_AVATAR_GALLERY_REQUEST);
return true;
}
});
This allows you to set both a click and a longClick listener with more control. The way you had it, you were never really defining the onClick or onLongClick until you clicked on them the first time.

Android error Attempt to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
I would like to set my variables at the top of my class instead of in the method
(4 answers)
Closed 7 years ago.
I'm new to Android Studio (and am hating the transition experience from Eclipse). I'm trying to write an app that currently has two activities. I already wrote the Java code for the main logic and it works fine, but haven't put it in the second activity yet. As I'm trying to write and run the app, it gives me an error.
There's a LoginActivity and MainActivity. Currently LoginActivity just has a dummy text and a button that takes the user to MainActivity. Currently MainActivity has just a TextView in it. When I click it, the app crashes and gives the following error. I can see it has something to do with initiating MainActivity but I can't seem to fix it.
09-10 20:16:43.012 21126-21126/com.projects.example.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.projects.example.myapp, PID: 21126
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.projects.example.myapp/com.projects.example.myapp.MainActivity}: 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:2267)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
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:2072)
at com.projects.example.myapp.MainActivity.<init>(MainActivity.java:22)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
            at android.app.ActivityThread.access$900(ActivityThread.java:154)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5289)
            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:904)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
My xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".LoginActivity"
android:orientation="vertical" >
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/loginbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="goToMainActivity" />
</LinearLayout>
LoginActivity relevant code:
public void goToMainActivity(View view)
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
MainActivity code as requested (line 22 is indicated by the prefix **):
public class MainActivity extends AppCompatActivity {
String currentWinnerName = "";
**TextView currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);**
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentWinnerLabel.setText("Finding...");
//try
//{
//checkCurrentWinner(); //will implement this
//}
//catch (Exception e)
//{
//print e.getMessage() to log
//}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The reason is, that you are trying to assign value to currentWinnerLabel before activity is created.
Unless activity is created, the context is null, and you are calling findViewById method on a null object reference.
Just change your code:
TextView currentWinnerLabel;
and after:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);
...

Categories