Search code examples
androiddoctrinesymfonyfosrestbundle

Variables from Android are always null in Symfony


I'm programming an API RESTful (FosRestBundle) in Symfony3 for Android. I pass values from Android with classes that inherit from StringRequest.

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 class:

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));


}

}

expense, idtable and iduser are always null in Symfony. However if i debug the android app the values are passed correctly. I don't understand!! I tried to do with differentes methods

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

And dev.log shows me

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)"} []

and too

$qb = $em->createQueryBuilder();

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

or

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

and dev.log shows me

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 = '' [] []

The controller method in 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); 
}

In other activities i have used the same procedure with the same Entity and it runs without problems.

Help me please!! It's drive me crazy! Thanks!!


Solution

  • Currently, your Android application isn't sending any POST nor GET parameter.

    This is why Symfony doesn't receive them.

    Try to add this function :

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

    to your RegcommandRequest class.