Retrofit 2.0 Conditional Logic in onResponse not working - retrofit2

I am trying to make a login logic using post request with retrofit, here is my code
Button btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showProgress(true,"Sedang login... ");
String username = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
apiService.login(new LoginParam(username,password)).enqueue(new Callback<AuthResponse>() {
#Override
public void onResponse(Call<AuthResponse> call, Response<AuthResponse> response) {
if(response.isSuccessful()){
showProgress(false,null);
Editor ed = sp.edit();
ed.putString("token",response.body().getToken());
Boolean login = response.body().getLogin();
Log.d("Login",response.body().getLogin().toString());
ed.putBoolean("login",response.body().getLogin().booleanValue());
ed.putString("username",response.body().getUser().getUsername());
ed.commit();
//startActivity(new Intent(getBaseContext(), MainActivity.class));
if(!login){
TextView infologin = (TextView) findViewById(R.id.loginInfo);
infologin.setText("Username dan password salah, coba lagi");
infologin.setVisibility(View.VISIBLE);
return;
}
else{
Intent i = new Intent(getBaseContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.putExtra("route","afterlogin");
startActivity(i);
finish();
}
}
}
#Override
public void onFailure(Call<AuthResponse> call, Throwable t) {
LoginActivity.this.showProgress(false, null);
Toast.makeText(LoginActivity.this, "Gagal koneksi ke server, periksa jaringan internet anda error: " + t.toString(), Toast.LENGTH_LONG).show();
}
});
}
});
it was working when username and password are correct, but when it was not, it only shows a loading animation, the block that handle if login is false remains inexecuted. what's going wrong?

Related

When they want to log in my app crashes firebase realtime database [duplicate]

This question already has answers here:
Validate username and email crashed and cannot insert to firebase database
(2 answers)
Cannot add data to different nodes in firebase
(2 answers)
Closed 9 months ago.
I am using a real-time database (in firebase) and my error is that when trying to enter the account it gives me an error and the application crashes in the case it indicates that the error is that attached the code and one more image clear
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText et_correo = findViewById(R.id.et_correo);
final EditText et_contrasena = findViewById(R.id.et_contrasena);
final Button btn_ingresar = findViewById(R.id.btn_ingresar);
final TextView btn_registrate = findViewById(R.id.btn_registrate);
btn_ingresar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String correotxt = et_correo.getText().toString();
final String contrasenaTxt = et_contrasena.getText().toString();
if (correotxt.isEmpty() || contrasenaTxt.isEmpty()) {
Toast.makeText(LoginActivity.this, "Favor de introducir sus datos", Toast.LENGTH_SHORT).show();
} else {
databaseReference.child("nombre").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//THIS IS MY ERROR
if (snapshot.hasChild(correotxt)) {
final String getPassword = snapshot.child(correotxt).child("contrasena").getValue(String.class);
if (getPassword.equals(contrasenaTxt)) {
Toast.makeText(LoginActivity.this, "Se ha logueado de manera exitosa!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}else{
Toast.makeText(LoginActivity.this, "Correo o Contraseña incorrectos", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
btn_registrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// open RegistroActivity
startActivity(new Intent(LoginActivity.this, RegistroActivity.class));
}
});
}
}
});}}
IMG. LOGCAT

Fragment cannot be cast to java.util.concurrent.Executor error

I'm attempting to sign in or sign up using fragments, and after a successful sign-in/sign up, the HomeActivity supposed to load. The issue is that when I click the sign-in/sign up button, it returns to the same fragment instead of going to the HomeActivity.class. The app's initialization page is called LoginRegistrationActivity.class where it will call the SignIn fragment. I confirmed that Sign in/Sign Up is working well, but I am unable to navigate to the HomeActivity.class after successful authentication. I'm not sure if there is an issue with the AndroidManifest.xml file.
I got this logcat error after I clicked sign in:
java.lang.ClassCastException: com.fyp.selfzen.fragments.O_LoginRegistration.SignIn cannot be cast to java.util.concurrent.Executor
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn.login(SignIn.java:124)
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn$1.onClick(SignIn.java:87)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
SignIn.java fragment
public class SignIn extends Fragment{
private EditText editText_email, editText_password;
private String email, password;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
LoginRegisrationActivity loginRegistration;
public SignIn(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
}
public static SignIn newInstance(LoginRegisrationActivity loginRegistration) {
SignIn fragment = new SignIn(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_email = view.findViewById(R.id.editText_email_login_activity);
editText_password = view.findViewById(R.id.editText_password_login_activity);
TextView button_login = view.findViewById(R.id.button_login_activity);
TextView textView_signup_login = view.findViewById(R.id.textView_signup_login);
final SmoothCheckBox checkBox = view.findViewById(R.id.checkbox_login_activity);
checkBox.setChecked(false);
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = editText_email.getText().toString();
password = editText_password.getText().toString();
editText_email.clearFocus();
editText_password.clearFocus();
login(email, password);
}
});
textView_signup_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignUp f2 = SignUp.newInstance(loginRegistration);
loginRegistration.loadFrag(f2, getResources().getString(R.string.regis));
}
});
return view;
}
public void login(String email, String password) {
editText_email.setError(null);
editText_password.setError(null);
if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if(password.isEmpty()){
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else {
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Successfully sign in!", Toast.LENGTH_LONG).show();
// Intent i = new Intent(loginRegistration, HomeActivity.class); //First try to go to HomeActivity
Intent i = new Intent(getContext(), HomeActivity.class); //Second try
startActivity(i);
//loginRegistration.finish();
} else {
Toast.makeText(getContext(), "Sign in failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
} //onComplete
}); // firebaseAuth
}// else
} // login end
}
SignUp.java fragments
public class SignUp extends Fragment{
private EditText editText_name, editText_email, editText_password, editText_phoneNo;
private String name, email, password, phoneNo;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
LoginRegisrationActivity loginRegistration;
public SignUp(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
// Required empty public constructor
}
public static SignUp newInstance(LoginRegisrationActivity loginRegistration) {
SignUp fragment = new SignUp(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_registration, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_name = view.findViewById(R.id.editText_name_register);
editText_email = view.findViewById(R.id.editText_email_register);
editText_password = view.findViewById(R.id.editText_password_register);
editText_phoneNo = view.findViewById(R.id.editText_phoneNo_register);
TextView button_submit = view.findViewById(R.id.button_submit);
TextView textView_login = view.findViewById(R.id.textView_login_register);
// Go to login page
textView_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignIn f1 = SignIn.newInstance(loginRegistration);
loginRegistration.loadFrag(f1, getResources().getString(R.string.login));
}
});
button_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = editText_name.getText().toString();
email = editText_email.getText().toString();
password = editText_password.getText().toString();
phoneNo = editText_phoneNo.getText().toString();
form();
}
});
return view;
}
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void form() {
editText_name.setError(null);
editText_email.setError(null);
editText_password.setError(null);
editText_phoneNo.setError(null);
if (name.equals("") || name.isEmpty()) {
editText_name.requestFocus();
editText_name.setError(getResources().getString(R.string.please_enter_name));
}
else if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if (password.equals("") || password.isEmpty()) {
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else if (phoneNo.equals("") || phoneNo.isEmpty()) {
editText_phoneNo.requestFocus();
editText_phoneNo.setError(getResources().getString(R.string.please_enter_phone));
}
else {
editText_name.clearFocus();
editText_email.clearFocus();
editText_password.clearFocus();
editText_phoneNo.clearFocus();
}
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getContext(), "Successfully registered!", Toast.LENGTH_LONG).show();
//Intent i = new Intent(loginRegistration, HomeActivity.class);
Intent i = new Intent(getActivity(), HomeActivity.class);
startActivity(i);
//loginRegistration.finish();
}
else{
Toast.makeText(getContext(), "Sign up failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
} // end of form
}
LoginRegistrationActivity.class
public class LoginRegisrationActivity extends AppCompatActivity {
private String curent;
VideoView vide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_regisration);
vide = findViewById(R.id.vide);
String video_url = "android.resource://" + getPackageName() + "/" + R.raw.login_video;
Uri videoUri = Uri.parse(video_url);
vide.setVideoURI(videoUri);
vide.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
vide.requestFocus();
vide.start();
}
});
SignIn f1 = SignIn.newInstance(this);
loadFrag(f1, getResources().getString(R.string.login));
}
public void loadFrag(Fragment f1, String name) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(!name.equals(curent)){
curent =name;
ft.replace(R.id.frame_layout, f1, name);
}
ft.commitAllowingStateLoss();
}
}
AndroidManifest.xml
<activity
android:name="com.fyp.selfzen.activities.LoginRegisrationActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.fyp.selfzen.activities.HomeActivity"
android:label="#string/title_activity_home"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Have you solved your problem yet?
I ran into a similar but different issue when trying to use Fragments with FirebaseAuth. All of the documentation I found only referenced using Activities. Changing .addOnCompleteListener to .addOnSuccessListener and adding an .addOnFailureListener made my app work as expected. My app was originally crashing because of the Executor even though it would successfully authenticate users; the success/failure listeners fixed my issue.
My original code (written with help from Firebase Docs):
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener( (java.util.concurrent.Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(getContext(), "Successfully signed in", Toast.LENGTH_SHORT).show();
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
FragmentFactory.startAdminFragment((MainActivity) getActivity());
} else
Toast.makeText( getContext(), "Authentication failed.", Toast.LENGTH_SHORT ).show();
}
});
}
Current/Working code:
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener( new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FragmentFactory.startAdminFragment((MainActivity) getActivity());
}
})
.addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// If sign in fails, display a message to the user.
Log.d(TAG, "signInWithEmail:failure");
Toast.makeText( getContext(), e.getMessage(), Toast.LENGTH_LONG ).show();
}
} );
}
Note:
I only have 1 Activity so I was able to login and continue to my desired Fragment but you should be able to modify my code (FragmentFactory.startAdminFragment((MainActivity) getActivity());) to continue to your HomeActivity.class
This video helped a lot: https://www.youtube.com/watch?v=fPhy1PKR1Wg
I hope this helps.
In SignIn.java and SignUp.java fragment you add addOnCompleteListener() for firebaseAuth. So, pass arguments in it,
Instead of,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {}
To,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(getContext(), new OnCompleteListener<AuthResult>() {}
IF, getContext() not work then try to write getActivity().

Toggle TextToSpeech on and off using a togglebutton?

So i have an app connected to firebase. The app retrieves data(a string) from firebase into a text view and then the TextToSpeech feature reads the text out(not from the textView but it itself retrieves the same data from firebase real-time database). I have used onDataChange() meathod so the texttospeech feature reads the text out as soon as any change in the data occurs on firebase, and not on the click of any button. Now i want to place a toggle button in my app and use it to either turn the tts feature on or off but i cant get it to work. When the toggle button is off, i want the texttospeech feature to stop and when the button state is on, i want the texttospeech feature to turn back on.This is what ive tried:
mtts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
mtts.setLanguage(Locale.US); }else{
Toast.makeText(MainActivity.this, "Couldnt initialize speech function!", Toast.LENGTH_SHORT).show();
}
}
}); mIvToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
reff = FirebaseDatabase.getInstance().getReference().child("Match").child("Screen1");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String tts= dataSnapshot.getValue().toString();
mtts.speak(tts, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else{
mtts.stop();
mtts.shutdown();
}
}
});
TIA !
When you attach a valueEventListener the listener will trigger as long as there is change in the data, even though you checked the toggle to off. So the thing that you should do is to remove the listener when you are done:
Directly under this:
mtts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
mtts.setLanguage(Locale.US);
}else{
Toast.makeText(MainActivity.this, "Couldnt initialize speech function!", Toast.LENGTH_SHORT).show();
}
}
});
Add these:
//the reference
reff=FirebaseDatabase.getInstance().getReference().child("Match").child("Screen1");
//make a listener
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String tts= dataSnapshot.getValue().toString();
mtts.speak(tts, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
//toggle
mIvToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
//add listener
reff.addValueEventListener(listener);
}else{
//remove listener
reff.removeEventListener(listener);
mtts.stop();
mtts.shutdown();
}
}
});

login form validation in android before implementing method login

I need help to filter empty edittext in login activity before trying to call method and execute query in mysql.. I am new in android development and getting really lost.. I followed a tutorial that works well in registration and login but no filtering or validation. Sad to say, I was not able to fully understand the steps on how each function / method are running.. I will appreciate if you can give me a link to a better page for a good tutorial which is not obsolete or have deprecated libraries.. I am using android 1.5.
I've been searching google and threads here but I could not find solution that is understandable by a newbie in android..
Here is the code of my Main.java which handles log in
public class Main extends AppCompatActivity implements View.OnClickListener {
EditText name, password;
String Name, Password;
Context ctx=this;
String NAME=null, PASSWORD=null, EMAIL=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = (EditText) findViewById(R.id.main_name);
password = (EditText) findViewById(R.id.main_password);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void main_register(View v){
startActivity(new Intent(this,Register.class));
}
public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
BackGround b = new BackGround();
b.execute(Name, Password);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.main_login:
break;
}
}
class BackGround extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String name = params[0];
String password = params[1];
String data="";
int tmp;
try {
URL url = new URL("http://10.0.2.2/BirdBreedingManagement/scripts/login.php");
String urlParams = "name="+name+"&password="+password;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
String err=null;
try {
JSONObject root = new JSONObject(s);
JSONObject user_data = root.getJSONObject("user_data");
NAME = user_data.getString("name");
PASSWORD = user_data.getString("password");
EMAIL = user_data.getString("email");
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: "+e.getMessage();
}
Intent i = new Intent(ctx, Home.class);
i.putExtra("name", NAME);
i.putExtra("password", PASSWORD);
i.putExtra("email", EMAIL);
i.putExtra("err", err);
startActivity(i);
}
}
And here is the php script
try{
//$username = "jeel";
//$pssword = "23456";
$username = filter_input(INPUT_POST, 'name');
$pssword = filter_input(INPUT_POST, 'password');
if($username == "" ){
$results = "Invalid Entry";
echo json_encode(array("user_data"=>$results));
}else{
$stmt = $db->prepare('SELECT * '
. 'FROM users1 '
. 'WHERE name = :uname AND password = :password ');
$stmt->bindParam(':uname', $username);
$stmt->bindParam(':password', $pssword);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if($results > 0 ){
$response = array();
echo json_encode(array("user_data"=>$results));
} else{
$results = "No Record Found";
echo json_encode(array("user_data"=>$results));
}
}
}catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
Thanks in advance.
Since you need to check the username and password fields empty or not before running the AsyncTask to get data from php. Modify the main_login(View v) method as below
public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
if(Name==null || Password==null){
// can alert the user that either one of username or the password is empty by
Toast.makeText(getActivity(), "Username or the Password is empty",Toast.LENGTH_LONG).show();
// in here you can restart the current activity
startActivity(this,Main.class);
finish(); // to destroy the current activity
}
else{
BackGround b = new BackGround();
b.execute(Name, Password);
}
}
The answer of Kasun Siyambalapitiya lead me to make the code perform as expected with some adjustment made.. I am posting it here to share to others who's also looking for a code which they can try if the answer of Kasun didn't fit in their requirement..
`public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
if(name.getText().length()==0){
Toast.makeText(getApplicationContext(),
"Please Enter your name", Toast.LENGTH_LONG).show();
Intent intent = getIntent();
startActivity(intent);
}else{
Intent intent = getIntent();
startActivity(intent);
BackGround b = new BackGround();
b.execute(Name, Password);
}
}`
I remove the finish command to avoid the application from closing and reopening.

my register info will not store in parse

I keep getting an error message when trying to register my users in parse. I also have it set up for email verification too. I can't tell if i doing wrong in my code, looks like i followed parse to the "T".
public class Register extends AppCompatActivity {
protected EditText mUsername;
protected EditText mEmail;
protected EditText mPassword;
protected EditText mPhone;
protected EditText mDob;
protected Button mRegisterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mUsername=(EditText)findViewById(R.id.username);
mEmail=(EditText)findViewById(R.id.email);
mPassword=(EditText)findViewById(R.id.password);
mPhone=(EditText)findViewById(R.id.phonenumber);
mDob=(EditText)findViewById(R.id.birthday);
mRegisterButton=(Button)findViewById(R.id.registerbutton);
//listen to register button click
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get info covert to string
String username = mUsername.getText().toString().trim();
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String phonenumber= mPhone.getText().toString().trim();
String birthday = mDob.getText().toString().trim();
//store to parse
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.put(phonenumber, "650-253-0000");
user.put(birthday,"00-00-000");
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
//user signed up succesfully
Toast.makeText(Register.this, "Welcome To The Party...", Toast.LENGTH_LONG).show();
//take user to home page
} else {
Toast.makeText(Register.this, "Error Try Again...", Toast.LENGTH_LONG).show();
//there was an error siging up
}
}
});
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}

Resources