Android StartActivity won't start a new activity - java

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

Related

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

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

NullPointerException calling getIntent().getStringExtra(...)

First of all I'm very new with coding just trying and also new with the features of Firebase. The problem is that, I'm trying to get specific value from firebase by putting number associated with the value. As I have designed it as my first activity (Buffer2) to put the serial number with EditText and thus pass the value from this activity to next activity (Buffer3). and assigned this intent.getExtra string and then making this as int to put the serial number. But the process getting crash (or stopped as to saying it null).
Is there, another way to get this done? any help will be appreciated.
Here is my code (xml and java) for buffer2 and buffer3
buffer2 xml----------------------------
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Buffer2">
<LinearLayout
android:layout_gravity="center"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/etGo"
android:hint="Go To Page No"
android:inputType="number"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnGo"
android:text="Go"
android:textStyle="bold"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
Buffer2 java---------------------------------------
public class Buffer2 extends AppCompatActivity {
Button BtnGo;
EditText EtGo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buffer2);
BtnGo=findViewById(R.id.btnGo);
EtGo=findViewById(R.id.etGo);
String number = Buffer2.this.EtGo.getText().toString();
BtnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Buffer2.this, Buffer3.class);
intent.putExtra("numberto", number);
startActivity(intent);
}
});
}
}
buffer3 xml-------------------------------
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Buffer3">
<TextView
android:id="#+id/nameTv"
android:textSize="28sp"
android:gravity="center"
android:text="Loading..."
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
<TextView
android:id="#+id/professionTv"
android:textSize="28sp"
android:gravity="center"
android:text="Loading..."
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
</LinearLayout>
Buffer3 java------------------------------
public class Buffer3 extends AppCompatActivity {
TextView Name, Profession;
DatabaseReference reference;
String Number = getIntent().getStringExtra("numberto");
int count = Integer.parseInt(String.valueOf(Number));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buffer3);
Name = findViewById(R.id.nameTv);
Profession = findViewById(R.id.professionTv);
reference=FirebaseDatabase.getInstance().getReference().child("What")
.child(String.valueOf(count));
}
protected void onStart() {
super.onStart();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String type = dataSnapshot.child("type").getValue().toString();
Name.setText(name);
Profession.setText(type);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Logcat------------------------
2020-04-22 18:39:48.939 11231-11231/com.potato.manpower I/Timeline: Timeline: Activity_launch_request time:419024820 intent:Intent { cmp=com.potato.manpower/.Buffer3 (has extras) }
2020-04-22 18:39:48.969 11231-11231/com.potato.manpower D/AndroidRuntime: Shutting down VM
2020-04-22 18:39:48.970 11231-11231/com.potato.manpower E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.potato.manpower, PID: 11231
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.potato.manpower/com.potato.manpower.Buffer3}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2649)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at com.potato.manpower.Buffer3.<init>(Buffer3.java:17)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2639)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:165) 
at android.app.ActivityThread.main(ActivityThread.java:6375) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802) 
2020-04-22 18:39:48.999 11231-11231/com.potato.manpower I/Process: Sending signal. PID: 11231 SIG: 9
Firebase Structure
enter image description here
It looks like getIntent() returns null in this line:
String Number = getIntent().getStringExtra("numberto");
I expect that problem will disappear if you move the initialization of Number into the onCreate method:
public class Buffer3 extends AppCompatActivity {
TextView Name, Profession;
DatabaseReference reference;
String Number;
int count = Integer.parseInt(String.valueOf(Number));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buffer3);
Number = getIntent().getStringExtra("numberto");
Name = findViewById(R.id.nameTv);
Profession = findViewById(R.id.professionTv);
reference=FirebaseDatabase.getInstance().getReference().child("What")
.child(String.valueOf(count));
}
...
A few other notes:
It is idiomatic to have the names of member fields start with lowercase letters, so number instead of Number.
When you get a NullPointerException, follow the advice from this post to learn how to troubleshoot it yourself: What is a NullPointerException, and how do I fix it?

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

Getting value of edittext into object

Hi I'm new to android programming and am running into a frustrating bug. I'm trying to get the value from an edittext and put it into an object. My code will print the value into Log.v but throws a NullPointerException when I try to use mEdit.getText().toString() in my setter method. Here's the code:
Button mButton;
EditText mEdit;
WorkoutTop workoutTop;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
mButton = (Button) findViewById(R.id.addButton);
mEdit = (EditText) findViewById(R.id.addEditText);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("This works: ", mEdit.getText().toString());
workoutTop.setName(mEdit.getText().toString());
Log.v("Never gets here:", workoutTop.getName());
}
}
}
);
}
The xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context="eric.hork.AddWorkout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/addEditText"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/addButton"
android:layout_below="#+id/addEditText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
and the Class I'm trying to use:
package eric.hork.Workout;
import java.util.ArrayList;
/**
* Created by eric on 4/29/15.
*/
public class WorkoutTop {
private String name;
private ArrayList<WorkoutDay> workoutDays;
public String getName(){
return name;
}
public void setName(String workoutName){
name = workoutName;
}
public ArrayList<WorkoutDay> getWorkoutDays(){
return workoutDays;
}
public Boolean addWorkoutDay(WorkoutDay workoutDay){
return workoutDays.add(workoutDay);
}
}
The error occurs in this line:
workoutTop.setName(mEdit.getText().toString());
Here's the log:
04-29 16:22:37.131 20937-20937/eric.hork E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: eric.hork, PID: 20937
java.lang.NullPointerException: Attempt to invoke virtual method 'void eric.hork.Workout.WorkoutTop.setName(java.lang.String)' on a null object reference
at eric.hork.AddWorkout$1.onClick(AddWorkout.java:35)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Thanks for any help!
You have to initialize workoutTop variable.
workoutTop = new WorkoutTop();
Within your onCreate Method you must initialize workoutTop.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
workoutTop = new WorkoutTop(); //add this
mButton = (Button) findViewById(R.id.addButton);
mEdit = (EditText) findViewById(R.id.addEditText);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("This works: ", mEdit.getText().toString());
workoutTop.setName(mEdit.getText().toString());
Log.v("Never gets here:", workoutTop.getName());
}
}
}
);
}

Categories

Resources