2016-11-09 6 views
0

Android用Symfony3でAPI RESTful(FosRestBundle)をプログラミングしています。私はStringRequestを継承したクラスでAndroidから値を渡します。Androidからの変数は常にsymfonyではnullです

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


} 

}

費用、IDTABLEとiduserはsymfonyに常にnullです。しかし、私はアンドロイドアプリをデバッグする場合、値が正しく渡されます。わかりません!! 私は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 = '' [] [] 

iが同じエンティティと同じ手順を使用して、それが問題なく実行され、他の活動に

/** 
* @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); 
} 

symfonyのコントローラ方法。

お願いします。それは私を夢中にさせてくれる! ありがとうございます!

+1

まず最初に、あなたのエラーに関係していなくても、 ' - > where(" t.id = '$ idtable' ")のように' $ idtable'をクエリに直接連結してはいけません。 )。代わりに**クエリビルダー**にパラメータをバインドする必要があります([the doctrine documentation](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.htmlを参照)。 #binding-parameters-to-your-query)を参照してください)。もしあなたがそれをしないと、アプリケーション**はSQLインジェクション**に対して脆弱です。 –

+1

あなたのsymfonyコードは大丈夫です。リクエストに関連するAndroidコードで質問を編集し、完了したら通知してください。 –

+0

私はAndroidコードを入れました。ありがとう – DBCooper

答えて

1

現在のところ、AndroidアプリケーションはPOSTやGETパラメータを送信していません。

これは、Symfonyがそれらを受信しない理由です。

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

あなたRegcommandRequestクラスに:

は、この機能を追加してみてください。

+1

どのように私はそれらに気付かなかったのですか?私は完全に盲目でした。どうもありがとう!!!!!私は、クエリビルダーでパラメータをバインドするつもりです。 – DBCooper

関連する問題