简体   繁体   中英

Change screen after successful login? (Android studio)

I've been tasked during my internship to take over someone else's code and work on a project.I am having difficulties trying to navigate to another screen after a successful login.Currently, the code below redirects me back to the original main menu page after a successful login (While a failed login does nothing).

My question is how do I display a toast message saying wrong username/password?

Currently it displays nothing during a failed login.Also, how do I change screens from activity_login.xml to landing_page.xml after a SUCCESSFUL login? What code should I add?

LoginActivity.java :

package com.finchvpn.androidcloudpark;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Objects;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText textUsername;
    private EditText txtPassword;
    private static RestClient restClient = new RestClient();

    private SharedPreferences.Editor sharedPreferencesEditor;

    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        try {
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        } catch (Exception e) {
        }

        textUsername = findViewById(R.id.textUsername);
        txtPassword = findViewById(R.id.textPassword);
        SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", 0);
        sharedPreferencesEditor = sharedPreferences.edit();
        textUsername.setText(sharedPreferences.getString("textUsername", ""));
        txtPassword.setText(sharedPreferences.getString("txtPassword", ""));
    }

    public static RestClient getRestClient() {
        return restClient;
    }

    public void loginButtonClick(View v) {
        if (!textUsername.getText().toString().equals("") && !txtPassword.getText().toString().equals("")) {
            apiPostLogin(Constants.ANDROID_KEY + ":" + textUsername.getText().toString() + ":" + txtPassword.getText().toString());
            sharedPreferencesEditor.putString("textUsername", textUsername.getText().toString());
            sharedPreferencesEditor.putString("txtPassword", txtPassword.getText().toString());
            sharedPreferencesEditor.commit();
        } else {
            Toast.makeText(LoginActivity.this, "NULL", Toast.LENGTH_LONG).show();
        }
    }

    private void apiPostLogin(String data) {
        final ProgressDialog progress = new ProgressDialog(this);
        progress.setTitle("Logging in");
        progress.setMessage("Please wait ...");
        progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
        progress.show();
        Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful() && response.body() != null) {
                    try {
                        String data = response.body().string();
                        JSONObject jsonObject = new JSONObject(data);
                        Constants.uid = Integer.parseInt(jsonObject.getString("id"));
                        Constants.username = jsonObject.getString("username");
                        Constants.email = jsonObject.getString("email");
                        Constants.credit = jsonObject.getString("credit");
                        Constants.qr_code = jsonObject.getString("qr_code");
                        Constants.created_at = jsonObject.getString("created_at");
                        Constants.updated_at = jsonObject.getString("updated_at");
                        Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
                        Intent returnIntent = new Intent();
                        setResult(Activity.RESULT_CANCELED, returnIntent);
                        finish();
                    } catch (IOException | JSONException e) {
                        e.printStackTrace();
                    }
                }
                progress.dismiss();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
                progress.dismiss();
            }
        });
    }
}

First of all, for changing your activity layout you have to change this line of code in the onCreate method:

setContentView(R.layout.activity_login);

Second, to display toast if the login fails, change your apiPostLogin method to:

 private void apiPostLogin(String data) {
    final ProgressDialog progress = new ProgressDialog(this);
    progress.setTitle("Logging in");
    progress.setMessage("Please wait ...");
    progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
    progress.show();
    Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful() && response.body() != null) {
                try {
                    String data = response.body().string();
                    JSONObject jsonObject = new JSONObject(data);
                    Constants.uid = Integer.parseInt(jsonObject.getString("id"));
                    Constants.username = jsonObject.getString("username");
                    Constants.email = jsonObject.getString("email");
                    Constants.credit = jsonObject.getString("credit");
                    Constants.qr_code = jsonObject.getString("qr_code");
                    Constants.created_at = jsonObject.getString("created_at");
                    Constants.updated_at = jsonObject.getString("updated_at");
                    Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
                    Intent returnIntent = new Intent();
                    setResult(Activity.RESULT_CANCELED, returnIntent);
                    finish();
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            } else {
              //
              //
              //This scope runs where the login fails
            }
            progress.dismiss();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
            progress.dismiss();
        }
    });
}

If you are starting this loginactivity using startActivityForResult then handle the response from onActivityResult method in your calling activity.

And

setResult(Activity.RESULT_CANCELED, returnIntent);

this should be

setResult(Activity.RESULT_OK, returnIntent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM