0

I have created an Api which is used to add multiple invitations in the database called as sendMultipleInvites.

Now I want to implement this API in android. I am trying to create an AsyncTask to call the api. I have helper class to connect to http server.

I am testing this in postman: my input should be like this:

 {
"invitations": [
    {

    "date" : "12/08/2016",
    "invitee_no" : "196756456",
    "status" : "1",
    "user_name" : "user10"

    },
    {

    "date" : "12/08/2016",
    "invitee_no" : "13633469",
    "status" : "1",
    "user_id" : "user9"

    }
  ]
}

My serverRequest class:

    public class ServerRequest {
    String api;
    JSONObject jsonParams;

    public ServerRequest(String api, JSONObject jsonParams) {
        this.api = api;
        this.jsonParams = jsonParams;
    }

    public JSONObject sendRequest() {
        try {
            URL url = new URL(api);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoOutput(true);
            con.setDoInput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(jsonParams.toString());
            writer.close();

            int responseCode = con.getResponseCode();
            if  (responseCode == HttpURLConnection.HTTP_OK) {
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line = "";
                while ( (line = reader.readLine()) != null ){
                    sb.append(line);
                }
                reader.close();
                Log.d("ServerResponse", new String(sb));
                return new JSONObject(new String(sb));
            } else {
                throw new UnexpectedServerException("Unexpected server exception with status code : "+responseCode);
            }
        } catch (MalformedURLException me) {
            me.printStackTrace();
            return Excpetion2JSON.getJSON(me);
        } catch(IOException ioe) {
            ioe.printStackTrace();
            return Excpetion2JSON.getJSON(ioe);
        } catch(UnexpectedServerException ue) {
            ue.printStackTrace();
            return Excpetion2JSON.getJSON(ue);
        } catch (JSONException je) {
            je.printStackTrace();
            return Excpetion2JSON.getJSON(je);
        }
    }

    public ServerRequest(String api) {
        this.api = api;
    }

}

This is my asyncTask :

    public class SendMultipleInvitesAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject> {

    private Context context;

    public SendInviteAsyncTask(Context context) {
        this.context = context;
        this.progressDialog = new ProgressDialog(context);
    }

    @Override
    protected JSONObject doInBackground(Map<String, String>... params) {
        try {
            String api =  context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
            Map2JSON mjs = new Map2JSON();
            JSONObject jsonParams = mjs.getJSON(params[0]);
            ServerRequest request = new ServerRequest(api, jsonParams);
            return request.sendRequest();
        } catch (JSONException je) {
            return Excpetion2JSON.getJSON(je);
        }
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);

        Log.d("ServerResponse", jsonObject.toString());
        try {
            int result = jsonObject.getInt("status");
            String message = jsonObject.getString("message");
            if (result == 1) {


                //Code for having successful result for register api goes here

            } else {

                Toast.makeText(context, message, Toast.LENGTH_LONG).show();

            }

        } catch (JSONException je) {
            je.printStackTrace();
            Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

Edit:

Trying like this it is giving an error when I try to pass an arraylist to the execute method of async task.

AsyncTask:

public class SendInviteAsyncTask extends AsyncTask<ArrayList<Invitation>, Void, JSONObject> {

private ProgressDialog progressDialog;
private Context context;

public SendInviteAsyncTask(Context context) {
    this.context = context;
    this.progressDialog = new ProgressDialog(context);
}

@Override
protected JSONObject doInBackground(ArrayList<Invitation>... arrayLists) {
    try {
        String api =  context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";


        ServerRequest request = new ServerRequest(api, jsonParams);

        return request.sendRequest();
    } catch (JSONException je) {
        return Excpetion2JSON.getJSON(je);
    }
}

Activity:

public class SendMultipleInvites extends AppCompatActivity {

    private ArrayList<Invitation> invitationArrayList;


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

        invitationArrayList = new ArrayList<>();

        Invitation invitation = new Invitation("3","17/02/2016","55165122","1","user10");

        invitationArrayList.add(invitation);

        invitation = new Invitation("3","17/02/2016","282751221","1","user10");

        invitationArrayList.add(invitation);

        new SendMultipleInvitesAsyncTask(SendMultipleInvites.this).execute(invitationArrayList);

    }
}

I was using hash map to send key and values. How can I do to send a json array? How to modify my async Task? How can I send array to an async task? Can anyone help please.. Thank you..

Sid
  • 2,792
  • 9
  • 55
  • 111

3 Answers3

0

To pass Array to your async Task do this:

SendInviteAsyncTask extends AsyncTask<ArrayList<Sring>, Void, JSONObject>

To make a Json object you can use Gson library

Rusheel Jain
  • 843
  • 6
  • 20
  • can you please check edited question. What is going wrong? @Rusheel Jain – Sid Sep 13 '16 at 12:31
  • your async task name in execute line is wrong. It should be: new SendInviteAsyncTask(SendMultipleInvites.this).execute – Rusheel Jain Sep 13 '16 at 12:58
  • sorry is was a typo the name of an asynctask is SendMultipleInvitesAsyncTask. @Rusheel Jain – Sid Sep 13 '16 at 13:02
0

try this

JSONObject obj = new JSONObject();
    JSONArray req = new JSONArray();

    JSONObject reqObj = new JSONObject()
    reqObj.put( "ctrlId", "txt1" );
    req.put( reqObj );
    reqObj = new JSONObject();
    reqObj.put( "ctrlId", "txt2" );
    req.put( reqObj );
    obj.put( "req", req );
Prashant Sharma
  • 1,357
  • 1
  • 21
  • 31
0

You can really simplify your code by using a few libraries for building json and sending http requests. Here is sample code using Gson for building the json string and Volley for the http request.

I also used this fantastic project for generating the json pojo objects below. It makes really quick work of it.

        Invite ivt = new Invite();
        ivt.getInvitations().add( new Invitation("3","17/02/2016","55165122","1","user10"));
        ivt.getInvitations().add(  new Invitation("3","17/02/2016","282751221","1","user10"));

        Gson gson = new Gson();
        String jsonString = gson.toJson(ivt);

        String url = appContext.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";

        RequestQueue queue = Volley.newRequestQueue(appContext);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
              new Response.Listener<String>() {
                  @Override
                  public void onResponse(String response) {

                      Log.d("TAG", "success: " + response);
                  }
              }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        queue.add(stringRequest);

Invite.java

public class Invite {

    @SerializedName("invitations")
    @Expose
    private List<Invitation> invitations = new ArrayList<Invitation>();
    public List<Invitation> getInvitations() {
        return invitations;
    }
    public void setInvitations(List<Invitation> invitations) {
        this.invitations = invitations;
    }

}

Invitation.java

public class Invitation {

    @SerializedName("date")
    @Expose
    private String date;
    @SerializedName("invitee_no")
    @Expose
    private String inviteeNo;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("user_name")
    @Expose
    private String userName;
    @SerializedName("user_id")
    @Expose
    private String userId;

    public Invitation(String d, String one, String two, String three, String four) {
        date = d;
        inviteeNo = one;
        status = two;
        userName = three;
        userId = four;

    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getInviteeNo() {
        return inviteeNo;
    }
    public void setInviteeNo(String inviteeNo) {
        this.inviteeNo = inviteeNo;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }


}
Gary Bak
  • 4,746
  • 4
  • 22
  • 39