来自Android的变量在Symfony中始终为null

时间:2016-11-09 19:54:19

标签: android doctrine symfony fosrestbundle

我正在Symfony3 for Android中编写API RESTful(FosRestBundle)。我使用继承自StringRequest的类从Android传递值。

public class CommandActivity extends AppCompatActivity {

protected TextView tvDrink;
protected TextView tvFood;
protected TextView tvTotalprice;
protected Button btAccept;
protected Button btCancel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_command);


    //Recuperamos los arrays que nos ha pasado MainActivity
    Intent intent = getIntent();

    final ArrayList<String> namecomfoods = intent.getStringArrayListExtra("namecomfoods");
    final ArrayList<Integer> amountfoods = intent.getIntegerArrayListExtra("amountfoods");
    final ArrayList<String> namecomdrinks = intent.getStringArrayListExtra("namecomdrinks");
    final ArrayList<Integer> amountdrinks = intent.getIntegerArrayListExtra("amountdrinks");

    final String Sum = intent.getStringExtra("Sum");
    final int idtable = intent.getIntExtra("idtable", 0);
    final int iduser = intent.getIntExtra("iduser", 0);

    final LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);


    tvDrink = (TextView) findViewById(R.id.tvDrink);
    tvFood = (TextView) findViewById(R.id.tvFood);
    tvTotalprice = (TextView) findViewById(R.id.tvTotalprice);
    btAccept = (Button)findViewById(R.id.btAccept);
    btCancel = (Button)findViewById(R.id.btCancel);

    for(int i = 0; i < namecomdrinks.size(); i++) {
        tvDrink.append(amountdrinks.get(i)+" "+namecomdrinks.get(i));
        tvDrink.append("\n");

    }
    tvDrink.setMovementMethod(new ScrollingMovementMethod());

    for(int i = 0; i < namecomfoods.size(); i++) {
        tvFood.append(amountfoods.get(i)+" "+namecomfoods.get(i));
        tvFood.append("\n");
    }

    tvFood.setMovementMethod(new ScrollingMovementMethod());

    tvTotalprice.setText("Total: "+Sum);

    //Presionamos botón Aceptar
    btAccept.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {

            // Respuesta que recibimos del servidor
            Response.Listener<String> responseListener = new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response)
                {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success)
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(CommandActivity.this);
                            builder.setMessage("Pedido lanzado a cocina")
                                    .setNegativeButton("de acuerdo", null)
                                    .create()
                                    .show();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(CommandActivity.this);
                            builder.setMessage("Error al procesar el pedido")
                                    .setNegativeButton("Intenta de nuevo", null)
                                    .create()
                                    .show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };
            String expense = Sum.replace("€","");
            RegcommandRequest regcommandRequest = new RegcommandRequest(expense,idtable,iduser,responseListener);
            RequestQueue queue = Volley.newRequestQueue(CommandActivity.this);
            queue.add(regcommandRequest);
        }
    }
    );

    //Presionamos botón Cancelar
    btCancel.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            finish();
        }
    });
}
}

RegcommandRequest类:

public class RegcommandRequest extends StringRequest
{
    private static final ConvertUrl convurl = new ConvertUrl();
    private static final String REG_COMMAND_URL = convurl.ConvertUrl("regcommand");

private Map<String, String> params;

public RegcommandRequest(String expense,int idtable, int iduser, Response.Listener<String> listener)
{
    super(Method.POST, REG_COMMAND_URL, listener, null);
    params = new HashMap<>();
    params.put("Sum",String.valueOf(expense));
    params.put("idtable", String.valueOf(idtable));
    params.put("iduser", String.valueOf(iduser));


}

}

在Symfony中,

费用,idtable和iduser始终为null。但是,如果我调试Android应用程序值正确传递。我不明白!! 我尝试用differentes方法

$table = $em->getRepository('AppBundle:Table_')->find($idtable);

dev.log向我展示

request.CRITICAL: Uncaught PHP Exception Doctrine\ORM\ORMException: "The identifier id is missing for a query of AppBundle\Entity\Table_" at /opt/lampp/htdocs/ebar11/vendor/doctrine/orm/lib/Doctrine/ORM/ORMException.php line 294 {"exception":"[object] (Doctrine\\ORM\\ORMException(code: 0): The identifier id is missing for a query of AppBundle\\Entity\\Table_ at /opt/lampp/htdocs/ebar11/vendor/doctrine/orm/lib/Doctrine/ORM/ORMException.php:294)"} []

也是

$qb = $em->createQueryBuilder();

    $table = $qb->select('t')
                 ->from('AppBundle:Table_', 't')
                ->where("t.id = '$idtable'")
                 ->getQuery()
                 ->getResult();

$table = $em->getRepository('AppBundle:Table_')->findOneById($idtable);

和dev.log显示我

doctrine.DEBUG: SELECT t0_.id AS id_0, t0_.number AS number_1, t0_.location AS location_2, t0_.sun AS sun_3, t0_.state AS state_4, t0_.nchair AS nchair_5, t0_.Bar_id AS Bar_id_6 FROM Table_ t0_ WHERE t0_.id = '' [] []

Symfony中的控制器方法

    /**
 * @Post("/api/regcommand.{_format}", defaults={"_format"="json"}, options={"expose"=true}, name="api_regcommand")
 * @View()
 */
public function regcommandAction(Request $request)
{
    // Recuperamos los datos que nos envían desde la aplicación android
    $expense = $request->request->get('expense');
    $idtable = $request->request->get('idtable'); 
    $iduser = $request->request->get('iduser');


    //Creamos objeto gestor de entidades responsable del manejo de la bbdd
    $em = $this->getDoctrine()->getManager();
    //$em->getConnection()->getConfiguration()->setSQLLogger(null);

    //$em->getConnection()->getConfiguration()->setSQLLogger(null);       
    //Establecemos la fecha de inicio
    $startdate = new \DateTime();
    //Establecemos estado del pedido (start/progress/final/kill)
    $statecommand = "start";

    //Buscamos las mesa
    //$table = $em->getRepository('AppBundle:Table_')->find($idtable);
    $table = $em->getRepository('AppBundle:Table_')->findOneBy(array('id' => $idtable));

    /*$qb = $em->createQueryBuilder();

    $table = $qb->select('t')
                 ->from('AppBundle:Table_', 't')
                ->where("t.id = '$idtable'")
                 ->getQuery()
                 ->getResult();*/

    if (!$table)
    {
        $data["success"] = false;
        $response = $this->view($data, 200);
        return $this->handleView($response);  
    }

    //Buscamos el usuario

    $user = $em->getRepository('AppBundle:User')->findOneBy(array('id' => $iduser));
    /*$qb = $em->createQueryBuilder();
    $user = $qb->select('u')
                 ->from('AppBundle:User', 'u')
                ->where("u.id = '$iduser'")
                 ->getQuery()
                 ->getResult();*/

    if(!$user)
    {
        $data["success"] = false;
        $response = $this->view($data, 200);
        return $this->handleView($response);            
    }


    $command = new Command();
    $command->setStartdate($startdate);
    $command->setStatecommand($statecommand); 
    $command->setBuy($command->getBuy()+1); 
    $command->setExpense($expense);
    $command->setUser($user);                  
    $command->setTable($table);      


    //Metemos el nuevo command en la base de datos
    $em->persist($command);
    $flush = $em->flush();  
    $data = ["success"=>true];
    $data["user"] = $user;
    $response = $this->view($data, 200);
    return $this->handleView($response); 
}

在其他活动中,我对同一个实体使用了相同的程序,它运行没有问题。

请帮帮我!!这让我发疯了! 谢谢!

1 个答案:

答案 0 :(得分:1)

目前,您的Android应用程序未发送任何POST或GET参数。

这就是Symfony没有收到它们的原因。

尝试添加此功能:

@Override
public Map<String, String> getParams() {
    return params;
}

到你的RegcommandRequest班。