【发布时间】:2018-01-31 09:18:58
【问题描述】:
我正在尝试将我的 android 应用程序与后端 MySQL 连接,并且我使用 php 作为服务器端语言,但问题是我正在从 php 中回显 $res 数组,它无法在 Android onPoseExecute(String res) 中访问。
我在其他应用程序中尝试过相同的代码,它在那里工作得非常好..但是这段代码没有显示正确的响应,也没有在创建 Json 对象时出现错误。
我的用户名是在OnCrate()的android代码中定义的。
这是我的 php 代码:
session_start();
$con = mysqli_connect("localhost", "root", "", "SWR");
//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 $str;
}
$empID = strtoupper(clean($_POST['username']));
$resu = array();
$resu["status"] = true;
$sql3="insert into t_booked_hall values ('','$empID','','','','','','1','','','0','','0','','','','','','','','0','','','0','','')";
$result3 = mysqli_query($con,$sql3);
echo json_encode($resu);
安卓代码:
public class SigninActivity extends AsyncTask<String, Void , String>{
protected void onPreExecute(){}
@Override
protected String doInBackground(String... arg0) {
try{
link="https://haripriyag2362.000webhostapp.com/login_php.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode(username, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
//final context context = this;
@Override
protected void onPostExecute(String result){
try{
JSONObject jObj = new JSONObject(result);
if(jObj.getBoolean("status")) {
Toast.makeText(emp_home.this,"Invalid Succesful..",Toast.LENGTH_SHORT);
}
else{
Toast.makeText(emp_home.this,"Invalid Login ! Try Again",Toast.LENGTH_SHORT);
}
}catch (JSONException ex) {
ex.printStackTrace();
}
}
}
【问题讨论】:
-
尝试在
while循环中删除break;doInBackground方法 -
是的。你现在只读一行。
-
it is not accessed in Android onPoseExecute(String res)..这是什么意思?您本可以告诉我们 String res 包含的内容。 -
JSONObject jObj = new JSONObject(result);你不应该盲目这样做,因为还有一个声明return new String("Exception: " + e.getMessage());。所以首先检查 res 是否以 "Exception:" 开头。 -
谢谢先生,@greenapps 正在删除,在 while 循环中插入解决了问题