Checking if RadioButtons are not checked in java - 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");
}

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;
}
}}

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

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
}
}

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">

NullPointerException on TextView using setText()

I'm rather new to android programming, and am running into my old friend the NullPointerException...
I've been on it for quite a while now, but can't figure out what is wrong.
basicly gives me a NullPointerException when I try to call any .setText() methods, maybe someone sees what I'm doing wrong here...(though i tried to follow examples as close as possible)
public class lessonView extends Activity {
TextView adressOfLecture;
TextView lecturer;
TextView lesson;
Lecture lecture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson_view);
Bundle data = getIntent().getExtras();
lecture = (Lecture) data.getParcelable("student");
adressOfLecture = (TextView)findViewById(R.id.lectureViewAdressLabel);
lecturer = (TextView)findViewById(R.id.lectureViewLecturerLabel);
lesson = (TextView)findViewById(R.id.lectureViewTitle);
updateLabels();
}
#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_lesson_view, 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);
}
private void updateLabels(){
adressOfLecture.setText(lecture.getRoom());
lecturer.setText(lecture.getTutor());
lesson.setText(lecture.getName());
}
}
also, here's my xml file:
<RelativeLayout 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="com.coronarip7.app.stupla.lessonView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(ort)"
android:id="#+id/lectureViewAdressLabel"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/lectureViewTitle"
android:layout_marginRight="86dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dozent"
android:id="#+id/lectureViewLecturerLabel"
android:layout_toEndOf="#+id/lectureViewTitle"
android:layout_alignTop="#+id/lectureViewAdressLabel"
android:layout_alignParentEnd="true"
android:layout_marginRight="27dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lectureViewTitle"
android:gravity="center_horizontal"
android:text="test"
android:textSize="40dp"
android:textStyle="bold"
android:padding="10dp"
android:layout_row="0"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
and the logcat I'm getting:
04-25 01:23:51.058 12236-12236/com.coronarip7.app.stupla E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.coronarip7.app.stupla, PID: 12236
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coronarip7.app.stupla/com.coronarip7.app.stupla.lessonView}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
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:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.coronarip7.app.stupla.lessonView.updateLabels(lessonView.java:59)
at com.coronarip7.app.stupla.lessonView.onCreate(lessonView.java:31)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.access$800(ActivityThread.java:145)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5081)
            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:781)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)
seriously, I am out of ideas on how to fix it...
First check if you properly put the extra in the intent. Then I would use the following test in your onCreate method:
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
}
Then test if lecture is null like Rami wrote earlier.
Ok guys, thanks for the suggestions, but I'll go the global route. I'll create a static version of my array (from which i wanted to pass an object via the Intent), and just pass an int[] array with the coordiantes and call it in the new view.
But thanks for the quick answers anyways!
(I'm new to stackoverflow, is there a way to mark a question as "solved", or "not-needed-to-be-solved-anymore"?)
Do not use static objects in your code like arrays, objects, they have globally available, you should create intent and add your data into your intent like and call your activity
Intent intent = new Intent ();
intent.putExtra ("student",value);
start activity with intent
And in your
lessonViewActivity check for intent like
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
if (lecture !=null){
updateLabels ();
}
}

java.lang.IllegalStateException: cannot find button's onClick method in Android Studio

I am building an app named Ping in Android Studio. So far my activities are LoginActivity ProfileActivity and Timeline. My issue is that a button in the layout corresponding to the Timeline activity has an onClick method that isn't working. When the button is clicked, the emulator gives the "Unfortunatley, Ping has stopped." I'm defining the buttons and onClick methods the same way I have for other buttons whose functions are working, just this one does not seem to work. I'm receiving an error saying the method can't be found, but I've written the method in the corresponding activity. Here is the logcat:
04-30 10:40:08.727 2075-2075/com.ping_social.www.ping E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ping_social.www.ping, PID: 2075
java.lang.IllegalStateException: Could not find a method onProfilePress(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'profileButton'
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NoSuchMethodException: onProfilePress [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:4000)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Here is my Timeline activity class:
package com.ping_social.www.ping;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class TimeLine extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_line);
/*print log that shows we've got here*/
Log.i("LoginActivity", "Layout has been set");
}
#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_time_line, 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);
}
/*called when user presses the Log in button*/
public void onProfilePress(View view){
/*Log the button press*/
Log.i("TimeLine", "Has reached the onProfilePress method");
Intent intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
}
}
And here is my Timeline layout xml code:
<RelativeLayout 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"
android:theme="#style/GeneralTheme"
tools:context="com.ping_social.www.ping.TimeLine">
<TextView android:text="#string/no_pings" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textIsSelectable="false"
android:textColor="#color/PING_TOP_BAR_RED"
android:id="#+id/textView4" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/timeline_button"
android:id="#+id/timelineButton"
android:textColor="#color/PING_TOP_BAR_RED"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_ping_button"
android:id="#+id/newPingButton"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/activity_button"
android:id="#+id/activityButton"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/profile_button"
android:id="#+id/profileButton"
android:layout_weight="1"
android:onClick="onProfilePress"/>
</LinearLayout>
</RelativeLayout>
I'm pretty positive there are not spelling issues, and there are also no other buttons that share the same ID or methods that share the same name. Been stuck on this for a few days, any help is very much appreciated!
Ok, so I made my own test. I've put together a basic relative layout with a single button, put android:theme="#style/AppTheme" in it, and a button - app crashed with the same error. Then I removed android:theme attribute - onclick event fired as it should.
All the same happened when I used AppCompatActivity instead of now-deprecated ActionBarActivity.
It's hard for me to say why it doesn't work with android:theme. It's one of Lollipop's features, but I tried to launch in on API 5.0 emulator. The article states that currently this attribute is only supported for android.support.v7.widget.Toolbar.

Categories