Android Studio多级别登录(管理员/用户)实现方案咨询
Got it, let's modify your existing login system to support role-based navigation (admin to AdminActivity, regular user to UserActivity). Here's the step-by-step solution:
Step 1: Update Your Backend (login.php)
First, make sure your backend login.php returns the user's role in the JSON response. Assuming your database has a role column in the users table (values like admin or user), adjust the PHP code to include this field in the success response. For example, your successful response should look like:
{"success":1,"message":"Login successful!","id":"1","username":"admin_user","role":"admin"}
Step 2: Modify the Android Login Activity Code
Here's the updated code with role-based logic added. I've marked new/changed sections with comments for clarity:
package com.zahran.login; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; 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.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.zahran.login.Server; import com.zahran.login.app.AppController; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class Login extends AppCompatActivity { ProgressDialog pDialog; Button btn_register, btn_login; EditText txt_username, txt_password; Intent intent; int success; ConnectivityManager conMgr; private String url = Server.URL + "login.php"; private static final String TAG = 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 = "id"; // NEW: Add constant to handle user role from backend public final static String TAG_ROLE = "role"; String tag_json_obj = "json_obj_req"; SharedPreferences sharedpreferences; Boolean session = false; String id, username, role; // NEW: Add role variable to store user's role public static final String my_shared_preferences = "my_shared_preferences"; public static final String session_status = "session_status"; @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(), "No Internet Connection", Toast.LENGTH_LONG).show(); } } btn_login = (Button) findViewById(R.id.btn_login); btn_register = (Button) findViewById(R.id.btn_register); txt_username = (EditText) findViewById(R.id.txt_username); txt_password = (EditText) findViewById(R.id.txt_password); // Check session: redirect to role-specific Activity if already logged in sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE); session = sharedpreferences.getBoolean(session_status, false); id = sharedpreferences.getString(TAG_ID, null); username = sharedpreferences.getString(TAG_USERNAME, null); role = sharedpreferences.getString(TAG_ROLE, null); // NEW: Retrieve role from session if (session && role != null) { // NEW: Navigate to correct Activity based on stored role intent = role.equals("admin") ? new Intent(Login.this, AdminActivity.class) : new Intent(Login.this, UserActivity.class); intent.putExtra(TAG_ID, id); intent.putExtra(TAG_USERNAME, username); intent.putExtra(TAG_ROLE, role); finish(); startActivity(intent); } btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = txt_username.getText().toString(); String password = txt_password.getText().toString(); 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(), "No Internet Connection", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(getApplicationContext(), "Kolom tidak boleh kosong", Toast.LENGTH_LONG).show(); } } }); btn_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { intent = new Intent(Login.this, Register.class); finish(); startActivity(intent); } }); } private void checkLogin(final String username, final String password) { pDialog = new ProgressDialog(this); pDialog.setCancelable(false); pDialog.setMessage("Logging in ..."); 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); if (success == 1) { String username = jObj.getString(TAG_USERNAME); String id = jObj.getString(TAG_ID); // NEW: Extract role from the JSON response String role = jObj.getString(TAG_ROLE); Log.e("Successfully Login!", jObj.toString()); Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); // Save login session including role SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(session_status, true); editor.putString(TAG_ID, id); editor.putString(TAG_USERNAME, username); editor.putString(TAG_ROLE, role); // NEW: Store role in session editor.commit(); // NEW: Redirect to role-specific Activity intent = role.equals("admin") ? new Intent(Login.this, AdminActivity.class) : new Intent(Login.this, UserActivity.class); intent.putExtra(TAG_ID, id); intent.putExtra(TAG_USERNAME, username); intent.putExtra(TAG_ROLE, role); finish(); startActivity(intent); } else { Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { 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() { Map<String, String> params = new HashMap<String, String>(); params.put("username", username); params.put("password", password); return params; } }; AppController.getInstance().addToRequestQueue(strReq, tag_json_obj); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }
Key Changes Explained
- Role Handling: Added
TAG_ROLEconstant androlevariable to manage user role data from backend and session storage. - Session-Based Redirect: When the app launches, if the user is already logged in, we check their stored role and send them directly to the correct Activity.
- Login Success Logic: After parsing the login response, we save the user's role to SharedPreferences and redirect to either
AdminActivityorUserActivitybased on the role value. - Intent Data: Passed the role along with ID and username to target Activities, so you can use this information in those screens if needed.
Important Notes
- Ensure
AdminActivityandUserActivityexist in your project (create them if they don't). - Verify your backend
login.phpcorrectly returns therolefield in the JSON response for successful logins.
内容的提问来源于stack exchange,提问作者Zahran Diaz
相关产品推荐
相关产品推荐

