Android Studio two buttons Java code error - java

Can anyone tell me what I am missing, this is driving me crazy.
Below is the java code for the Profile Activity. I've only been at this for about 30 days now and a lot is still confusing to me.
When I run the emulator, it opens, then crashes after the first button
that is supposed to send the user to the second activity.
Running Logcat, it gets hung up on line 26 of the page posted below, stating it hates something about my Listener for Button 2.
Help???
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Button Click Goes to Main Activity
Button button1 = (Button) findViewById(R.id.start_over);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
back();
}
});
// Button Click Goes To Third Activity
Button button2 = (Button) findViewById(R.id.forward);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward();
}
});
}
private void back() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void forward() {
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
}
Logcat File is below:
FATAL EXCEPTION: main
Process: com.defy, PID: 2481
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.defy/com.defy.ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.defy.ProfileActivity.onCreate(ProfileActivity.java:26)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method)
MainActivity .XML Below:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.defy.trailmaster.MainActivity">
<ImageView
android:id="#+id/background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/start_hiking"
android:layout_width="95dp"
android:layout_height="35dp"
android:background="#000000"
android:text="#string/app_start"
android:textColor="#FDFEFE"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.868"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.966"
tools:layout_editor_absoluteX="242dp" />
<ImageView
android:id="#+id/tent"
android:layout_width="121dp"
android:layout_height="96dp"
android:contentDescription="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.06"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.26"
app:srcCompat="#drawable/tent" />
<ImageView
android:id="#+id/hiker_right"
android:layout_width="92dp"
android:layout_height="90dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="37dp"
android:layout_marginTop="8dp"
android:contentDescription="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.991"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.889"
app:srcCompat="#drawable/hiker_right"
tools:ignore="MissingConstraints,RtlHardcoded" />
</android.support.constraint.ConstraintLayout>
Main Activity .JAVA Below:
package com.defy.trailmaster;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button Click Goes To Profile Activity
Button button = (Button) findViewById(R.id.start_hiking);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hike();
}
});
}
private void hike() {
Intent intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
}
}
Last is the Manifest file Below:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ProfileActivity" />
<activity android:name=".ThirdActivity"></activity>
</application>
Profile Activity XML Below:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_profile"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.defy.trailmaster.ProfileActivity">
<ImageView
android:id="#+id/background"
android:layout_width="0dp"
android:layout_height="0dp"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="#+id/start_over"
android:layout_width="95dp"
android:layout_height="35dp"
android:background="#000000"
android:text="#string/app_back"
android:textColor="#FDFEFE"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.145"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.966" />
<Button
android:id="#+id/hike_now"
android:layout_width="95dp"
android:layout_height="35dp"
android:background="#000000"
android:text="#string/app_hike"
android:textColor="#FDFEFE"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.868"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.966" />
<ImageView
android:id="#+id/tent"
android:layout_width="121dp"
android:layout_height="96dp"
android:contentDescription="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.06"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.26"
app:srcCompat="#drawable/tent" />
<ImageView
android:id="#+id/left_hiker"
android:layout_width="92dp"
android:layout_height="90dp"
android:layout_marginBottom="0dp"
android:layout_marginStart="42dp"
android:layout_marginLeft="42dp"
android:layout_marginRight="8dp"
android:layout_marginEnd="8dp"
android:contentDescription="#string/app_name"
app:layout_constraintBottom_toTopOf="#+id/start_over"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="#+id/hiker_right"
app:srcCompat="#drawable/hiker_left" />
<ImageView
android:id="#+id/hiker_right"
android:layout_width="92dp"
android:layout_height="90dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="37dp"
android:layout_marginTop="8dp"
android:contentDescription="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.991"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.889"
app:srcCompat="#drawable/hiker_right"
tools:ignore="MissingConstraints,RtlHardcoded" />
</android.support.constraint.ConstraintLayout>

It is crashing most likely due to R.id.forward, button2 is null.
It looks like you either named the button id something else, or missed it.
Post the XML for ProfileActivity

Here's your problem. button2 should refer to hike_now
Final Button button2 = (Button) findViewById(R.id.hike_now);

Related

Setting up a text view as a clickable button

I am developing a simple application which allows users to login using a username and password, I am trying to set up a "register" link in the form of a TextView which will take the user to the register page of the app. I can't find any error in my coding or logic but when I run the app and click the register link, the app just shuts down.
Here is my MainActivity code -
package com.example.squashsademo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText mTextUsername;
EditText mTextPassword;
Button mButtonLogin;
TextView mTextViewRegister;
// #RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextUsername = (EditText)findViewById(R.id.edittext_username);
mTextPassword = (EditText)findViewById(R.id.edittext_password);
mButtonLogin = (Button)findViewById(R.id.button_login);
mTextViewRegister = (TextView)findViewById(R.id.textview_register);
mTextViewRegister.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent registerIntent = new Intent(MainActivity.this,RegisterActivity.class);
startActivity(registerIntent);
}
});
}
}
Here is the RegisterActivity I am trying to get to -
package com.example.squashsademo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends AppCompatActivity {
EditText mTextUsername;
EditText mTextPassword;
EditText mTextCnfPassword;
Button mButtonRegister;
TextView mTextViewLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mTextUsername = (EditText)findViewById(R.id.edittext_username);
mTextPassword = (EditText)findViewById(R.id.edittext_password);
mTextCnfPassword = (EditText) findViewById(R.id.edittext_cnf_password);
mButtonRegister = (Button)findViewById(R.id.button_login);
mTextViewLogin = (TextView)findViewById(R.id.textview_register);
mTextViewLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent LoginIntent = new Intent(RegisterActivity.this,MainActivity.class);
startActivity(LoginIntent);
}
});
}
}
and here is my AndroidManifest -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.squashsademo">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.SquashSADemo">
<activity android:name=".RegisterActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can anyone help see why this is not working because from my understanding it should be :(
Thank you
EDIT - here are the layout files aswell
MainActivity -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#drawable/background">
<ImageView
android:layout_width="299dp"
android:layout_height="80dp"
app:srcCompat="#drawable/logo" />
<EditText
android:id="#+id/edittext_username"
android:layout_width="356dp"
android:layout_height="57dp"
android:layout_marginTop="160dp"
android:background="#drawable/custom_input"
android:drawableLeft="#drawable/username"
android:drawablePadding="12dp"
android:hint="#string/username"
android:textColorHint="#color/white"/>
<EditText
android:id="#+id/edittext_password"
android:layout_width="356dp"
android:layout_height="57dp"
android:layout_marginTop="20dp"
android:background="#drawable/custom_input"
android:drawableLeft="#drawable/password"
android:drawablePadding="12dp"
android:hint="#string/password"
android:textColorHint="#color/white"/>
<Button
android:id="#+id/button_login"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="20dp"
android:text="#string/login"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="35dp"
android:textColor="#ffffff"
android:text="#string/not_registered"/>
<TextView
android:id="#+id/textview_register"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:paddingLeft="10dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:text="#string/register"/>
</LinearLayout>
</LinearLayout>
RegisterActivity -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context=".RegisterActivity">
<ImageView
android:layout_width="298dp"
android:layout_height="80dp"
app:srcCompat="#drawable/logo" />
<EditText
android:id="#+id/edittext_username"
android:layout_width="356dp"
android:layout_height="57dp"
android:layout_marginTop="160dp"
android:background="#drawable/custom_input"
android:drawableLeft="#drawable/username"
android:drawablePadding="12dp"
android:hint="#string/username"
android:textColorHint="#color/white"/>
<EditText
android:id="#+id/edittext_password"
android:layout_width="356dp"
android:layout_height="57dp"
android:layout_marginTop="20dp"
android:background="#drawable/custom_input"
android:drawableLeft="#drawable/password"
android:drawablePadding="12dp"
android:hint="#string/password"
android:textColorHint="#color/white" />
<EditText
android:id="#+id/edittext_cnf_password"
android:drawablePadding="12dp"
android:background="#drawable/custom_input"
android:layout_width="356dp"
android:layout_height="57dp"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/password"
android:hint="#string/confirm_password"
android:textColorHint="#color/white"/>
<Button
android:id="#+id/button_register"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="20dp"
android:text="#string/register"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="35dp"
android:textColor="#ffffff"
android:text="#string/already_registered"/>
<TextView
android:id="#+id/textview_login"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:paddingLeft="10dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="16dp"
android:text="#string/login"/>
</LinearLayout>
</LinearLayout>
here are the log files aswell -
2020-10-21 20:56:22.881 11328-11328/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.squashsademo, PID: 11328
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.squashsademo/com.example.squashsademo.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3654)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3806)
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:2267)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8167)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.squashsademo.RegisterActivity.onCreate(RegisterActivity.java:28)
at android.app.Activity.performCreate(Activity.java:7963)
at android.app.Activity.performCreate(Activity.java:7952)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3629)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3806) 
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:2267) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:237) 
at android.app.ActivityThread.main(ActivityThread.java:8167) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100) 
Below line of code is throwing NullPoinerException
mTextViewLogin = (TextView)findViewById(R.id.textview_register);
in the register activity layout, there is no id as textview_register that's why you are getting the issue
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
possible fix using below line
mTextViewLogin = (TextView)findViewById(R.id.textview_login);
instead of
mTextViewLogin = (TextView)findViewById(R.id.textview_register);
you can see you are trying to link XML view to java with an invalid id

java.lang.IllegalStateException: Could not execute method for android:onClick / Android

Does any one know how to fix this error, THANK YOU!!
I think something wrong with "public void choose answer" in MainActivity, because then i try press on 1 of 4 buttons I get this error and app crash.
Error message:
FATAL EXCEPTION: main
Process: com.example.braintrainer, PID: 19387
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.braintrainer.MainActivity.chooseAnswer(MainActivity.java:24)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Here all buttons have same onClick (maybe here something wrong?)- android:onClick="chooseAnswer"
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#4CAF50"
android:onClick="start"
android:text="Go!"
android:textSize="60sp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#4CAF50"
android:text="30s"
android:textAlignment="center"
android:textSize="25sp" />
<TextView
android:id="#+id/sumTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="31 + 12"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25sp" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#03A9F4"
android:text="0/0"
android:textAlignment="center"
android:textSize="25sp" />
</LinearLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/gridLayout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constrainedHeight="true"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toTopOf="#+id/resultTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_max="300dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout"
app:layout_constraintWidth_max="300dp">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<Button
android:id="#+id/button0"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#9C27B0"
android:onClick="chooseAnswer"
android:text="3"
android:textSize="36sp"
app:layout_constraintBottom_toTopOf="#+id/guideline2"
app:layout_constraintEnd_toStartOf="#+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#CDDC39"
android:onClick="chooseAnswer"
android:text="3"
android:textSize="36sp"
app:layout_constraintBottom_toTopOf="#+id/guideline2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#FF5722"
android:onClick="chooseAnswer"
android:text="3"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline2" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#4CAF50"
android:onClick="chooseAnswer"
android:text="3"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/guideline2" />
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:id="#+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct!"
android:textSize="40sp"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="#+id/startButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here Im trying call buttons from "public void chooseAnswer(View view)" to check if they are working and Im getting their id
MainActivity.java
package com.example.braintrainer;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button startButton;
TextView resultTextView;
ArrayList<Integer> answers = new ArrayList<Integer>();
int locationOfCorrectAnswer;
int score = 0;
public void chooseAnswer(View view){
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
Log.i("TAG", String.valueOf(view.getTag()));
}
}
public void start(View view){
startButton.setVisibility(View.INVISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button)findViewById(R.id.startButton);
TextView sumTextView = (TextView)findViewById(R.id.sumTextView);
Button button0 = (Button)findViewById(R.id.button0);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
resultTextView = (TextView)findViewById(R.id.resultTextView);
Random rand = new Random();
int a = rand.nextInt(21);
int b = rand.nextInt(21);
sumTextView.setText(Integer.toString(a) + " + " + Integer.toString(b));
locationOfCorrectAnswer = rand.nextInt(4);
int incorrectAnswer;
for (int i=0; i<4; i++){
if (i == locationOfCorrectAnswer){
answers.add(a + b);
} else {
incorrectAnswer = rand.nextInt(41);
while (incorrectAnswer == a + b){
incorrectAnswer = rand.nextInt(41);
}
answers.add(incorrectAnswer);
}
}
button0.setText(Integer.toString(answers.get(0)));
button1.setText(Integer.toString(answers.get(1)));
button2.setText(Integer.toString(answers.get(2)));
button3.setText(Integer.toString(answers.get(3)));
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.braintrainer">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You try to check buttons by tag but you didn't set any tags in xml
It's a NullPointerException caused by this. Please check
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
Log.i("TAG", String.valueOf(view.getTag()));
}
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
as view.getTag() return null.
try to set the tag to your Buttons like this:
<Button
android:id="#+id/button0"
android:tag="1" // this line
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#9C27B0"
android:onClick="chooseAnswer"
android:text="3"
android:textSize="36sp"
app:layout_constraintBottom_toTopOf="#+id/guideline2"
app:layout_constraintEnd_toStartOf="#+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Not switching accounts in same project on button click

This is an app about layout
first the screen will be in portrait layout on clciking button it will be changed to landscape layout.so here on clicking button it is not going to next activity though no compilation errors are found
activity_main.xml
?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vamshivikas.orientation.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="28dp"
android:text="#string/this_is_potrait_layout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.48"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.15" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="47dp"
android:layout_marginStart="8dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="#string/go_to_next_activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</android.support.constraint.ConstraintLayout>
activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="#string/this_is_landscape_layout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
activityManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vamshivikas.orientation">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name="com.example.vamshivikas.orientation.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:screenOrientation="landscape">
</activity>
</application>
</manifest>
mainActivity.java
package com.example.vamshivikas.orientation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
}
public void onClcik(View v){
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
secondActivity.java
package com.example.vamshivikas.orientation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SecondActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
As I see you have no onClick-Attribute in your Button-Element in activity_main.xml.
Give your Button an onClick-Attribute like this
<Button
android:onClick="onButtonNextActivityClick"
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="47dp"
android:layout_marginStart="8dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="#string/go_to_next_activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
and then create a public void method in MainActivity.java with the same name and handle your stuff in there. Like this:
public void onButtonNextActivityClick(View v){
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
And Consider using MrFishermans solution too
If I understand you in a good way, you want to go the another Activity when you click on Button? You also want to switch View to Landscape?
You can do: (in onClick() function)
Intent intent = new Intent(this, AnotherActivity.class);
startActivity(intent);
And then in your second activity, in onCreate() function call:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

android java Null point exeption at view.setonclicklistener at the secend init why they do not match

I have this problem and it shows me following error
please help me:
I get a NullPointerException in init2(). Apperently sms is null.
I don't understand the problem
Process: com.example.android.projectdestage, PID: 11049
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.android.projectdestage/com.example.android.projectdestage.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
com.example.android.projectdestage.MainActivity.init2(MainActivity.java:60)
at
com.example.android.projectdestage.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6956)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
****this is my main activity****
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity
{
private Button sms;
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
if(isServicesOK()){
init();
init2();
}
}
private void init(){
Button btnMap = (Button) findViewById(R.id.btnMap);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MapActivity.class);
startActivity(intent);
}
});
}
private void init2()
{
Button sms = (Button) findViewById(R.id.sms);
sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent message = new Intent(MainActivity.this, MainActivity2.class);
startActivity(message);
}
});
}
public boolean isServicesOK()
{
Log.d(TAG, "isServicesOK: checking google services version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MainActivity.this);
if(available == ConnectionResult.SUCCESS)
{
// koulchi mli7 map request
Log.d(TAG, "isServicesOK: Google Play Services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(available))
{
//test d erreur
Log.d(TAG, "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else
{
Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show();
}
return false;
}
}
`**this is my mainactivity xml**`
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.projectdestage.MainActivity">
<Button
android:id="#+id/btnMap"
android:layout_width="87dp"
android:layout_height="45dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="244dp"
android:text="#string/map"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/smsbtn"
android:layout_width="wrap_content"
android:layout_height="43dp"
android:layout_marginBottom="136dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/enter_your_message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
**and the main2activity xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.example.android.projectdestage.MainActivity2">
<TextView
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/enter_your_message"
android:textSize="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="519dp"
android:orientation="vertical">
<TextView
android:id="#+id/editText2"
android:layout_width="385dp"
android:layout_height="410dp"
android:layout_marginTop="50dp"
android:layout_weight="1"
android:text="#string/textview" />
<Button
android:id="#+id/btnSendSMSendSms"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginLeft="150dp"
android:layout_marginStart="150dp"
android:layout_marginVertical="110dp"
android:layout_weight="1"
android:text="#string/sendsms"
tools:targetApi="o" />
</LinearLayout>
</LinearLayout>
and the the mapactivity xml
i think the main problem is here
<?xml version="1.0" encoding="utf-8"?>
<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">
<fragment 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:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="#drawable/white_border"
android:id="#+id/relLayout1" tools:targetApi="lollipop">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="#+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_magnify" android:contentDescription="#string/todoo" android:layout_marginStart="10dp" />
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/ic_magnify"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#000"
android:id="#+id/input_search"
android:background="#null"
android:hint="#string/enter_address_city_or_zip_code"
android:imeOptions="actionSearch" android:layout_toEndOf="#+id/ic_magnify" />
</RelativeLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#id/relLayout1"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:id="#+id/ic_gps"
android:src="#drawable/ic_gps" android:contentDescription="#string/todo" android:layout_alignParentEnd="true" android:layout_marginEnd="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:layout_below="#+id/relLayout1"
android:src="#drawable/ic_map" android:contentDescription="#string/todoml" android:layout_marginStart="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:id="#+id/place_info"
android:src="#drawable/ic_info" android:layout_marginStart="10dp" android:contentDescription="#string/todoop" />
</RelativeLayout>
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
Button sms = (Button) findViewById(R.id.sms); returns null
This means he can not find R.id.sms in your activity_main.xml layout.
Maybe a typo or copy paste error? Check if this button's ID in this file really is sms.
Also if you have multiple layouts for different screen sizes, etc. Check all of them.
You have smsBtn as an id for sms Button in your activity_main.xml, whereas you've passed sms as id. So id with sms is not found and so button is null and throws null pointer exception.
There is better approach that can accomplish this using Butterknife library:
public class MainActivity extends AppCompatActivity
{
#BindView(R.id.smsBtn)
private Button sms;
#BindView(R.id.btnMap)
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#OnClick({R.id.btnMap, R.id.smsBtn})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnMap:
//Your functionality
break;
case R.id.smsBtn:
//Your functionality
break;
}
}
}
//Dependency for ButterKnife library
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//Butterknife link
https://github.com/JakeWharton/butterknife

My first app isn't working and it crashes: UnsupportedOperationException

I am new to Android and I started making my first application following tutorials and such. However, when I click the run button it gives me following error on the logcat from which I count not identify where the error is. Hence, here is my code in hope of some advice. Thanks in advance.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstnum = (EditText) findViewById(R.id.numberinput);
TextView resultTextView = (TextView) findViewById(R.id.resulttextview);
int num1 = Integer.parseInt(firstnum.getText().toString()) ;
int result = num1 * num1;
resultTextView.setText(result + "");
}
});
}
}
LogCat after fixing the render problem :
7-16 01:27:14.359 10870-10870/com.example.abarimess.myfirstapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abarimess.myfirstapp, PID: 10870
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abarimess.myfirstapp/com.example.abarimess.myfirstapp.MainActivity}: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x4
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3294)
at android.app.ActivityThread.access$1000(ActivityThread.java:210)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1704)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x4
at android.content.res.TypedArray.getDimensionPixelOffset(TypedArray.java:546)
at android.support.constraint.ConstraintLayout$LayoutParams.<init>(ConstraintLayout.java:2685)
at android.support.constraint.ConstraintLayout.generateLayoutParams(ConstraintLayout.java:1915)
at android.support.constraint.ConstraintLayout.generateLayoutParams(ConstraintLayout.java:476)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:820)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:467)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.abarimess.myfirstapp.MainActivity.onCreate(MainActivity.java:11)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3294) 
at android.app.ActivityThread.access$1000(ActivityThread.java:210) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1704) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6938) 
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:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
And the layout XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="73dp">
<TextView
android:id="#+id/textView3"
android:layout_width="360dp"
android:layout_height="119dp"
android:layout_marginTop="50dp"
android:text="#string/square_of_the_number_is"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textColor="#android:color/holo_purple"
android:textSize="40sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.49"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/numberinput" />
<TextView
android:id="#+id/Resulttextview"
android:layout_width="390dp"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:background="#android:color/holo_red_dark"
android:text="#string/the_result_is"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textColor="#ffffff"
android:textSize="50sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/resulttextview"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginTop="30dp"
android:background="#android:color/darker_gray"
android:text="#string/_0"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textColor="#color/Optional"
android:textSize="40sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.51"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Resulttextview" />
<Button
android:id="#+id/btn"
android:layout_width="370dp"
android:layout_height="80dp"
android:layout_marginTop="50dp"
android:background="?android:attr/colorActivatedHighlight"
android:text="#string/butan"
android:textColor="#android:color/holo_blue_bright"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
<EditText
android:id="#+id/numberinput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="50dp"
android:ems="10"
android:hint="#string/number_in_here"
android:inputType="numberDecimal"
android:singleLine="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/resulttextview" />
</android.support.constraint.ConstraintLayout>
the manifest.Xml as requested in the comments :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abarimess.myfirstapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In your layout xml file, you have two separate TextView which are the following.
<TextView
android:id="#+id/Resulttextview"
android:layout_width="390dp"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:background="#android:color/holo_red_dark"
android:text="#string/the_result_is"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textColor="#ffffff"
android:textSize="50sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/resulttextview"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginTop="30dp"
android:background="#android:color/darker_gray"
android:text="#string/_0"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textColor="#color/Optional"
android:textSize="40sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.51"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Resulttextview" />
Name of both text views are identical except the first one has started with a capital R. You might consider the name of the first TextView to something else like resulttextview1 like the following.
<TextView
android:id="#+id/resulttextview1"
android:layout_width="390dp"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:background="#android:color/holo_red_dark"
android:text="#string/the_result_is"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textColor="#ffffff"
android:textSize="50sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/resulttextview"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginTop="30dp"
android:background="#android:color/darker_gray"
android:text="#string/_0"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textColor="#color/Optional"
android:textSize="40sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.51"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/resulttextview1" />
Please avoid naming layout identifiers with capital letters. Use underscores instead (e.g. result_text_view).
Another potential problem in your code is, if there is nothing entered in your EditText the app will crash again with a NullPointerException as the value which will be returned from firstnum.getText().toString() will have the null value.
In this case, you might consider adding a null checking here.
#Override
public void onClick(View v) {
EditText firstnum = (EditText) findViewById(R.id.numberinput);
TextView resultTextView = (TextView) findViewById(R.id.resulttextview);
// Add a null check here for safety
if(firstnum.getText().toString() == null) return;
int num1 = Integer.parseInt(firstnum.getText().toString()) ;
int result = num1 * num1;
resultTextView.setText(result + "");
}
You will get NumberFormatException in case of entering a string in your EditText other than a number. So you might need to handle that case as well. However, this can be ignored in case of handling only numbers in your EditText.
this Is because you should to instance
EditText firstnum = (EditText) findViewById(R.id.numberinput);
Out of method on click listener.
The layout_editor_absoluteX attribute for the resulttextview in your layout XML is referencing spotShadowAlpha, which is an integer which can't be explicitly converted to a dimension, as it doesn't contain any units.
You should update this value to a dimension. For example:
app:layout_editor_absoluteX="30dp"
Obviously, you'll need to change this example up to fit the rest of your layout.

Categories