【问题标题】:How to open Android activities based on role of user?如何根据用户角色打开 Android 活动?
【发布时间】:2015-10-07 23:43:59
【问题描述】:

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

【问题讨论】:

    标签: android android-activity server listviewitem role


    【解决方案1】:

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

    1.创建一个单独的类并根据需要命名(我这里更喜欢 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。在项目内的其他一些类上调用上述方法:

    在会话中存储数据

    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();
    

    【讨论】:

      【解决方案2】:

      假设你的应用有一个 MainActivity,用户输入他们的用户名和密码然后他们就登录了。所以 LoginActivity 是打开的。在此代码中,如果用户按下按钮,代码会使用 php 代码检查用户是教师还是学生,然后返回结果并打开另一个活动。

      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");
      

      【讨论】:

        【解决方案3】:

        首先需要在登录正确的情况下从服务器返回用户的角色。您还需要将用户详细信息(id、用户名、角色...)存储在 SharedPreferences 等变量中,并在用户注销时将其删除。之后,您只需询问存储在会话 (SharedPreferences) 中的用户详细信息,以了解为每个用户/角色显示/隐藏哪些选项。

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

        Android User Session Management using Shared Preferences

        【讨论】:

          【解决方案4】:
          1. 首先使用View.generateViewId()为ListView的每个元素定义一个唯一ID。

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

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

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

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

          6. 通过将角色分配到变量中来应用角色并将它们传递给您的下一个活动。

          像这样:

            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);
          
          }
          

          【讨论】:

            【解决方案5】:

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

            【讨论】:

            • 目前还没有......我开发了一个类似的应用程序,需要同样的东西,所以我遵循了类似的方法
            猜你喜欢
            • 2019-09-24
            • 2020-11-14
            • 1970-01-01
            • 2017-08-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多