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

时间:2015-07-18 09:12:35

标签: android android-activity server listviewitem role

我正在创建一个基于在线的Android应用,其中有一个 listview ,它显示来自不同类型用户的通知,例如&#39; 学生< / strong>&#39;,&#39; 老师&#39;。当我点击列表视图项时,它应该检查用户的角色,用户是否注册为&#39; 教师&#39;或者学生&#39;它应该根据自己的角色打开活动屏幕。我将使用意图打开不同的活动。如何从服务器检查用户的角色?

5 个答案:

答案 0 :(得分:4)

好吧,我想提供自己的答案。我实际上使用了class ProjectCreate(CreateView): model = project fields = ['project_name'] template_name = 'project_form.html' 。它非常简单,可以在全球范围内使用我们放入的值。以下是代码:

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

Shared Preferences

<强> 2。在项目内的其他一些类上调用上述方法:

在会话中存储数据

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

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

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

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

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

  7. 像这样:

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

答案 3 :(得分:0)

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

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

Android User Session Management using Shared Preferences

答案 4 :(得分:0)

考虑您的应用具有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");