使用会话的多级登录用户和管理员?

时间:2019-08-13 20:31:55

标签: java android authentication session

我有一个项目,可以在Android Studio中使用多级会话以及具有不同活动的用户登录名和管理员登录名来创建登录应用程序。

例如,如果管理员单击登录按钮,则转到管理员活动。如果用户单击,则转到用户的用户活动。所有这些已经起作用;但是,问题是如果我使用admin登录并通过两次按后退按钮而不注销而关闭应用程序,此后,我尝试重新打开应用程序,但出现的是用户activity(**MainActivity**) not admin activity(**AdminActivity**) ....

您有帮助我的解决方案吗?抱歉,如果我的英语不好/

package com.example.ilvan.gogas;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.ilvan.gogas.app.AppController;
import com.example.ilvan.gogas.util.Server;

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

import java.util.HashMap;
import java.util.Map;


public class Login extends AppCompatActivity {

    ProgressDialog pDialog;
    EditText txtusername, txtpassword;
    Button btnLogin;
    TextView btnRegister;


    int success;
    ConnectivityManager conMgr;

    private String url = Server.URL + "checkLogin.php";

    private static final String TAG = com.example.ilvan.gogas.Login.class.getSimpleName();

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    public final static String TAG_USERNAME = "username";
    public final static String TAG_ID = "user_id";
    public final static String TAG_USERTYPE = "user_type";

    String tag_json_obj = "json_obj_req";
    SharedPreferences sharedpreferences;
    Boolean session = false;
    String user_id, username,user_type;

    public static final String my_shared_preferences = "my_shared_preferences";
    public static final String session_status = "session_status";

    final String MESSAGE_NO_INTERNET_ACCESS = "No Internet Connection";
    final String MESSAGE_CANNOT_BE_EMPTY = "Kolom Tidak Boleh Kosong";
    final String MESSAGE_LOGIN = "Logging in ...";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        {
            if (conMgr.getActiveNetworkInfo() != null
                    && conMgr.getActiveNetworkInfo().isAvailable()
                    && conMgr.getActiveNetworkInfo().isConnected()) {
            } else {
                Toast.makeText(getApplicationContext(), MESSAGE_NO_INTERNET_ACCESS,
                        Toast.LENGTH_LONG).show();
            }
        }

        btnLogin = (Button) findViewById(R.id.btn_login);
        btnRegister = (TextView) findViewById(R.id.lbl_register);
        txtusername = (EditText) findViewById(R.id.txt_username);
        txtpassword = (EditText) findViewById(R.id.txt_password);

        // Cek session login jika TRUE maka langsung buka halaman setelah login
        sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
        session = sharedpreferences.getBoolean(session_status, false);
        user_id = sharedpreferences.getString(TAG_ID, null);
        username = sharedpreferences.getString(TAG_USERNAME, null);
        user_type = sharedpreferences.getString(TAG_USERTYPE, null);

        if (session) {
            Intent intent = new Intent(Login.this, MainActivity.class);
            intent.putExtra(TAG_ID, user_id);
            intent.putExtra(TAG_USERNAME, username);
            finish();
            startActivity(intent);

        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String username = txtusername.getText().toString();
                String password = txtpassword.getText().toString();

                // mengecek kolom yang kosong
                if (username.trim().length() > 0 && password.trim().length() > 0) {
                    if (conMgr.getActiveNetworkInfo() != null
                            && conMgr.getActiveNetworkInfo().isAvailable()
                            && conMgr.getActiveNetworkInfo().isConnected()) {
                        checkLogin(username, password);
                    } else {
                        Toast.makeText(getApplicationContext(), MESSAGE_NO_INTERNET_ACCESS, Toast.LENGTH_LONG).show();
                    }
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(), MESSAGE_CANNOT_BE_EMPTY, Toast.LENGTH_LONG).show();
                }
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent intent = new Intent(Login.this, Register.class);
                Login.this.startActivity(intent);
            }
        });
    }

    private void checkLogin(final String username, final String password) {
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);
        pDialog.setMessage(MESSAGE_LOGIN);
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.e(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    success = jObj.getInt(TAG_SUCCESS);

                    // Check for error node in json
                    if (success == 1) {
                        String username = jObj.getString(TAG_USERNAME);
                        String user_type = jObj.getString(TAG_USERTYPE);
                        String id = jObj.getString(TAG_ID);

                        Log.e("Successfully Login!", jObj.toString());

                        Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

                        // menyimpan login ke session
                        SharedPreferences.Editor editor = sharedpreferences.edit();
                        editor.putBoolean(session_status, true);
                        editor.putString(TAG_ID, id);
                        editor.putString(TAG_USERNAME, username);
                        editor.commit();

                        // Memanggil halaman setelah login
                        if (session && user_type.contentEquals("penjual")) {
                            Intent intent = new Intent(com.example.ilvan.gogas.Login.this, MainActivityPenjual.class);
                            intent.putExtra(TAG_ID, id);
                            intent.putExtra(TAG_USERNAME, username);
                            finish();
                            startActivity(intent);

                        } else {
                            Intent intent = new Intent(Login.this, MainActivity.class);
                            intent.putExtra(TAG_ID, id);
                            intent.putExtra(TAG_USERNAME, username);
                            finish();
                            startActivity(intent);
                        }
                    } else {
                        Toast.makeText(getApplicationContext(),
                                jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                        Log.e("username : ", username);
                        Log.e("password : ",password);
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();

                hideDialog();

            }
        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", username);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}


2 个答案:

答案 0 :(得分:0)

解决方案很简单,只需用您的方法覆盖onBackPressed方法即可注销上一个活动

@Override
    public void onBackPressed() {
            super.onBackPressed();  
            logout();
      }
    }

然后根据需要定义logout()方法。

答案 1 :(得分:0)

关于您的项目,您可以通过多种方式来实现它,并且可以实现多个设计模式,但是要使其变得简单,您可以尝试以下操作...

创建一个充当用户角色管理的屏幕。一个SplashScreen与此很方便。您可以在此处检查用户的类型,它可以帮助您保持关注点的分离。

现在,我们可以看到您只在onCreate方法上签入会话,但没有在user_type上签入。实际上,您需要执行与checkLogin方法的“回调”相同的操作,但是这次验证会话的变量。

        if (session && user_type.contentEquals("admin")) {
        Intent intent = new Intent(com.example.ilvan.gogas.Login.this, AdminActivity.class);
        intent.putExtra(TAG_ID, id);
        intent.putExtra(TAG_USERNAME, username);
        finish();
        startActivity(intent);

    } else {
        Intent intent = new Intent(Login.this, MainActivity.class);
        intent.putExtra(TAG_ID, id);
        intent.putExtra(TAG_USERNAME, username);
        finish();
        startActivity(intent);
    }

因此,无论用户类型如何,您都只能进入MainActivity

希望这对您有所帮助!干杯...欢迎来到stackoverflow!