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

如何根据用户角色打开Android活动?,android,android-activity,server,listviewitem,role,Android,Android Activity,Server,Listviewitem,Role,我正在创建一个基于在线的Android应用程序,其中有一个列表视图,显示来自不同类型用户的通知,如“学生”,“教师””。当我单击列表视图项目时,它应该检查用户的角色,用户是注册为“教师”还是注册为“学生”,并且它应该根据他们的角色打开活动屏幕。我将使用意图来开展不同的活动。如何从服务器检查用户的角色?我会这样做:当用户登录应用程序时,其用户id将存储在本地存储中,当要加载某些内容时,将在服务器中检查用户id,最好在用户表中指定用户是教师还是学生或 首先使用View.generateView()为

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

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

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

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

  • 在回调函数中放入一个switch语句来检查ID。例如: 案例ID=1:是学生吗 案例ID=2:是老师吗

  • 通过POST请求将Id发送到远程服务器

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

  • 通过将角色分配到变量中并将其传递到下一个活动中来应用角色

  • 像这样:

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

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

    以下是如何将SharedReferences用作会话的教程:


    假设您的应用程序有一个主活动,用户输入用户名和密码,然后登录。所以后勤活动是开放的。在这段代码中,如果用户按下一个按钮,代码将检查用户是否是使用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);
            }
        }
    }
    
    config.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();
    
    }
    
    define("DB_HOST", "localhost");
    define("DB_USER", "Your DB Username");
    define("DB_PASSWORD", "Your DB Password");
    define("DB_NAME", "Your DB Name");
    

    嗯,我想提供我自己的答案。我实际上使用了
    共享首选项
    。它非常简单,可以在全球范围内使用我们输入的值。代码如下:

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

    正在从会话检索数据

    SessionManager session=newsessionmanager(getApplicationContext());
    HashMap user=session.getUserDetails();
    字符串userId=user.get(“userId”).toString();
    String categoryId=user.get(“catId”).toString();
    String categoryType=user.get(“catType”).toString();
    字符串batchId=user.get(“batchId”).toString();
    
    目前还没有。。。。。。我开发了一个类似的应用程序,需要同样的东西,所以我采用了类似的方法
    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;
       }
    }
    
    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();