Android根据保存在xampp中的用户角色定向到新页面

Posted

技术标签:

【中文标题】Android根据保存在xampp中的用户角色定向到新页面【英文标题】:Android directing to new page based on user role saved in xampp 【发布时间】:2016-05-10 16:49:11 【问题描述】:

我遵循了一个教程,现在我得到了一个登录编码,可以检查用户是否存在并检查用户角色(管理员或用户)。

我已经读到要进入新页面,我们需要使用 Intent,但是我如何让它的用户角色传递到 android?其中 admin 将被定向到页面 A,而用户将被定向到页面 B。

Tqvm 进阶。

1.BackgroundWorker.java

public class BackgroundWorker extends AsyncTask<String,Void,String> 
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) 
    context = ctx;

@Override
protected String doInBackground(String... params) 
    String type = params[0];
    String login_url = "http://ipaddress/foldername/login.php";
    if(type.equals("login")) 
        try 
            String user_name = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) 
                result += line;
            
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
         catch (MalformedURLException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        
    
    return null;


@Override
protected void onPreExecute() 
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");


@Override
protected void onPostExecute(String result) 
    alertDialog.setMessage(result);
    alertDialog.show();



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

    super.onProgressUpdate(values);


2.MainActivity.java

public class MainActivity extends AppCompatActivity 

EditText UsernameEt, PasswordEt;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    UsernameEt = (EditText) findViewById(R.id.etUserName);
    PasswordEt = (EditText) findViewById(R.id.etPassword);


public void OnLogin(View view)
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();
    String type = "login";


    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, username, password);



3.login.php

<?php 
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from employee_data where username like '$user_name'  and      password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);


if(mysqli_num_rows($result) > 0)

            while ($data =mysqli_fetch_array($result))
            

                $userrole = $data['role'];  

                if ($userrole == "admin")


                    echo "login admin successful";

                

                else if ($userrole == "user")
                

                    echo "login user successful";
                

            

        
else
echo "login unsuccessful";




?>

p.s 我对 android 非常陌生,因此非常感谢任何解释。

【问题讨论】:

【参考方案1】:

如果登录成功,您可以先在 PHP 脚本中回显角色:

echo $user['role'];

并且只回显“登录失败”或简单地“失败”。然后你可以像这样解析来自onPostExecute() 方法的响应:

switch (result) 
    case "failed":
        // Login failed.
        break;
    case "user": // Login successful, result (role) is "user"
        break;
    case "admin": // Login successful, result (role) is "admin"
        break;

如果您想将此角色传递回您的活动,您可以在AsyncTask 上实现一个侦听器接口,该接口将在调用onPostExecute() 方法时被调用。例如:

public class BackgroundWorker extends AsyncTask<String,Void,String> 
    ... // Member properties.
    // Define the listener interface.
    public interface OnTaskFinishedListener 
        void onTaskFinished(String result);
    

    // Member property to reference listener.
    private OnTaskFinishedListener mOnTaskFinishedListener;

    // Setter for listener.
    public void setOnTaskFinishedListener(OnTaskFinishedListener listener) 
        mOnTaskFinishedListener = listener;
    

    // Invoke the listener in the onPostExecute() method.
    @Override 
    protected void onPostExecute(String result) 
        // Only call it if it's set.
        if (mOnTaskFinishedListener != null) 
            mOnTaskFinishedListener.onTaskFinished(result);
    

然后在你的活动中,OnLogin():

public void OnLogin(View view) 
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();
    String type = "login";


    BackgroundWorker backgroundWorker = new BackgroundWorker(this);

    // Set your listener here.
    backgroundWorker.setOnTaskFinishedListener(new BackgroundWorker.OnTaskFinishedListener() 
        @Override
        public void onTaskFinished(String result) 
            // Now you have the result of your login here.
            // Result should be "admin", "user", or "failed"
            // You can now create an intent and open the page 
            // to your next activity.
            switch (result) 
                case "admin":
                    // Create your intent.
                    Intent adminIntent = new Intent(MainActivity.this, AdminPageActivity.class);

                    // Start the admin page activity.
                    startActivity(adminIntent);
                    break;
                case "user":
                    // Create your intent.
                    Intent userIntent = new Intent(MainActivity.this, UserPageActivity.class);

                    // Start the user page activity.
                    startActivity(userIntent);
                    break;
                default:
                    // Login failed.
            
        
    );

    backgroundWorker.execute(type, username, password);

听者的东西一开始可能很难掌握,但一旦你掌握了,它就会变得非常强大。希望这会有所帮助!

【讨论】:

这确实有很大帮助。我要先学习听众的东西,然后试着理解你的解释。又是 tqvm。 没问题。多线程和侦听器接口齐头并进。一旦后台任务完成,这是一种非常有效的方式来“同步”(我松散地使用该术语)与您的 UI 线程备份。另外,请注意,如果您觉得这个问题对您的问题有所帮助,请考虑将其标记为正确。谢谢,祝你好运。 你好。 tqvm 昨天为您提供帮助。我刚刚发布了一个新问题,希望您能花一些时间。 ***.com/questions/35170144/….

以上是关于Android根据保存在xampp中的用户角色定向到新页面的主要内容,如果未能解决你的问题,请参考以下文章

laravel 5根据用户的角色在登录后重定向用户

根据角色将不同的用户重定向到 Keycloak 登录的不同页面

Visual C# - 根据用户角色将用户重定向到不同的窗体

Symfony 登录表单根据用户角色重定向

php WordPress功能,用于根据用户角色重定向用户登录

从同一登录页面使用其用户角色将用户重定向到仪表板