2017-02-06 3 views
0

Ich bin in der Lage, API via Volley-Bibliothek zu konsumieren, die normale Post-Methode verwenden, aber mein PHP-Team hat nur meine API, die JSON akzeptieren geändert. Ich weiß, es gibt JsonObjectrequest in volley, aber ich weiß nicht, wie man Parameter in `JsonObjectRequest setzen. Jede Hilfe wird geschätzt.Probleme beim PHP Api über Volley-Bibliothek Android

PHP API

<?php 
if($_SERVER['REQUEST_METHOD']=='POST'){ 
$data_back = json_decode(file_get_contents('php://input')); 
header("Content-type: application/json"); 
require "conn.php"; 
$id = $data_back->{"id"}; 
$address = $data_back->{"address"}; 
$pincode = $data_back->{"pincode"}; 
$name = $data_back->{"name"}; 
$mobile = $data_back->{"mobile"}; 

$sql = "UPDATE tbl_addressbook SET name = '$name', address = '$address', pincode = '$pincode', mobile = '$mobile' WHERE id = $id"; 

if(mysqli_query($conn,$sql)){ 
    echo 'Address Book Updated Successfully'; 
} 
else{ 
    echo 'Could Not Update Your Address Book'; 
    } 
} 
?> 

Volley Anfrage

StringRequest stringRequest=new StringRequest(Request.Method.POST, Config.UPDATE_ADDRESS_BOOK, 
           new Response.Listener<String>() { 
            @Override 
            public void onResponse(String response) { 
             Toast.makeText(mContext,"Address Changed",Toast.LENGTH_LONG).show(); 
             list.set(getAdapterPosition(),new AddressBookModel(bookModel.getId(), 
               etName.getText().toString(), 
               etAddress.getText().toString(), 
               etPinCode.getText().toString(), 
               etPhone.getText().toString(), 
               bookModel.getDefAddress())); 
             d.dismiss(); 
             progress.dismiss(); 
             ((Activity)mContext).runOnUiThread(new Runnable() { 
              @Override 
              public void run() { 
               notifyDataSetChanged(); 
              } 
             }); 
            } 
           }, new Response.ErrorListener() { 
          @Override 
          public void onErrorResponse(VolleyError error) { 
           Toast.makeText(mContext,"Something Went Wrong \n ttry again later",Toast.LENGTH_LONG).show(); 
          } 
         }){ 
          @Override 
          protected Map<String, String> getParams() throws AuthFailureError { 
           Map<String, String> map=new HashMap<String, String>(); 
           map.put("id",bookModel.getId()); 
           map.put("name",etName.getText().toString()); 
           map.put("address",etAddress.getText().toString()); 
           map.put("pincode",etPinCode.getText().toString()); 
           map.put("phone",etPhone.getText().toString()); 
           return checkParams(map); 
          } 
          private Map<String, String> checkParams(Map<String, String> map){ 
           Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); 
           while (it.hasNext()) { 
            Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next(); 
            if(pairs.getValue()==null){ 
             map.put(pairs.getKey(), ""); 
            } 
           } 
           return map; 
          } 
         }; 
         VolleySingleton.getInstance(mContext).addToRequestQueue(stringRequest); 
+0

Werfen Sie einen Blick auf die Antwort, die ich poste d. Es sollte dir helfen. – AnixPasBesoin

Antwort

2

Leicht kitschig Zitrone squeezy

Einige Code

HashMap<String, String> params = new HashMap<String, String>(); 
params.put("id", "300"); 
params.put("address", "Mars"); 
params.put("pincode", "***"); 
params.put("name", "Jon Skeet"); 
params.put("mobile", "911"); 
JsonObjectRequest request = new JsonObjectRequest(
          /*URL*/, 
          new JSONObject(params), 
          new Response.Listener<JSONObject>(){/*...*/}); 
+0

Was ist, wenn meine Antwort String Format ist. es geht direkt in den Fehlerantwortabschnitt –

2

Erste Erstellen Sie Ihre JsonObject wie

JSONObject js = new JSONObject(); 
    try { 
     js.put("email", "adasda"); 
     js.put("address", "adasd"); 
     js.put("pincode", "adadasd"); 

    }catch (JSONException e) { 
      e.printStackTrace(); 
    } 

Ihre JSON Anfrage Dann nehmen Sie einen sorgfältigen Blick auf get-Header .

JsonObjectRequest jsonObjReq = new JsonObjectRequest(
    Request.Method.POST,url, js, 
    new Response.Listener<JSONObject>() { 
     @Override 
     public void onResponse(JSONObject response) { 
      Log.d(TAG, response.toString()); 

      msgResponse.setText(response.toString()); 
      hideProgressDialog(); 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      VolleyLog.d(TAG, "Error: " + error.getMessage()); 
      hideProgressDialog(); 
     } 
    }) { 

/** 
* Passing some request headers 
* */ 
@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    HashMap<String, String> headers = new HashMap<String, String>(); 
    headers.put("Content-Type", "application/json; charset=utf-8"); 
    return headers; 
} 
+0

Vielen Dank für Ihre Hilfe bro ... Stand Antworten funktioniert großartig .. aber ich kann nur einen Tick, also werde ich Ihre Antwort aufwerten. –

-2

private void getWalletDetails() {

final ProgressDialog pDialog; // = new ProgressDialog(mcontext); 
    StringRequest stringRequest; 

    pDialog = GifDialog.ctor(mcontext); 
    pDialog.show(); 

    stringRequest = new StringRequest(Request.Method.POST, place your url, 
      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String s) { 
        //Disimissing the progress dialog 
        pDialog.dismiss(); 
        //Showing toast message of the response 

        try { 

         JSONObject jsonObject = new JSONObject(s); 

         totbal.setText("\u20B9 "+jsonObject.getString("avail_balance")); 
         JSONArray jsonArray = jsonObject.getJSONArray("tx_detail"); 

         for (int i = 0; i < jsonArray.length(); i++) { 

          JSONObject object = jsonArray.getJSONObject(i); 
          mode = new Model_Wallet_Transaction(); 
          mode.setStr1(object.getString("date")); 
          mode.setStr4(object.getString("insert_time")); 
          mode.setStr2(object.getString("name")); 

          mode.setStr3(object.getString("transaction_id_no")); 
          mode.setAmount(object.getString("amount")); 
          mode.setTxtype(object.getString("tx_type")); 
          modlist.add(mode); 
         } 
         // Collections.sort(modlist, new StringDateComparator()); 
         adp = new CustomAdapter_Wallet_Transaction(getApplicationContext(), modlist); 
         list.setAdapter(adp); 

        } catch (Exception e) { 

         Log.e("Error", e.toString()); 
        } 
        // Toast.makeText(Wallet_Transaction.this, s, Toast.LENGTH_LONG).show(); 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError volleyError) { 
        //Dismissing the progress dialog 
        pDialog.dismiss(); 
        //Showing toast 
        //Toast.makeText(Wallet_Transaction.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show(); 
       } 

      }) { 

     @Override 
     protected Map<String, String> getParams() throws AuthFailureError { 

      //Creating parameters 
      Map<String, String> params = new Hashtable<String, String>(); 
      //Adding parameters 
      params.put("user_id", UserId);   
      params.put("deviceId", DeviceId); 

      return params; 
     } 
    }; 

    //Creating a Request Queue 
    RequestQueue requestQueue = Volley.newRequestQueue(this); 
    //Adding request to the queue 
    requestQueue.add(stringRequest); 
} 
+0

[TROCKEN] (https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRfJOOBbrcra9IBbvPsk0c1u5JR78hZDhnsN16ych6Mva5XREHn). Du machst etwas, das Volley schon für dich tut. Erfinde das Rad nicht neu. – AnixPasBesoin