java - 使用 PHP 和 mysql 构建 Android 登录

标签 java php android mysql authentication

我已经创建了连接到我的 PHP 和 mysql 的 android 登录,问题是,每次我运行我的程序并输入正确的电子邮件和密码时,它总是在我的 EditText 中显示 android.os.NetworkOnMainException ,或者当我正在删除代码,以免发生任何事情。我的编码是否犯了错误,或者我遗漏了什么。好的,这是我的代码。

安卓:

**

public class LoginActivity extends Activity {
/** Called when the activity is first created. */
     EditText inputEmail ;
    EditText inputPassword ;
    Button btnLogin ;
    public void validation()
    {
        if(inputEmail.getText().toString().equals("") || inputPassword.getText().toString().equals(""))
                {
                Toast.makeText( getApplicationContext(),"Fill Empty Fields",Toast.LENGTH_SHORT ).show();
                }
        else
        {
            connectphp();
        }
        }
    public void connectphp()
    {
    // TODO Auto-generated method stub
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("eadd", inputEmail.getText().toString()));
    postParameters.add(new BasicNameValuePair("password", inputPassword.getText().toString()));
    //Passing Parameter to the php web service for authentication
    //String valid = "1";
    String response = null;
    try {
    response = CustomHttpClient.executeHttpPost("http://10.0.2.2:8080/TheCalling/log_in.php", postParameters);  //Enter Your remote PHP,ASP, Servlet file link
    String res=response.toString();
    res = res.trim();
    res= res.replaceAll("\\s+","");
    //error.setText(res);
    if(res.equals("1"))
    {
        Toast.makeText( getApplicationContext(),"Correct Username or Password",Toast.LENGTH_SHORT ).show();
        Intent i = new Intent(LoginActivity.this,MainMenu.class);
        startActivity(i);
    }
        else
            if(res.equals("0"))
        {
        Toast.makeText( getApplicationContext(),"Sorry!! Incorrect Username or Password",Toast.LENGTH_SHORT ).show();
        }
    } catch (Exception e) {
        inputEmail.setText(e.toString());
    }}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
 inputEmail = (EditText)findViewById(R.id.inputEmail);
 inputPassword = (EditText)findViewById(R.id.inputPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{ 
    validation(); 
    //(This is to check empty fields)
}
});
}}

**

顺便说一句,这段代码也来自堆栈溢出。

自定义HttpClient

**

public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
 * Get our single instance of our HttpClient object.
 *
 * @return an HttpClient object with connection parameters set
 */
private static HttpClient getHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
}
/**
 * Performs an HTTP Post request to the specified url with the
 * specified parameters.
 *
 * @param url The web address to post the request to
 * @param postParameters The parameters to send via the request
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
/**
 * Performs an HTTP GET request to the specified url.
 *
 * @param url The web address to post the request to
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
}

**

和我的 PHP 代码。

**

<?php
include("db_config.php");
$eadd=addslashes($_POST['eadd']);
$password=addslashes($_POST['password']);
$sql="SELECT * FROM users WHERE eadd='$eadd' and password='$password'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$count=mysql_num_rows($result);
if($count==1)
    {
    echo "1";
    //(If result found send 1 to android)
    }
else
    {
    echo "0";
    //(If result not found send o to android)
    }
?>

**

感谢大家抽出时间。

最佳答案

在较新版本的 Android 中,默认启用严格模式。基本上,这意味着您无法在 UI 线程上执行网络操作,因为它们会卡住应用程序并使其看起来有问题;因此你会得到NetworkOnMainThreadException

为了避免这种情况,请使用 AsyncTask ,这将允许您在不同的线程上运行下载代码。该文档展示了如何创建子类以及如何运行它(单击按钮时将运行它)。

关于java - 使用 PHP 和 mysql 构建 Android 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554734/

相关文章:

java - spring注释不起作用

java - 如何将php客户端连接到java webservice?

java - 多词搜索栏

java - 以编程方式生成 zip 会创建无效的 zip[android]

android - 按下项目后如何立即关闭抽屉导航?

android - 具有双向数据绑定(bind)的自定义 View

java - 使用 char[] 参数通过 JNI 调用方法

java - Spring 复合 bean ?

java - 单元测试需要很多接口(interface)?

php - 使用 PHP 和页面安全性将记录添加到 MySQL