如何根据用户角色打开 Android 个活动?

How to open Android activities based on role of user?

我正在创建一个基于在线的 Android 应用程序,其中有一个 listview,显示来自不同类型的 通知 像“学生”、“教师”这样的用户。当我单击列表视图项时,它应该检查用户的角色,用户是注册为“teacher”还是“student” ' 它应该根据他们的角色打开 activity 屏幕。我将使用意图来打开不同的活动。如何从服务器查看用户的角色?

我会这样做:当用户登录到应用程序时,his/her user_id 将存储在本地存储中,当要加载某些内容时,用户 ID 将在服务器中检查,最好在用户 table 中指定用户是教师还是学生还是...

  1. 首先使用View.generateViewId()为ListView的每个元素定义一个唯一的ID。

  2. 为每个元素定义一个名为onClickListener()的回调函数,并将用户点击的ID传递给它。

  3. 在回调函数中放置一个检查 ID 的 switch 语句。例如: 案例 ID = 1:是学生 case ID = 2: 是老师

  4. 通过 POST 请求将 Id 发送到远程服务器。

  5. 检查 POST 请求中的响应值以查找用户角色。

  6. 通过将角色分配到变量中来应用角色,并将它们传递到下一个 Activity。

像这样:

  public void onClickListView(View view) {
         Intent intent = new Intent(this, RoleActivity.class);
    Bundle b = new Bundle();
    b.putInt("user_role", mRole);
    intent.putExtras(b);
    startActivity(intent);

}

首先,您需要return 登录正确时从服务器获取用户的角色。您还需要将用户详细信息(id、用户名、角色...)存储在 SharedPreferences 等变量中,并在用户注销时将其删除。之后,您只需询问存储在会话 (SharedPreferences) 中的用户详细信息,以了解每个 user/role.

的 show/hide 选项。

这里有一个关于如何使用 SharedPreferences 作为会话的教程:

Android User Session Management using Shared Preferences

假设您的应用程序有一个 MainActivity,用户可以在其中输入用户名和密码然后登录。因此 LoginActivity 已打开。在此代码中,如果用户按下按钮,代码会使用 php 代码检查用户是教师还是学生,然后取回结果并打开另一个 activity.

public class LoginActivity extends AppCompatActivity {

    String json_string ;

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

        Intent intent = getIntent();
        Bundle intentBundle = intent.getExtras();

        //It gets the Username from MainActivity
        final String loggedUser = intentBundle.getString("USERNAME");
        TextView loginUsername = (TextView)findViewById(R.id.login_user);
        loginUsername.setText(loggedUser);

        Button UserAccount = (Button)findViewById(R.id.useraccount);

        //If user push the UserAccount button it calls the doInBackground task
        UserAccount.setOnClickListener(new View.OnClickListener()   {
            public void onClick(View v)  {
                new BackgroundTask(getBaseContext()).execute(loggedUser);
            }
        });
    }
}

public class BackgroundTask extends AsyncTask<String, Void, String> {

    Context context;
    AlertDialog alertDialog;

    public BackgroundTask(Context userContext) {
        this.context = userContext;
    }

    String JSON_STRING;
    String result;

    @Override
    protected void onPreExecute() {
       super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... params) {

        if(android.os.Debug.isDebuggerConnected())
            android.os.Debug.waitForDebugger();

        String json_url = "Your PHP Login URL";
        try {
            String username = params[0];
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);


            OutputStream outputStream = httpURLConnection.getOutputStream();

            // Building the message to the PHP script
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

            //Making the POST URL to send to PHP code and get the result.
            String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");


            // Writing the data
            bufferedWriter.write(post_data);

            // Closing all writing structures
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            // Building the Reading Infrastructure
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));


            // Reading the data
            //StringBuilder stringBuilder = new StringBuilder();
            StringBuilder stringBuilder = new StringBuilder();

            while ((JSON_STRING = bufferedReader.readLine()) != null) {

                stringBuilder.append(JSON_STRING+"\n");

            }

            // Closing all reading structures

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            result = stringBuilder.toString();
            return result;


        } catch (MalformedURLException e) {
            e.printStackTrace();


        } catch (IOException e) {
            Log.e("log_tag", "Error converting result "+e.toString());

        }

        return null;

    }

    @Override
    protected void onProgressUpdate(Void... values) {

        super.onProgressUpdate(values);

    }

    @Override
    protected void onPostExecute(String result) {

        //This is removing the double quotation from string result so we can compare
        json_string = result.replace("\"", "");

        //Trim removes the unwanted spaces from the result.

        if (json_string.trim().contentEquals("student")) {

            // Create your intent.

            Intent sellerIntent = new Intent(LoginActivity.this, StudentAccountActivity.class);
            // Start the Student page activity.
            startActivity(studentIntent);

        } else if (json_string.trim().contentEquals("teacher")){

            // Create your intent.

            Intent buyerIntent = new Intent(LoginActivity.this, TeacherAccountActivity.class);
            // Start the teacher page activity.
            startActivity(teacherIntent);
        }
    }
}

login.php

if($_SERVER['REQUEST_METHOD']=='POST'){

    include_once 'config.php';

    $connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);   
    mysql_select_db(DB_NAME, DB_HOST);        
    $username = $_POST["username"];
    $mysql_qry = "select role from users where username = '$username'";
    $result = mysqli_query($connect, $mysql_qry);

    while ($data =mysqli_fetch_array($result)) {

        $userrole = $data['role'];  

        if ($userrole == "teacher"){
            $therole=json_encode($userrole);
        } else if ($userrole == "student") {
            $therole=json_encode($userrole);
        }    

        echo $therole;
    }

    mysql_close();

}

config.php

define("DB_HOST", "localhost");
define("DB_USER", "Your DB Username");
define("DB_PASSWORD", "Your DB Password");
define("DB_NAME", "Your DB Name");

好吧,我想提供我自己的答案。我居然用了Shared Preferences。它非常简单,可以全局使用我们放入其中的值。下面是代码:

1.创建一个单独的 class 并根据需要命名(我更喜欢这里的 SessionManager)

public class SessionManager {

   // Shared Preferences
   SharedPreferences sharedPrefer;

   // Editor for Shared preferences
   SharedPreferences.Editor editor;

   // Context
   Context context;

   // Shared Pref mode
   int PRIVATE_MODE = 0;

   // Shared Pref file name
   private static final String PREF_NAME = "MySession";

   // SHARED PREF KEYS FOR ALL DATA

   // User's UserId
   public static final String KEY_USERID = "userId";

   // User's categoryId
   public static final String KEY_CATID = "catId";

   // User's categoryType[Teacher, Student, etc.,]
   public static final String KEY_CATTYPE = "categoryType";

   // User's batchId[like class or level or batch]
   public static final String KEY_BATCHID = "batchId";



    // Constructor
    public SessionManager(Context context) {
       this.context = context;
       sharedPrefer = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
       editor = sharedPrefer.edit();
    }

/**
 * Call this method on/after login to store the details in session
 * */

   public void createLoginSession(String userId, String catId, String catTyp, String batchId) {        

       // Storing userId in pref
       editor.putString(KEY_USERID, userId);

       // Storing catId in pref
       editor.putString(KEY_CATID, catId);

       // Storing catType in pref
       editor.putString(KEY_CATTYPE, catTyp);

       // Storing catType in pref
       editor.putString(KEY_BATCHID, batchId);

       // commit changes
       editor.commit();
   }

/**
 * Call this method anywhere in the project to Get the stored session data
 * */
   public HashMap<String, String> getUserDetails() {

       HashMap<String, String> user = new HashMap<String, String>();
       user.put("userId",sharedPrefer.getString(KEY_USERID, null));
       user.put("batchId",sharedPrefer.getString(KEY_BATCHID, null));      
       user.put("catId", sharedPrefer.getString(KEY_CATID, null));
       user.put("catType", sharedPrefer.getString(KEY_CATTYPE, null));

       return user;
   }
}

2。在项目中的一些其他 classes 上调用上述方法:

在会话中存储数据

SessionManager session = new SessionManager(getApplicationContext());
session.createLoginSession(userId, categoryId, categoryType, batchId);

正在从会话中检索数据

SessionManager session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String userId = user.get("userId").toString();
String categoryId = user.get("catId").toString();
String categoryType = user.get("catType").toString();
String batchId= user.get("batchId").toString();