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

时间:2016-02-02 02:29:00

标签: java php android xampp

我已经按照教程进行操作,现在我已经有了一个登录编码,可以检查用户是否存在并检查用户角色(管理员或用户)。

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

Tqvm in advanced。

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 im非常新的android所以任何解释都非常感谢。

1 个答案:

答案 0 :(得分:0)

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

echo $user['role'];

并且只有echo&#34;登录失败&#34;或者只是&#34;失败&#34;。然后,您可以解析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);
}

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