Having trouble getting EditText field with onClick function - java

I am building a client application on android, and I have a problem getting my input in EditText objects. I am having the error message : android.text.Editable android.widget.EditText.getText()' on a null object reference
package com.example.tom.friendlyhousingandroid;
import android.os.Debug;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class register extends AppCompatActivity {
public EditText passwordText;
public EditText emailText;
public EditText firstnameText;
public EditText lastnameText;
public String password,email,lastname,firstname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
passwordText = findViewById(R.id.password);
emailText = findViewById(R.id.email);
firstnameText = findViewById(R.id.firstnameregister);
lastnameText = findViewById(R.id.lastnameregister);
}
public void Registration(View view){
password = passwordText.getText().toString();
email = emailText.getText().toString();
firstname = firstnameText.getText().toString();
lastname = lastnameText.getText().toString();
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://172.16.10.92:8080/school/rest/users/addUser";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response",response);
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("password", "fdgfr"); //Add the data you'd like to send to the server.
MyData.put("email", "fdgfr");
MyData.put("first_name", "fdgfr");
MyData.put("last_name", "fdgfr");
/*Log.d("password",password);
Log.d("firstname",firstname);
Log.d("lastname",lastname);
Log.d("email",email);*/
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
}
and the XML FILE :
<?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=".register">
<EditText
android:id="#+id/emailregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:ems="10"
android:hint="email address"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/lastnameregister" />
<EditText
android:id="#+id/passwordregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="password"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/emailregister" />
<EditText
android:id="#+id/lastnameregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="43dp"
android:ems="10"
android:hint="last name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firstnameregister" />
<EditText
android:id="#+id/firstnameregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="first name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/launchregistration"
android:layout_width="206dp"
android:layout_height="wrap_content"
android:layout_marginBottom="95dp"
android:layout_marginTop="96dp"
android:text="Register"
android:onClick="Registration"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/passwordregister" />
</android.support.constraint.ConstraintLayout>
Obviously I am missing something here. I think the initialisation is not done well and the objects are not initialised in the onCreate() method.

Your layout says
android:id="#+id/emailregister"
but your code says:
emailText = findViewById(R.id.email);
I'm betting you want to be using R.id.emailregister instead.

Id used for email and password into java code and in XML are different. Those must be same. So rewrite your java code for finding views as
passwordText = findViewById(R.id.passwordregister);
emailText = findViewById(R.id.emailregister);

Related

EditText not focusing, and not showing keyboard after keyboard is hidden after one input

I am implementing an OTP Verification system and have 3 EditText fields in my layout, and one of them is hidden until the user clicks a button.
Here is the layout file:
registration_acivity_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=".RegistrationActivity">
<ImageView
/>
<TextView
/>
<TextView
/>
<TextView
/>
<EditText
android:id="#+id/mobile"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_below="#+id/regText"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:clickable="true"
android:focusable="true"
android:hint="Enter Mobile Number"
android:inputType="phone"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/regText" />
<EditText
android:id="#+id/pin_code"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_below="#+id/mobile"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:autofillHints="Enter Area Pin Code"
android:clickable="true"
android:focusable="true"
android:hint="Enter Area Pin Code"
android:inputType="number"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mobile" />
<TextView
android:id="#+id/verify_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pin_code"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Verify mobile number with OTP"
android:textAlignment="center"
android:textColor="#696969"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pin_code" />
<Button
android:id="#+id/get_otp_button"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/verify_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:alpha="1"
android:backgroundTint="#00FA9A"
android:text="Get OTP"
android:textAlignment="center"
android:textColor="#696969"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/verify_text" />
<EditText
android:id="#+id/gen_otp"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_below="#+id/verify_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:alpha="0"
android:clickable="true"
android:focusable="true"
android:hint="Enter OTP"
android:inputType="number"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/verify_text" />
<Button
android:id="#+id/verify_otp_button"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/get_otp_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:alpha="0"
android:backgroundTint="#00FA9A"
android:text="Verify OTP"
android:textAlignment="center"
android:textColor="#696969"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/gen_otp" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem I am having is that when the third otp EditText is shown it doesn't show the virtual keyboard or gets focused when clicked. Instead I have to first click one of the previous two EditTexts for it to show the virtual keyboard.
What can I do to make the virtual keyboard show on clicking the OTP field at once?
Here is the java file.
RegistrationActivity.java:
package com.example.covislot;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.FirebaseException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class RegistrationActivity extends AppCompatActivity {
EditText mobileField, pinField,otpField;
Button getOTP, verifyOTP;
String mobileNumber, pinCode, OTP;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback;
FirebaseAuth auth;
private String verificationCode;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_activity);
sp = getSharedPreferences("login",MODE_PRIVATE);
StartFirebaseLogin();
mobileField = findViewById(R.id.mobile);
pinField = findViewById(R.id.pin_code);
otpField = findViewById(R.id.gen_otp);
getOTP = findViewById(R.id.get_otp_button);
verifyOTP = findViewById(R.id.verify_otp_button);
getOTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (TextUtils.isEmpty(mobileField.getText().toString())) {
// when mobile number field is empty
// displaying a toast message.
Toast.makeText(RegistrationActivity.this, "Please enter a valid phone number.", Toast.LENGTH_SHORT).show();
} else {
mobileNumber = "+91" + mobileField.getText().toString();
}
if (TextUtils.isEmpty(pinField.getText().toString())) {
// when pin number field is empty
// displaying a toast message.
Toast.makeText(RegistrationActivity.this, "Please enter a valid Pin code.", Toast.LENGTH_SHORT).show();
} else {
pinCode = pinField.getText().toString();
}
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(mobileNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(RegistrationActivity.this) // Activity (for callback binding)
.setCallbacks(mCallback) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
});
verifyOTP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(otpField.getText().toString())) {
// when otp field is empty
// displaying a toast message.
Toast.makeText(RegistrationActivity.this, "Please enter a valid OTP.", Toast.LENGTH_SHORT).show();
} else {
OTP = otpField.getText().toString();
}
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCode, OTP);
SigninWithPhone(credential);
}
});
}
private void SigninWithPhone(PhoneAuthCredential credential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sp.edit().putBoolean("logged", true).apply();
sp.edit().putString("phone", mobileNumber).apply();
sp.edit().putString("pinCode", pinCode).apply();
startActivity(new Intent(RegistrationActivity.this,SignedInActivity.class));
finish();
} else {
Toast.makeText(RegistrationActivity.this,"Incorrect OTP",Toast.LENGTH_SHORT).show();
}
}
});
}
private void StartFirebaseLogin() {
auth = FirebaseAuth.getInstance();
mCallback = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Toast.makeText(RegistrationActivity.this,"verification completed",Toast.LENGTH_SHORT).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(RegistrationActivity.this,"verification failed",Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCode = s;
Toast.makeText(RegistrationActivity.this,"Code sent",Toast.LENGTH_SHORT).show();
getOTP.animate().alpha(0f).setDuration(500);
otpField.setVisibility(View.VISIBLE);
otpField.animate().alpha(1f).setDuration(500);
verifyOTP.setVisibility(View.VISIBLE);
verifyOTP.animate().alpha(1f).setDuration(600);
}
};
}
}
Put this line when you want to give it focus:
otpField.requestFocus();
Also, to show the soft keyboard explicitly, you can do like below:
otpField.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager im = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(otpField, InputMethodManager.SHOW_IMPLICIT);
}
},200);

Text view is disappearing in android studio

my textview in activity configure disappears after setting it
the small text 192.168.0, is the text view appears only when i hit the save button
the textview is disappearing completely when i come back to this activity
edit: added my java code and my xml
package com.example.smartcharge;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class configure extends AppCompatActivity {
EditText ip, port;
public TextView tv;
Button SAVEBTN;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String IPSTR = "ipKey";
public static final String PORTSTR = "portKey";
public static final String TEXT1 = "textkey";
private String text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
ip = findViewById(R.id.et1);
port = findViewById(R.id.et2);
SAVEBTN = findViewById(R.id.savebtn);
tv = findViewById(R.id.tv2);
SAVEBTN.setOnClickListener(v -> {
senddata();
});
loaddata();
updateviews();
}
public void senddata(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(configure.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
String ipstr = ip.getText().toString();
String portstr = port.getText().toString();
tv.setText(ipstr + "," + portstr);
editor.putString(IPSTR, ipstr);
editor.putString(PORTSTR, portstr);
editor.putString(TEXT1, tv.getText().toString());
editor.apply();
Toast.makeText(configure.this,"saved",Toast.LENGTH_LONG).show();
}
public void loaddata(){
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
text1 = sharedPreferences.getString(TEXT1 , "");
}
public void updateviews(){
tv.setText(text1);
}
}
Below is xml code of my configure activity
<?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=".configure">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Broker Settings"
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.361"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.038" />
<TextView
android:id="#+id/tv2"
android:layout_width="327dp"
android:layout_height="49dp"
android:text="TextView"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.309"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.247" />
<Button
android:id="#+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btns"
android:text="save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.08"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.572" />
<EditText
android:id="#+id/et2"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:backgroundTint="#D1D1D1"
android:hint="port "
android:inputType="number"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.096"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.444">
</EditText>
<EditText
android:id="#+id/et1"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:backgroundTint="#D1D1D1"
android:hint="ip Address"
android:inputType="number"
android:text="192.168.0."
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.163"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.339">
</EditText>
</androidx.constraintlayout.widget.ConstraintLayout>
any one have any clue of this behavior?, please help me if you can :)
The text disappears since the updating of your TextView takes place in onCreate.
#Override
protected void onResume() {
SAVEBTN.setOnClickListener(v -> {
senddata();
});
loaddata();
updateviews();
}
This should do the trick.
Go through the Activity lifecycle to see how this works. But basically moving methods to onResume should work.

Android Studio - Database fetch to Textview not displaying correctly

I'm trying to display read from table in database, what i have written so far passes the json, however rather than showing in textview - it displays as a short popup, and then disappears.
Activity_tasks.java
package com.example.myapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class activity_tasks extends AppCompatActivity {
TextView TextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
Button button = findViewById(R.id.button1);
button.setOnClickListener(v -> showInfo());
TextView = findViewById(R.id.textView4);
downloadJSON();
}
private void downloadJSON() {
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
setTextView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://myurl.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void setTextView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] tasks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
tasks[i] = obj.getString("Task_title") + " " + obj.getString("task_description");
}
}
private void showInfo() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
builder.setIcon(R.drawable.alert);
builder.setTitle(" ");
builder.setMessage("Lockdown sucks, we know.\nThat's why we created W2D.\n\nOver the comings weeks/months, we'll be adding some cool stuff here. So bear with...\n\nStay Home\nProtect the NHS\nSave Lives");
// Create and show the AlertDialog
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
I have a funny feeling this is something about me having a button requesting a pop-up too in the code, perhaps I haven't integrated the 2nd onCreate properly?
The above is linked to a textview on activity_tasks.xml
Example on phone:
activity.xml below:
<?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"
android:background="#color/black"
android:clickable="true"
tools:context=".MainActivity"
tools:ignore="ExtraText"
android:focusable="true">
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="95dp"
android:layout_height="90dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.946"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022"
app:srcCompat="#drawable/shortlogo"
tools:ignore="ContentDescription" />
<Button
android:id="#+id/button"
android:layout_width="158dp"
android:layout_height="153dp"
android:background="#drawable/circlebutton"
android:text="#string/hit_me_again"
android:textColor="#000"
android:textSize="8sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.896" />
<Button
android:id="#+id/button1"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/alert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.077"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<TextView
android:id="#+id/textView4"
android:layout_width="183dp"
android:layout_height="119dp"
android:textColor="#color/white"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/design"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.092"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/version_0_0_1"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.963"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
What you are seeing at the bottom is the toast you create in onPostExecute(). You receive the data, but then never update the text of the TextView. In setTextView() you could also do that:
textView.setText(json);
On another note: Don't use AsyncTasks anymore. They are deprecated and way too laborious. Also, to read the Json much more easily, you can use a library like Gson or Moshi.

App keeps crashing every time i click the Log in Button

I am new to android, i was following some tutorial and at this point, app keeps crashing when i click the login button.
When i run the app and click the login button, the app crashes and in the logcat, it shows this error of java RuntimeException.
This is my logcat, loginactivity.xml and loginactivity.java.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.ugtunda/com.example.ugtunda.LoginActivity}:
java.lang.ClassCastException:
androidx.appcompat.widget.AppCompatTextView cannot be cast to
com.rey.material.widget.TextView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2806)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2884)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1614)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6524)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:451)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to
com.rey.material.widget.TextView
at com.example.ugtunda.LoginActivity.onCreate(LoginActivity.java:48)
at android.app.Activity.performCreate(Activity.java:7044)
at android.app.Activity.performCreate(Activity.java:7035)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2759)
Here is my login_activity_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"
android:background="#drawable/login"
tools:context=".LoginActivity">
<ImageView
android:id="#+id/login_applogo"
android:layout_width="300dp"
android:layout_height="100dp"
android:src="#drawable/applogo"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
/>
<EditText
android:id="#+id/login_phone_number_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_applogo"
android:background="#drawable/input_design"
android:padding="20dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:hint="Phone Number"
android:inputType="number"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorPrimaryDark"
android:textSize="17sp"
android:textStyle="bold"
/>
<EditText
android:id="#+id/login_password_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_phone_number_input"
android:background="#drawable/input_design"
android:padding="20dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="6dp"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorPrimaryDark"
android:textSize="17sp"
android:textStyle="bold"
/>
<LinearLayout
android:id="#+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/login_password_input"
android:layout_marginTop="5dp"
>
<com.rey.material.widget.CheckBox
android:id="#+id/remember_me_chkb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/Material.Drawable.CheckBox"
android:text="Remember Me"
android:textColor="#color/colorPrimaryDark"
app:cbd_strokeColor="#color/colorPrimaryDark"
android:gravity="center_vertical"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginLeft="17dp"
/>
<TextView
android:id="#+id/forget_password_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forget Password"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginLeft="80dp"
/>
</LinearLayout>
<Button
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linear_layout_1"
android:layout_marginTop="5dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:background="#drawable/buttons"
android:padding="17dp"
android:text="Login"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp" />
<TextView
android:id="#+id/admin_panel_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/login_button"
android:layout_alignParentEnd="true"
android:layout_marginLeft="80dp"
android:layout_marginEnd="23dp"
android:text="I'm an Admin"
android:textAppearance="#android:style/TextAppearance.Material.Small"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/not_admin_panel_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I'm not an Admin"
android:layout_alignParentStart="true"
android:layout_below="#+id/login_button"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginLeft="80dp"
android:layout_marginEnd="23dp"
android:layout_marginStart="25dp"
android:visibility="invisible"
/>
</RelativeLayout>
And lastly my loginactivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ugtunda.Models.Users;
import com.example.ugtunda.Prevalent.Prevalent;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rey.material.widget.CheckBox;
import com.rey.material.widget.TextView;
import io.paperdb.Paper;
public class LoginActivity extends AppCompatActivity
{
private EditText InputPhoneNumber, InputPassword;
private Button LoginButton;
private ProgressDialog loadingBar;
private TextView AdminLink, NotAdminLink;
private String parentDbName = "Users";
private CheckBox chkBoxRememberMe;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginButton = findViewById(R.id.login_button);
InputPassword = findViewById(R.id.login_password_input);
InputPhoneNumber = findViewById(R.id.login_phone_number_input);
AdminLink = findViewById(R.id.admin_panel_link);
NotAdminLink = findViewById(R.id.not_admin_panel_link);
loadingBar = new ProgressDialog(this);
chkBoxRememberMe = findViewById(R.id.remember_me_chkb);
Paper.init(this);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
LoginUser();
}
});
AdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
LoginButton.setText("Login Admin");
AdminLink.setVisibility(View.INVISIBLE);
NotAdminLink.setVisibility(View.VISIBLE);
parentDbName = "Admins";
}
});
NotAdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
LoginButton.setText("Login");
AdminLink.setVisibility(View.VISIBLE);
NotAdminLink.setVisibility(View.INVISIBLE);
parentDbName = "Users";
}
});
}
private void LoginUser()
{
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
if (TextUtils.isEmpty(phone))
{
Toast.makeText(this, "Please write your phone number...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please write your password...", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Login Account");
loadingBar.setMessage("Please wait, while we are checking the credentials.");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount(phone, password);
}
}
private void AllowAccessToAccount(final String phone, final String password)
{
if(chkBoxRememberMe.isChecked())
{
Paper.book().write(Prevalent.USER_PHONE_KEY, phone);
Paper.book().write(Prevalent.USER_PASSWORD_KEY, password);
}
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.child(parentDbName).child(phone).exists())
{
Users usersData = dataSnapshot.child(parentDbName).child(phone).getValue(Users.class);
if (usersData.getPhone().equals(phone))
{
if (usersData.getPassword().equals(password))
{
if (parentDbName.equals("Admins"))
{
Toast.makeText(LoginActivity.this, "Welcome Admin, you are logged in Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, AdminCategoryActivity.class);
startActivity(intent);
}
else if (parentDbName.equals("Users"))
{
Toast.makeText(LoginActivity.this, "logged in Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Prevalent.currentOnlineUser = usersData;
startActivity(intent);
}
}
else
{
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Password is incorrect.", Toast.LENGTH_SHORT).show();
}
}
}
else
{
Toast.makeText(LoginActivity.this, "Account with this " + phone + " number do not exists.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It looks like you're defining standard Android components in the XML layout, then attempting to inflate them into custom components (the com.rey.material package). Try going into your imports and deleting the com.rey.material lines. Then when your IDE prompts you to import the TextView and Checkbox, make sure you're importing the versions from android.widget, not com.rey.material. Alternatively, you could change your XML file to specify the com.rey.material components if you wanted to be using those instead of the default ones.
You used the wrong import so you need to
replace this import
import com.rey.material.widget.TextView;
with
import android.widget.TextView;
OR
You can use the corresponding view in the XML
Replace
<TextView
android:id="#+id/forget_password_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forget Password"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginLeft="80dp"
/>
with
<com.rey.material.widget.TextView
android:id="#+id/forget_password_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forget Password"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginLeft="80dp" />
in your XML file
Looks like you are using the AppCompat Button in your XML, but using the material button in your java code.
So they need to be the same.
First you need to use the right import for whatever view you're using, if you want to use the AppCompat button then import like this
import android.widget.Button;
If you want to use the Material button, then use this import:
import com.rey.material.widget.Button;
Same thing goes for the TextView.
Hope this helps!
androidx.appcompat.widget.AppCompatTextView cannot be cast to
com.rey.material.widget.TextView
In your xml, you're using the SDK TextView but in your code, you want the com.rey.material.widget one.
--> Change one of these

How to fix "com.android.Volley.TimeoutError" in android while trying to perform a registration activity

I am using wamp server as my localhost and I have an app that I want to capture user's particulars during registration. Notwithstanding, the app runs fine on my mobile phone but when I fill the the editText and click my registration button I get this error "Registration Errorcom.android.Volley.TimeoutError".
I have tried checking for any errors in the logcat but found none. Anyone who is good at Android (Java) programing could kindly help me resolve this. Here is my layout code and the java class code. Thanks in advance
My Layout Code
<?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:orientation="vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="60dp"
android:background="#color/colorPrimaryDark2"
tools:context=".RegisterActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="150dp"
android:contentDescription="#string/todo"
android:src="#drawable/ic_lock_outline_white" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:hint="#string/name"
android:inputType="textPersonName"
android:textColor="#color/ColorText"
tools:targetApi="o" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/constituency"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:hint="#string/county"
android:inputType="textPersonName"
android:textColor="#color/ColorText"
tools:targetApi="o" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:hint="#string/email"
android:inputType="textEmailAddress"
android:textColor="#color/ColorText"
tools:targetApi="o" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:hint="#string/password"
android:inputType="textPassword"
android:textColor="#color/C2olorText"
tools:targetApi="o" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true">
<EditText
android:id="#+id/c_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:hint="#string/confirm_password"
android:inputType="textPassword"
android:textColor="#color/ColorText"
tools:targetApi="o" />
enter code here
</com.google.android.material.textfield.TextInputLayout>
<ProgressBar
android:id="#+id/loading"
android:layout_marginTop="30dp"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btn_regist"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginTop="30dp"
android:text="#string/register"
android:backgroundTint="#color/colorPrimary"
android:textColor="#android:color/white"
tools:targetApi="lollipop" />
The Java class code
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
private EditText name, constituency, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
private static String URL_REGIST = "http://192.168.0.115/kpp/register.php";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
loading = findViewById(R.id.loading);
name = findViewById(R.id.name);
constituency = findViewById(R.id.constituency);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Regist();
}
});
}
private void Regist(){
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String constituency = this.constituency.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Toast.makeText(RegisterActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegisterActivity.this, "Registration Error" + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Registration Error" + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name",name);
params.put("constituency",constituency);
params.put("email",email);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}`enter code here`
}
I expect upon successful registration it toast to notify the user "Registration Successful!"...
In your request set Retry policy:
public static int TIMEOUT_MS=10000 //10 seconds
myRequest.setRetryPolicy(new DefaultRetryPolicy(
TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Here with variable TIMEOUT_MS you can specify timeout in milliseconds.
use retry policy like this
RequestQueue requestQueue = Volley.newRequestQueue(this);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
requestQueue.add(stringRequest);

Categories