Viewed   117 times

To post json from android to php, i used Volley library StringRequest object.

StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // some code
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //some code
            }
        }){
            @Override
            protected Map<String,String> getParams(){
                Map<String, String> params = new HashMap<String, String>();
                ArrayList<Command> commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND);
                String jsonCommands = new Gson().toJson(commands);
                params.put("commands", jsonCommands);
                return params;
            }
        };

And to catch the data in php and verify if it was sent correcttly, I used this

echo $_POST["commands"]; 

Output:

[{"product":{"category_id":1,"created_at":"2015-06-13 17:49:58","description":"CF77 COIN FINDER","url_image":"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg","name":"CF77 COIN FINDER","pid":12,"price":500.0},"product_quantity":3},{"product":{"category_id":1,"created_at":"2015-06-13 17:49:58","description":"JEOSONAR 3D DUAL SYSTEM","url_image":"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg","name":"JEOSONAR 3D DUAL SYSTEM","pid":15,"price":500.0},"product_quantity":1},{"product":{"category_id":1,"created_at":"2015-06-13 17:49:58","description":"MAKRO POINTER","url_image":"IMG_Macro.jpg","name":"MAKRO POINTER","pid":18,"price":500.0},"product_quantity":3}]

I have noticed that when sending the json string with POST Method using Volley library, a lot of anti-slashes have been added to escape double quotes.

So here comes my problem:

I want to decode json to an array of objects in php, so i used

$commands = json_decode( $_POST["commands"],true);

But it always returns an empty array because of the invalide above json (caused by the anti-slashes).

Is there a method in php or in java SDK providing a contract for sending and receiving json without having this kind of problems? Or should i reformat the json in php and delete all the anti-slashes?

 Answers

1

Finally, I solved my problem using a custom json_decode method in order to clean the json string before decoding it.

function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {
    // search and remove comments like /* */ and //
    $json = preg_replace("#(/*([^*]|[rn]|(*+([^*/]|[rn])))**+/)|([st]//.*)|(^//.*)#", '', $json);
    // search and remove all backslashes
    $json = str_replace("\","", $json);

    if(version_compare(phpversion(), '5.4.0', '>=')) {
        $json = json_decode($json, $assoc, $depth, $options);
    }
    elseif(version_compare(phpversion(), '5.3.0', '>=')) {
        $json = json_decode($json, $assoc, $depth);
    }
    else {
        $json = json_decode($json, $assoc);
    }

    return $json;
}
Friday, October 21, 2022
 
pubby
 
1

Ok, I found the answer. The JsonObjectRequest / JsonArrayRequest take an additional JsonObject / JsonArray object as an argument. In most sample codes online, this argument is set to null and I did the same because I did not want to send a Json, only to receive. Now what happens (quite unintuitively) behind the scenes of the Volley Json requests, is that if this argument is null the request is not done as a POST request, but as a GET instead. This caused my request to fail and the server to return an error code rather than a json. Such an error code in turn could not be parsed to a json of course. Very bad choice for a default implementation in Volley I find.

In any case, the solution was as easy as introducing a CustomJsonObjectRequest which is very similar to the implementation from the library, except that it sticks with the POST request:

public class CustomJsonObjectRequest extends Request<JSONObject> {

protected static final String PROTOCOL_CHARSET = "utf-8";

private final Response.Listener<JSONObject> mListener;

public CustomJsonObjectRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
    super(Method.POST, url, errorListener);
    mListener = listener;
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
  }

  @Override
  protected void deliverResponse(JSONObject response) {
    mListener.onResponse(response);
  }

}
Wednesday, September 14, 2022
 
4

Update:

I checked your code everything was at it's place except listener.onReponseReceive(arrayList); as mentioned in my answer it should be right after where while loop ends. Now your recyclerview is displaying items

Update:

The reason You are not getting the list in your recyclerview is because it takes some time to fetch response from webserver and your list get return earlier. In order to Resolve this, Try this

Create an Interface

    public interface WebResponseListener{
     void onReponseReceive(ArrayList <Contact_actors_list> list);
   }

In your BackgrundTask declare a variable of this interface

WebResponseListener listener;
public BackgrundTask (Context context,WebResponseListener listener)
    {
       this.listener = listener
        this.context = context;
    }

Make your getList() return void and do the following changes

 public void getList(){
//Where your while condition ends
//add following line
  listener.onReponseReceived(arrayList);
    -----
}

IN actorsList class Make yout actorList class implements the inferface as

public class actorsList extends AppCompatActivity implements WebResponseListener

replace the following lines

BackgrundTask backgroundTask = new BackgrundTask(actorsList.this); 
 arrayList = backgroundTask.getList();

with

BackgrundTask backgroundTask = new BackgrundTask(this,this); 
arrayList = new ArrayList<>();
adapter = new RecyclerAdapterActorsList(arrayList);
recyclerView.setAdapter(adapter);
backgroundTask.getList();

Add the following method in your actorsList class

public void onReponseReceive(ArrayList <Contact_actors_list> list){
    actorsList.this.arrayList.addAll(list);
    actorsList.this.adapter.notifyDataSetChanged();
}

Thursday, August 11, 2022
 
warhog
 
5

You would have to write a server program on the PC and use a ServerSocket to accept a connection from and write a thread for your Android phone that uses a regular socket (with the same port as the PC end) and then manage them using DataInputStream and DataOutputStream. You also need to open permissions on your AndroidManifest.xml.

For the permissions use this:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

For the code here's a little example:

Server:

String msg_received;

ServerSocket socket = new ServerSocket(1755);
Socket clientSocket = socket.accept();       //This is blocking. It will wait.
DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
msg_received = DIS.readUTF();
clientSocket.close();
socket.close();

Client:

Socket socket = new Socket("192.168.0.1",1755);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();
Saturday, September 10, 2022
 
jasuten
 
5

You can connect to SQL Server database through webservice.

Here is the sample code to call the webservice.

String url = "your_webservice_URL";

 try 
 {
    HttpPost loginHttpPost   = new HttpPost(url); 
    HttpContext localContext = new BasicHttpContext();          

    MultipartEntity multipartContent = new MultipartEntity();
    multipartContent.addPart("parameter1", new StringBody(value1));
    multipartContent.addPart("parameter2", new StringBody(value2));
    loginHttpPost.setEntity(multipartContent);

    HttpClient objHttpClient = new DefaultHttpClient();
    HttpResponse response = objHttpClient.execute(loginHttpPost,localContext);
 } 
 catch (IOException e) {
     e.printStackTrace();}
Sunday, December 11, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :