我有一个php脚本,它将android应用程序与mysql DB连接起来,但当我运行它时,我会出现错误,我无法理解。
config.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'andro_test');?>
php脚本
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$name = clean($_POST['name']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);
//Input Validations
if($name == '') {
$errmsg_arr[] = 'Login ID missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($cpassword == '') {
$errmsg_arr[] = 'Confirm password missing';
$errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
$errmsg_arr[] = 'Passwords do not match';
$errflag = true;
}
//Check for duplicate login ID
if($login != '') {
$qry = "SELECT * FROM test WHERE name='$name'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
// here I want to show a msg that auto disappear...
$errmsg_arr[] = 'username already in use';
$_SESSION['errmsg'] = 'username already in use';
unset($_SESSION['errmsg']);
$errflag = true;
}
@mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: D:Third YearFYPdawaharabteamsrcandrowebsite");// here I need my php to direct the user to my next android file ".java" under the app. file in my PC
exit();
}
//Create INSERT query
$qry = "INSERT INTO test(name, password) VALUES('$name','".md5($_POST['password'])."')";
$result = @mysql_query($qry);
//Check whether the query was successful or not
if($result) {
// here I want to show a msg that auto disappear...
$errmsg_arr[] = 'succefull registeration';
$_SESSION['errmsg'] = 'succefull registeration';
unset($_SESSION['errmsg']);
$errflag = true;
}else {
echo("registeration failed");
}?>
我的安卓应用程序文件
我的主java文件
package andro.website;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ComminicateWithWebsiteActivity extends Activity
{
TextView txtUserName;
TextView txtPassword;
TextView confpass;
Button btnReg;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initComponents();
}
private void initComponents()
{
txtUserName=(TextView)findViewById(R.id.txtUserName);
txtPassword=(TextView)findViewById(R.id.txtPassword);
confpass= (TextView)findViewById(R.id.confirmpassword);
btnReg=(Button)findViewById(R.id.btnReg);
btnReg.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
String usName=txtUserName.getText().toString();
String pass=txtPassword.getText().toString();
String url="http://10.0.2.2/register-exec.php?name="+usName+"&password="+pass;
Server server=new Server(url, getApplicationContext());
server.run();
}
catch(Exception c)
{
Log.e("Thread Exception", c.getMessage());
}
}
});
}}
服务器文件
package andro.website;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class Server
{
String url;
Context context;
public Server(String url,Context context)
{
this.url=url;
this.context=context;
}
public void run()
{
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
Log.d("request", "done");
HttpResponse response = client.execute(request);
Log.d("respone", "done");
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
Log.d("Buffer", "readed");
String line = "";
while ((line = rd.readLine()) != null)
{
Toast.makeText(context, line, Toast.LENGTH_LONG).show();
Log.d("Toast", line);
}
}
catch(Exception c)
{
Log.e("Exception",c.getMessage());
}
}
}
我的主要文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtUserName"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/txtPassword"
android:layout_width="178dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/btnReg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="reg" />
<EditText
android:id="@+id/confirmpassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
我得到的错误没有出现在我的logcat中,而是出现在安卓虚拟机屏幕
虽然您没有提到错误的确切原因,但在执行时可能是NetworkOnMainThreadException
Server server=new Server(url, getApplicationContext());
server.run();
您应该考虑为网络操作使用AsynchTask
(参见此示例)
代码的快速修复方法是让Server
类扩展Thread
,并调用server.start()
而不是server.run()
编辑:
此外,如果没有正当理由使用ApplicationContext
,您应该使用您的活动上下文,例如
Server server=new Server(url, this);
如果要从服务器类使用Toast
,则必须在UI thread
中通过调用Activity.runOnUiThread