How to open Android activities based on role of user?

痞子三分冷 提交于 2019-12-06 09:51:02

Well, I would like to provide my own answer. I actually used Shared Preferences. Its much simple and could globally use the values we put in it. Below is the code:

1. Create a separate class and name it as you wish(I prefer SessionManager here)

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. Calling the above methods on some other classes inside the project:

Storing the data in session

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

Retrieving the data from session

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

I would do it like this: While the user logs into the app, his/her user_id will be stored in the local storage and when some things are to be loaded then the users id will be checked in the server, preferably in the users table specifying whether the user is a teacher or a student or ...

  1. First define a unique ID for each element of ListView by using View.generateViewId().

  2. Define a callback function named onClickListener() for each element and pass the ID which user has clicked to it.

  3. Inside the callback function put a switch statement that checks the IDs. For example: case ID = 1: is student case ID = 2: is teacher

  4. Send the Id to remote server through a POST request.

  5. Examine the response value in the POST request for finding the role of users.

  6. Apply the roles by assigning them into a variable and pass them into your next Activity.

like this:

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

}

At first, you need to return the role of the user from the server when the login is correct. You also need to store the user details (id, username, role...) in some variable like SharedPreferences and remove them when user logout. After that, all you need is to ask for the user details stored in the session (SharedPreferences) to know which options to show/hide for each user/role.

Here is a tutorial of how to use SharedPreferences as session:

Android User Session Management using Shared Preferences

Maryam Kashanaki

Consider your app has a MainActivity which user enters their username and password and then they are logged in. So the LoginActivity is open. In this code, if the user push a button, the code checks either user is a teacher or a student using the php code and gets back the results and opens another 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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!