0

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

4

1 回答 1

3

Mkay... 我喜欢相信你并不懒惰。可能是我的失眠在捉弄我。

从这个假设开始,我将给您一个由 LoginActivity 和 LoginValidator 组成的示例。请使用它们作为示例并根据您的需要进行调整。尽管它们确实有效,但您可能需要在这里和那里进行调整以使其适合您当前的环境。

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


登录活动.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();
    }
}



登录验证器.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;
    }
}



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

使用 MySQL 数据库连接的 Android 登录活动

使用 mysql 数据库的 Android 登录活动

如何从 mysql 数据库连接登录到我的 android 应用程序

使用 MySQL 数据库连接的 Android 登录活动


希望这会让你开始。

干杯

于 2013-03-24T23:40:34.610 回答