询问用于登录的android教程并使用php和远程数据库注册

时间:2013-03-24 22:30:00

标签: php android mysql

我正在寻找一个登录的例子,并使用php和一个真正有用的远程数据库注册android应用程序。你能帮帮我吗?

1 个答案:

答案 0 :(得分:3)

Mkay ......我想相信你懒惰。可能是我的失眠在我身上耍花招。

从这个假设开始,我将给你一个由LoginActivity和LoginValidator组成的例子。请将它们作为示例使用,并根据您的需求进行调整。虽然它们可以正常工作,但您可能需要在此处进行调整以使其适合您当前的环境。

另外,在我的回答的底部,您会找到一个包含有用链接的列表。


LoginActivity.java

import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.android.yourappname.R;
import com.example.android.yourappname.LoginValidator;
import com.example.android.yourappname.SavedValues; // key value pairs... used for saving the state of the Activity

public class LoginActivity extends Activity {

    public EditText usr;
    public EditText pass;
    final Context context = this;
    private TextView loginButton;
    private Boolean justCreated = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        initLoginButton();

        initEditTexts();

        addSwipeGesture();

        justCreated = true;
    }

    @Override
    public void onPause()
    {
        super.onPause();

        Log.v("Login", "onPause");

        SavedValues.setLoginUser(usr.getText().toString());
        SavedValues.setLoginPassword(pass.getText().toString());

        justCreated = false;
    }   

    @Override
    public void onResume()
    {
        super.onResume();

        Log.v("Login", "onResume");

        if (justCreated == true) //if the user recreated the activity, restore the login values from the previous instance
        {
            usr.setText(SavedValues.getLoginUser(), TextView.BufferType.EDITABLE);
            pass.setText(SavedValues.getLoginPassword(), TextView.BufferType.EDITABLE);

            usr.setSelection(usr.getText().length());
        }
        else //if the user only left the activity clear the login values
        {
            usr.setText("", TextView.BufferType.EDITABLE);
            pass.setText("", TextView.BufferType.EDITABLE);
        }
    }   

    private void initLoginButton()
    {
        loginButton = (TextView) findViewById(R.id.btnLogin);
        loginButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                onLoginClick();
            }
        });

        deactivateLoginButton();//the login button will be activated after the user types something in the user name field
    }

    private void initEditTexts()
    {
        usr = (EditText) findViewById(R.id.usr);
        pass = (EditText) findViewById(R.id.pass);

        //set the focus on the user's editText
        usr.setFocusable(true);
        usr.setFocusableInTouchMode(true);
        usr.requestFocus();

        usr.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            public void afterTextChanged(Editable s) {

                if(usr.length() == 0)
                {
                    deactivateLoginButton();
                }
                else
                {
                    activateLoginButton();
                }
            }
        });

        //set the login values from saved data
        usr.setText(SavedValues.getLoginUser(), TextView.BufferType.EDITABLE);
        pass.setText(SavedValues.getLoginPassword(), TextView.BufferType.EDITABLE);
    }

    private void addSwipeGesture()
    {
        View root = findViewById(android.R.id.content).getRootView();
        root.setOnTouchListener(new OnSwipeTouchListener(){

            public boolean onSwipeLeft() {
                onLoginClick();
                return true;
            }
        });
    }

    private void deactivateLoginButton()
    {
        loginButton.setVisibility(View.INVISIBLE);
        loginButton.setClickable(false);
    }

    private void activateLoginButton()
    {
        if (loginButton.getVisibility() != View.VISIBLE)
        {
            loginButton.setVisibility(View.VISIBLE);
            loginButton.setClickable(true);
        }
    }

    private void onLoginClick()
    {
        // Attempting Login
        // test U + P + MAC
        /*
         * // testing MAC address WifiManager manager = (WifiManager)
         * getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo =
         * manager.getConnectionInfo(); String MACAddress =
         * wifiInfo.getMacAddress();
         */

        String user = usr.getText().toString();
        String password = pass.getText().toString();

        if (!isOnline()) {
            alert("Must be connected to network!");
        } else {

            LoginValidator logval = new LoginValidator();

            Boolean validity = false;
            try {
                validity = (Boolean) logval.execute(user, password).get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (validity) {
                Intent i = new Intent(getApplicationContext(), GMC_MainActivity.class);
                startActivity(i);

            } else {
                alert("Invalid username or password");
            }
        }
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnectedOrConnecting()) 
        {
            return true;
        }
        return false;
    }

    public void alert(String s) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

        // set title
        alertDialogBuilder.setTitle(s);
        alertDialogBuilder.setCancelable(false).setNeutralButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // if this button is clicked, just close the
                // dialog
                // box and do nothing
                dialog.cancel();
            }
        });
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
}



<强> LoginValidator.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import android.os.AsyncTask;

public class LoginValidator extends AsyncTask<String, Void, Boolean> {

    Connection conn = null;

    private String jdbcURL = ""; // URL for your database... IP, port etc.
    private String user = ""; // Username for your DB
    private String passwd = ""; // Password for your DB

    @Override
    protected Boolean doInBackground(String... arg0) {

        String username = arg0[0];
        String password = arg0[1];

        Boolean v = false;
        ResultSet rs = null;
        Statement stmt = null;


        try {
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); // I use an oracle DB addapt this to your own DB
            conn = DriverManager.getConnection(jdbcURL, user, passwd);

            try {
                stmt = conn.createStatement();
                try {
                    rs = stmt
                            .executeQuery("SELECT * FROM ts_v4_res.user_t WHERE user_name='"
                                    + username + "'"  /*+" AND pass_word='" +password+"'"*/);

                    if (rs.next()) {
                        String p=rs.getString("pass_word");
                        if (p==null){
                            if(password.equals(""))
                                v = true;}
                        else
                            if(p.equals(password))
                                v=true;                         
                    }

                } finally {
                    try {
                        rs.close();
                    } catch (Throwable ignore) {
                    }
                }
            } finally {
                try {
                    stmt.close();
                } catch (Throwable ignore) {
                }
            }

        } catch (java.sql.SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (java.lang.ClassCastException e) {
            e.printStackTrace();
        }

        return v;
    }
}



带有示例的实用链接(其中有很多)

Android Login activity with MySQL database connection

Android login activity using mysql database

How to connect login to my android app from a mysql database

Android Login activity with MySQL database connection


希望这能让你开始。

干杯