【发布时间】:2015-02-26 04:57:05
【问题描述】:
我想将数据从 Java Android 发送到 mysql php 服务器。
这是我的按钮点击代码:
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
String result="";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://geospy.zz.mu/default.php");
try {
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", username));
nameValuePairs.add(new BasicNameValuePair("PassWord", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line;
InputStream instream = entity.getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
while ((line = bf.readLine()) != null ) {
sb.append(line).append("\n");
}
result = sb.toString();
Log.i("Read from server", result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
status.setText(username);
//Intent intent = new Intent(LoginActivity.this, PembukaActivity.class);
//startActivity(intent);
}
这是我在 login.php 中的代码:
<?php
include("connect.php");
//define $myusername and $mypassword
$myusername = $_POST['UserName'];
$mypassword = $_POST['PassWord'];
//to protect mysql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$mypassword = $mypassword;
$sql = "SELECT ID_MEMBER FROM MEMBER WHERE USERNAME='".$myusername."' and PASSWORD= '".$mypassword."'";
echo $sql;
$result = mysql_query($sql);
//mysql_num_row is counting table row
$count = mysql_num_rows($result);
echo "<script> alert('".$count."')</script>";
if($count == 1)
{
session_start();
$row = mysql_fetch_array($result);
//$_SESSION['login'] = $myusername;
$_SESSION['id_member'] = $row['id_member'];
header('Location: login.php');
}
else
{
header('Location: default.php');
}
?>
我在清单中添加了这个权限:
<uses-permission android:name="android.permission.INTERNET" />
但应用程序在我运行后停止了。不知道哪里出错了。
【问题讨论】:
-
您是否尝试在 php 的第一行调用 session_start() 来进行测试?
-
你是在后台线程做网络,如果你在 UI 线程上做网络会崩溃?
-
确保您使用的是
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> -
@scraaappy 不,我没叫它
-
@JRowan 我在活动课上做。如何在后台线程中进行?
标签: java php android mysql send