Android: How do I get the string value from inputfield? - java

I'm very new to Android, and I've been stuck on trying to get the value string from a material inputField component for hours.
To summarize, I have a button that clicks and opens up a dialog, and on the dialog there is an inputField and button. The button will read out what the inputField says using TextToSpeech.
I am confident that this is how you get the string from the material component (source: http://charmndroid.blogspot.com/2015/06/how-to-use-textinputlayout-in-android.html)
Everything works except for the string value extraction from inputField. If I only comment that out, everything works. Including the speech method (I tried with a static string and it works).
Could you please help me figure this out?
The error I'm getting:
2020-10-23 01:00:56.610 12012-12012/com.example.mint_anroidapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mint_anroidapp, PID: 31408
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:5979)
at android.view.View.performClick(View.java:7125)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:5974)
at android.view.View.performClick(View.java:7125) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992) 
at android.view.View.performClickInternal(View.java:7102) 
at android.view.View.access$3500(View.java:801) 
at android.view.View$PerformClick.run(View.java:27336) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.EditText com.google.android.material.textfield.TextInputLayout.getEditText()' on a null object reference
at com.example.mint_anroidapp.MainActivity.speak(MainActivity.java:49)
at java.lang.reflect.Method.invoke(Native Method) 
at android.view.View$DeclaredOnClickListener.onClick(View.java:5974) 
at android.view.View.performClick(View.java:7125) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992) 
at android.view.View.performClickInternal(View.java:7102) 
at android.view.View.access$3500(View.java:801) 
at android.view.View$PerformClick.run(View.java:27336) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextToSpeech text_to_speech;
private TextInputLayout one_voice;
Dialog myDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one_voice = (TextInputLayout) findViewById(R.id.command_one_voice);
myDialog = new Dialog(this);
text_to_speech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
text_to_speech.setLanguage(Locale.CANADA);
}
}
});
}
public void speak(View v) {
String to_speak = one_voice.getEditText().getText().toString();
text_to_speech.speak(to_speak, TextToSpeech.QUEUE_FLUSH, null);
}
public void OneShowPopup(View v) {
TextView text_close;
Button btnFollow = (Button) myDialog.findViewById(R.id.one_save_button);
myDialog.setContentView(R.layout.command_one);
text_close =(TextView) myDialog.findViewById(R.id.text_close);
text_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
command_one.xml
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/command_one_voice"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="#string/text">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="#+id/one_play_button"
android:onClick="speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="#string/play"
style="?attr/borderlessButtonStyle" />
MainActivity.xml
<com.google.android.material.button.MaterialButton
android:onClick="OneShowPopup"
android:id="#+id/command_one"
android:layout_width="140dp"
android:layout_height="100dp"
android:padding="5dp"
app:icon="#drawable/checked"
android:textColor="#ffffff"
android:text="Title 1"
android:layout_marginRight="30dp"
app:backgroundTint="#2BC9AF"
app:iconGravity="textStart" />

one_voice = (TextInputLayout) findViewById(R.id.command_one_voice);
You try to find a view in your activity layout (MainActivity.xml), but it is in the dialog layout (command_one.xml). You should do something like this:
one_voice = (TextInputLayout) myDialog.findViewById(R.id.command_one_voice);
But only after you init this dialog.

You need to add id to <com.google.android.material.textfield.TextInputEditText then you can get text from it directly.
Add id to your xml code as below
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/edt_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Then add below lines to activity
private TextInputEditText edtText;
In oncreate add below line
edtText= (TextInputEditText) findViewById(R.id.edt_text);
Edit your method
public void speak(View v) {
String to_speak = edtText.getText().toString();
text_to_speech.speak(to_speak, TextToSpeech.QUEUE_FLUSH, null);
}

Related

My app crashes whenever I open it and I can't figure out the problem

This is what the main screen of my app is supposed to look like I have that down I just have to figure out animations but the problem is I can't get the app to open because it crashes and I can't figure out what is causing my crash I used views for the lines at the top and just a regular android background change in the xml code for the mountain picture wondering if any of that might be the problem here is the xml code:
<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:id="#+id/mountains"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/nz"
tools:context=".MainActivity">
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/baloo_thambi"
android:text="NZ"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/white"
android:textSize="120sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/purple_medium"
android:layout_width="17dp"
android:layout_height="155dp"
android:layout_marginEnd="54dp"
android:background="#drawable/purple_gradient"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/green"
android:layout_width="17dp"
android:layout_height="235dp"
android:layout_marginEnd="13dp"
android:background="#drawable/green_gradient"
app:layout_constraintEnd_toStartOf="#+id/purple_medium"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/orange_long"
android:layout_width="17dp"
android:layout_height="215dp"
android:layout_marginEnd="13dp"
android:background="#drawable/orange_gradient"
app:layout_constraintEnd_toStartOf="#+id/green"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/purple_long"
android:layout_width="17dp"
android:layout_height="265dp"
android:layout_marginEnd="13dp"
android:background="#drawable/purple_gradient"
app:layout_constraintEnd_toStartOf="#+id/orange_long"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/orange_short"
android:layout_width="17dp"
android:layout_height="110dp"
android:layout_marginEnd="13dp"
android:background="#drawable/orange_gradient"
app:layout_constraintEnd_toStartOf="#+id/purple_long"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/purple_short"
android:layout_width="17dp"
android:layout_height="60dp"
android:layout_marginEnd="13dp"
android:background="#drawable/purple_gradient"
app:layout_constraintEnd_toStartOf="#+id/orange_short"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/subText"
android:layout_width="84dp"
android:layout_height="31dp"
android:layout_marginEnd="164dp"
android:layout_marginBottom="66dp"
android:fontFamily="#font/allura"
android:text="Next NZ"
android:textColor="#android:color/darker_gray"
android:textSize="22sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Whenever I try to check out what the problem in the logcat is this is what it tells me:
2022-02-14 12:26:47.614 20077-20077/com.revolution.covidnz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.revolution.covidnz, PID: 20077
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.revolution.covidnz/com.revolution.covidnz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.revolution.covidnz.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Im also going to include the main activity code in case something in my code is making the app crash:
public class MainActivity extends AppCompatActivity {
private final int SPLASH_DISPLAY_LENGTH = 2000;
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_down);
Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_up);
View gSlideDown, gSlideUp;
View pShortSlideDown, pShortSlideUp;
View pMediumSlideDown, pMediumSlideUp;
View pLongSlideDown, pLongSlideUp;
View oShortSlideDown, oShortSlideUp;
View oLongSlideDown, oLongSlideUp;
TextView textView, textView2;
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView2 = findViewById(R.id.subText);
gSlideDown = findViewById(R.id.green);
gSlideUp = findViewById(R.id.green);
pShortSlideDown = findViewById(R.id.purple_short);
pShortSlideUp = findViewById(R.id.purple_short);
pMediumSlideDown = findViewById(R.id.purple_medium);
pMediumSlideUp = findViewById(R.id.purple_medium);
pLongSlideDown = findViewById(R.id.purple_long);
pLongSlideUp = findViewById(R.id.purple_long);
oShortSlideDown = findViewById(R.id.orange_short);
oShortSlideUp = findViewById(R.id.orange_short);
oLongSlideDown = findViewById(R.id.orange_long);
oLongSlideUp = findViewById(R.id.orange_long);
relativeLayout = findViewById(R.id.mountains);
final ViewGroup transitionsContainer = (ViewGroup) findViewById(R.id.transition_position);
final TextView text = (TextView) transitionsContainer.findViewById(R.id.text);
gSlideUp.setOnClickListener(new View.OnClickListener() {
boolean visible;
#Override
public void onClick(View v) {
TransitionManager.beginDelayedTransition(transitionsContainer);
visible = !visible;
text.setVisibility(visible ? View.VISIBLE : View.GONE);
}
});
gSlideUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.START);
TransitionManager.beginDelayedTransition(relativeLayout, slide);
textView.setVisibility(View.VISIBLE);
}
});
gSlideUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.END);
TransitionManager.beginDelayedTransition(relativeLayout, slide);
gSlideDown.setVisibility(View.VISIBLE);
}
});
final android.os.Handler handler = new android.os.Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, Second.class);
startActivity(intent);
overridePendingTransition(R.transition.fade_in,R.transition.fade_out);
}
}, 3000);
}
}
See context can be of anything, so if you want the context of activity then use ActivityName.context, other the context you receive may not be of the activity.
One tip: Please study before making apps directly. A programmer is one who reads the documentation and creates apps.
So as you error states, you are trying to invoke getContext() on views/properties that are still null or have not been even created and that is what is happening here. You are trying to access the views and pass them the context even before they are created.
All the views are created during the onCreate method call and you can use them inside this method or after this method has been executed.
So try passing in the context to the views inside a meaningful method where your views are not null
For ref read the activity lifecycle: https://developer.android.com/guide/components/activities/activity-lifecycle

Android StartActivity won't start a new activity

I have two methods defined inside this class:
RegisterButtonClicked successfully calls an activity, but LoginButtonClicked won't....
The result of running this code is that it prints out "inside LoginButtonClicked2" log message which means the code is running the LoginButtonClicked method but not successfully executing the startActivity inside the method.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void RegisterButtonClicked(View view) {
Log.d("registerButtonClicked", "inside registerButtonClicked");
Button Register = findViewById(R.id.RegisterButton);
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, Register.class));
}
});
}
public void LoginButtonClicked(View view) {
Log.d("LoginButtonClicked", "inside LoginButtonClicked");
Button login = findViewById(R.id.LoginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("LoginButtonClicked", "inside LoginButtonClicked2");
startActivity(new Intent(MainActivity.this, Login2.class));
}
});
}
}
here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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/RegisterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="191dp"
android:layout_marginStart="134dp"
android:layout_marginLeft="134dp"
android:text="Register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="266dp"
android:onClick = "RegisterButtonClicked"/>
<Button
android:id="#+id/LoginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="150dp"
android:layout_marginStart="134dp"
android:layout_marginLeft="134dp"
android:text="Log in"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="200dp"
android:onClick = "LoginButtonClicked"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginStart="107dp"
android:layout_marginLeft="107dp"
android:text="Welcome to Pick Rose!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pickrose3, PID: 8252
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pickrose3/com.pickrose3.Login2}: java.lang.IllegalArgumentException: Given String is empty or null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(com.google.firebase:firebase-auth##19.0.0:202)
at com.pickrose3.Login2.onCreate(Login2.java:60)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
You may change your java code as below (consider it as one of the possible ways to solve this, please!):
public class MainActivity extends AppCompatActivity {
public void RegisterButtonClicked(View RegisterButtonClicked) {
startActivity(new Intent(MainActivity.this, Register.class));
}
public void LoginButtonClicked(View LoginButtonClicked) {
startActivity(new Intent(MainActivity.this, Login2.class));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If your are setting click from xml then dont need to set click listener in code.
public void RegisterButtonClicked(View view) {
Log.d("registerButtonClicked", "inside registerButtonClicked");
startActivity(new Intent(MainActivity.this, Register.class));
}
public void LoginButtonClicked(View view) {
Log.d("LoginButtonClicked", "inside LoginButtonClicked");
startActivity(new Intent(MainActivity.this, Login2.class));
}

When i run my android code the my code gives this error....."java.lang.IllegalStateException: Could not execute method for android:onClick" [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
this is my android code when we run application and it is automatically close when login method is call on the clicking of the button
FATAL EXCEPTION: main Process: soubhagya.hostinger, PID: 25611
java.lang.IllegalStateException: Could not execute method for
android:onClick at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5640)
at android.view.View$PerformClick.run(View.java:22455)
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:6165)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5640) 
at android.view.View$PerformClick.run(View.java:22455) 
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:6165) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.text.Editable android.widget.EditText.getText()' on a
null object reference
at soubhagya.hostinger.Login.logIn(Login.java:51)
at soubhagya.hostinger.Login.radhaJi(Login.java:106)
at java.lang.reflect.Method.invoke(Native Method) 
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5640) 
at android.view.View$PerformClick.run(View.java:22455) 
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:6165) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Here's the Login activity.
public class Login extends AppCompatActivity {
//web url string
public static final String LOGIN_URL="http://abhinavin.000webhostapp.com/userregistration/login.php";
public static final String KEY_EMAIL="email";
public static final String KEY_PASSWORD="password";
public static final String LOGIN_SUCCESS="success";
public static final String SHARED_PREF_NAME="tech";
public static final String EMAIL_SHARED_PREF ="email";
public static final String LOGGEDIN_SHARED_PREF="loggedin";
private EditText editTextEmail;
private EditText editTextPassword;
private Button btn_SignIn;
private boolean loggedIn=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//this is text fields
editTextEmail=findViewById(R.id.email);
editTextPassword=findViewById(R.id.password);
btn_SignIn=findViewById(R.id.btn_signup);
}
//End of onCreate method
this login method is call on the click of button
private void logIn() {
//error is in this line i think.
//get value of email from edit text
final String email = editTextEmail.getText().toString();
//get value of password from edit text
final String password = editTextPassword.getText().toString();
StringRequest stringRequest=new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
//override the onResponse method
#Override
public void onResponse(String response) {
//check condition
if (response.trim().equalsIgnoreCase(LOGIN_SUCCESS)) {
SharedPreferences sharedPreferences = Login.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putBoolean(EMAIL_SHARED_PREF, Boolean.parseBoolean(email));
editor.commit();
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
} else {
Toast.makeText(Login.this, "Invalid password", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
//overridre getParams
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> prams=new HashMap<>();
//put the data in map
prams.put(KEY_EMAIL, email);
prams.put(KEY_PASSWORD,password);
//return prams
return prams;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
End of login method
//overtide the onResume method
#Override
protected void onResume() {
super.onResume();
//get SharedPreferences
SharedPreferences sharedPreferences=getSharedPreferences(SHARED_PREF_NAME,Context.MODE_PRIVATE);
loggedIn=sharedPreferences.getBoolean(LOGGEDIN_SHARED_PREF ,false);
if(loggedIn)
{
//set Intent object
Intent i=new Intent(Login.this, MainActivity.class);
//StartActivity
startActivity(i);
}
}
//this is onclick function
public void btn_Click(View view) {
//call login function
logIn();
}
}
xml code in this code edit text and button are defined
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="soubhagya.hostinger.Login">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editText3" android:hint="Emile"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editText4" android:hint="Password"/>
<Button
android:text="Signin"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/button3"
android:onClick="btn_Click"
/></LinearLayout>
this is my xml code in whis we can design ui of our application
You should change to btn_Click in your xml
from android:onClick="radhaJi"
to android:onClick="btn_Click".
Your button initialize wrong id
btn_SignIn=findViewById(R.id.btn_signup);
should be
btn_SignIn=findViewById(R.id.button3);
You need implement the View.OnClickListener along with your Activity like the following.
public class Login extends AppCompatActivity implements View.OnClickListener {
#Override
public void onClick(View view) {
if(view.getId() == R.id.btn_signup)
logIn();
}
}
And change the layout to look like the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Emile"
android:inputType="textPersonName" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="#+id/btn_signup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Signin" />
</LinearLayout>

Android button not being detected and returning a null in the onCreate when trying to retrieve it [duplicate]

This question already has answers here:
findViewById returns null
(4 answers)
Closed 5 years ago.
I have a button in my XML that I'm retrieving in the onCreate method of the activity's java code. When I go to run the app, though, a null pointer exception is set off.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.android.chargerpoints.LogonActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/email"
android:hint="#string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/password"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sign_in_button"
style="?android:textAppearanceSmall"
android:layout_marginTop="16dp"
android:text="#string/action_sign_in"
android:textStyle="bold"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/register_button"
style="?android:textAppearanceSmall"
android:layout_marginTop="8dp"
android:text="#string/action_register"
android:textStyle="bold"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/forgot_password_button"
style="?android:textAppearanceSmall"
android:layout_marginTop="16dp"
android:text="Forgot Password"
android:textStyle="bold"/>
</LinearLayout>
The button in question is the one with the id "sign_in_button". This is the onCreate method in the java code:
private TextView emailTextView;
private TextView passwordTextView;
private Button signInButton;
private Button registerButton;
private Button forgotPasswordButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
emailTextView = (TextView) findViewById(R.id.email);
passwordTextView = (TextView) findViewById(R.id.password);
signInButton = (Button) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(LogonActivity.this, signIn(),
Toast.LENGTH_LONG).show();
}
});
registerButton = (Button) findViewById(R.id.register_button);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(LogonActivity.this, register(),
Toast.LENGTH_LONG).show();
}
});
forgotPasswordButton = (Button) findViewById(R.id.forgot_password_button);
}
This is the error I'm getting:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.chargerpoints, PID: 7276
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.chargerpoints/com.example.android.chargerpoints.LogonActivity}: 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:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.android.chargerpoints.LogonActivity.onCreate(LogonActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
It would be amazing if someone could help me with this. I am a novice at this stuff and this issue has gotten me stuck and its probably just a small thing I missed. Thanks!
you need to inflate the layout inside the activity/fragment first.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<xml file name>);
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//without this line your activity class doesn't know which xml file you wanna use
setContentView(R.layout.yourlayoutname);
//and only after that you can retrive names
bnt = (Button) findViewById(R.id.btn)'
}

Java lang IllegalStateException

I am new in android. I am trying to make simple login activity but I am getting run time error when I click on Login button. I think I am not getting data correctly.I have check and there is a data in SQLite in corresponding to that PK.
logcat.
FATAL EXCEPTION: main
Process: com.example.champ.remindme, PID: 4043
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:289)
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:5254)
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.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
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:5254) 
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.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference
at com.example.champ.remindme.Login.LogIn(Login.java:45)
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284) 
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:5254) 
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) 
java code.
package com.example.champ.remindme;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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.Toast;
public class Login extends AppCompatActivity {
EditText edtUsername, edtPass;
String Username,Password;
int counter=3;
Button LoginButton;
SQLiteDatabase db;
// TextView txtAttempts;
//private final int interval = 3000;
/*private Runnable runnable = new Runnable(){
public void run() {
LoginButton.setEnabled(true);
}
}; */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginButton= (Button)findViewById(R.id.LoginButton);
edtUsername=(EditText)findViewById(R.id.edtitem);
// Username=edtUsername.getText().toString();
edtPass=(EditText)findViewById(R.id.password);
}
public void LogIn(View v){
if((edtUsername.getText().toString().trim().length()==0)||(edtPass.getText().toString().trim().length()==0))
{
showMessage("Error", "Please enter the empty Text Box");
return;
}
Cursor c=db.rawQuery("SELECT * FROM User WHERE Username='"+ edtUsername.getText()+"'", null);
if(c.moveToFirst())
{
Username=c.getString(1);
Password=c.getString(2);
if (edtUsername.getText().toString().equals(Username) && edtPass.getText().toString().equals(Password)){
Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, Menu.class);
intent.putExtra("Username",Username);
startActivity(intent);
}
else {
Toast.makeText(Login.this, "Login Failed", Toast.LENGTH_LONG).show();
counter--;
}
// txtAttempts.setText("Attempts Left: " + counter);
if (counter == 0) {
LoginButton.setEnabled(false);
// new Timer().schedule((TimerTask) runnable,interval);
}
}
else
{
showMessage("Error", "Invalid Username");
}
/*-----------------------------------------------------------------*/
}
public void Signup(View v) {
Intent intent = new Intent(this, SignUp.class);
startActivity(intent);
}
public void showMessage(String title,String message)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
XML code.
<?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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.champ.remindme.Login"
android:background="#drawable/back">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/remind_me_logo"
android:contentDescription="Logo" />
<EditText
android:id="#+id/edtitem"
android:layout_width="265dp"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="#drawable/username_rounded_edited_text"
android:inputType="text"
android:hint="Username"
android:textAlignment="center"
android:layout_marginTop="37dp"
android:layout_below="#+id/imageView2"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/password"
android:layout_width="265dp"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="#drawable/pass_rounded_edited_text"
android:inputType="text"
android:hint="Password"
android:textAlignment="center"
android:layout_below="#+id/edtitem"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/LoginButton"
android:background="#drawable/blue_botton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/login"
style="#style/ButtonText"
android:onClick="LogIn"
android:layout_below="#+id/password"
android:layout_alignLeft="#+id/password"
android:layout_alignStart="#+id/password"
android:layout_alignRight="#+id/password"
android:layout_alignEnd="#+id/password" />
<Button
android:id="#+id/txtSignup"
android:background="#drawable/blue_botton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Signup"
style="#style/ButtonText"
android:onClick="Signup"
android:layout_below="#+id/LoginButton"
android:layout_alignLeft="#+id/LoginButton"
android:layout_alignStart="#+id/LoginButton" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView3"
android:src="#drawable/fb_loging"
android:layout_alignBottom="#+id/txtSignup"
android:layout_toRightOf="#+id/txtSignup"
android:layout_toEndOf="#+id/txtSignup" />
</RelativeLayout>
You didn't initialize db before using it. Add this to your onCreate()..
SQLiteDatabase db = this.getWritableDatabase();
Nothing to do. Just in your XML file's Button attribute remove
android:onClick
And in your activity type:-
LoginButton.setOnClickListener(new OnClickListener(){
#Override
onClick(){
LogIn();
}
});
I also faced this problem. Yeah, I know that your process is also not wrong. But the truth is I just don't know why that process doesn't work (for me). But when I implement onClick method programmatically then it works like a charm. And I hope you will also get your code working
And also add onCreate method
db = getWritableDatabase();

Categories

Resources