使用Volley向数据库发送数据失败


Fail to send data to database using Volley

我的应用程序通过 getStringExtra mapActivity 接收到地区名称,然后与从当前活动中获得的字符串 General_Info 一起需要发送到在线数据库。

PHP代码中没有错误。

我使用wi-fi和数据测试了应用程序,但不幸的是,它总是返回"失败"。

我不知道我的代码出了什么问题

附上我的代码

StringRequest request=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.contains("SUCCESS")){
                Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), "system error", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> param=new HashMap<String, String>();
            param.put("householdid",houseNo.getText().toString());
            param.put("region", region);
            param.put("totalmembers", totalMembers.getText().toString());
            param.put("totalfemale", totalFemale.getText().toString());
            param.put("totalmale", totalMale.getText().toString());
            return param;
        }
    };
    MySingleton.getInstance(General_Info.this).addToRequestQueue(request);
}
php代码:

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
    include_once("connect.php");
    $householdId = $_POST['householdid'];
    $region = $_POST['region'];
    $totalMembers = $_POST['totalmembers'];
    $totalFemale = $_POST['totalfemale'];
    $totalMale = $_POST['totalmale'];
    $result = mysqli_query($con,"INSERT INTO households (householdId,region,totalMembers,totalFemale,totalMale) 
      VALUES ('$householdId',' $region','$totalMembers','$totalFemale',' $totalMale')");
    if($result == true) {
        echo "SUCCESS";
    }
    else{
        echo "FAILURE ";
    }
}
mysqli_close($con);

如果我是你,我会这样修改代码。首先,我使用medoo作为我的数据库框架,它非常易于使用,并且有完整的文档。如果你使用它,你的插入将是这样的:

$householdId = $_POST['householdid'];
$region = $_POST['region'];
$totalMembers = $_POST['totalmembers'];
$totalFemale = $_POST['totalfemale'];
$totalMale = $_POST['totalmale'];
// $database is an object which you declared using medoo.
$result = $database->insert("households",[
    "householdId" => $householdId,
    "region" => $region,
    "totalMembers" => $totalMembers,
    "totalFemale" => $$totalFemale,
    "totalMale" => $totalMale
    ]);

和文档中说的一样,对于insert:

返回:[number]最后一个插入id

检查$result是否>= 1:

if($result >= 1) {
    echo "SUCCESS";
}
else{
    echo "FAILURE ";
}

我想它可以作为你的服务器。对于您的客户端,它将是这样的:

首先需要一个服务生成器:

public class ServiceGenerator {
    public static final String API_BASE_URL = "http://your.api-base.url";
    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());
    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
}

那么你必须写你自己的接口…假设你的web服务是这样的:http://your.api-base.url/my-service/insert.php

和你的界面:

public interface MyClient {  
    @POST("/myservice/insert.php")
    Call<String> insert(
        @Body("householdid") String householdId,
        @Body("region") String region,
        @Body("totalmembers") String totalMembers,
        @Body("totalfemale") String totalFemale,
        @Body("totalmale") String totalMale
    );
}

好了,现在一切都准备好了。

要调用这个方法,你应该这样做:

MyClient client = ServiceGenerator.createService(MyClient.class);
Call<String> insertCall = client.insert(houseNo.getText().toString(),
        region,
        totalMembers.getText().toString(),
        totalFemale.getText().toString(),
        totalMale.getText().toString());
        insertCall.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if(response != null && response.isSuccessful()){
                        // you have a response...handle it
                    }
                }
                @Override
                public void onFailure(Call<OwnerResponse> call, Throwable t) {
                    //PROBLEM!!!
                }
            }