13

I'm at a bit of a loss as to how to send a jsonobject from my android application to the database

As I am new to this I'm not too sure where I've gone wrong, I've pulled the data from the XML and I have no clue how to then post the object to our server.

any advice would be really appreciated

 package mmu.tom.linkedviewproject;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageButton;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.IOException;
    
    /**
     * Created by Tom on 12/02/2016.
     */
    public class DeviceDetailsActivity extends AppCompatActivity {

    private EditText address;
    private EditText name;
    private EditText manufacturer;
    private EditText location;
    private EditText type;
    private EditText deviceID;


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

        ImageButton button1 = (ImageButton) findViewById(R.id.image_button_back);
        button1.setOnClickListener(new View.OnClickListener() {
            Class ourClass;

            public void onClick(View v) {

                Intent intent = new Intent(DeviceDetailsActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });


        Button submitButton = (Button) findViewById(R.id.submit_button);

        submitButton.setOnClickListener(new View.OnClickListener() {
            Class ourClass;

            public void onClick(View v) {

                sendDeviceDetails();
            }
        });

        setContentView(R.layout.activity_device_details);

        this.address = (EditText) this.findViewById(R.id.edit_address);
        this.name = (EditText) this.findViewById(R.id.edit_name);
        this.manufacturer = (EditText) this.findViewById(R.id.edit_manufacturer);
        this.location = (EditText) this.findViewById(R.id.edit_location);
        this.type = (EditText) this.findViewById(R.id.edit_type);
        this.deviceID = (EditText) this.findViewById(R.id.edit_device_id);

    }




        protected void onPostExecute(JSONArray jsonArray) {

            try
            {
                JSONObject device = jsonArray.getJSONObject(0);

                name.setText(device.getString("name"));
                address.setText(device.getString("address"));
                location.setText(device.getString("location"));
                manufacturer.setText(device.getString("manufacturer"));
                type.setText(device.getString("type"));
            }
            catch(Exception e){
                e.printStackTrace();
            }




        }

    public JSONArray sendDeviceDetails() {
        // URL for getting all customers


        String url = "http://IP-ADDRESS:8080/IOTProjectServer/registerDevice?";

        // Get HttpResponse Object from url.
        // Get HttpEntity from Http Response Object

        HttpEntity httpEntity = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);

            httpEntity = httpResponse.getEntity();


        } catch (ClientProtocolException e) {

            // Signals error in http protocol
            e.printStackTrace();

            //Log Errors Here


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


        // Convert HttpEntity into JSON Array
        JSONArray jsonArray = null;
        if (httpEntity != null) {
            try {
                String entityResponse = EntityUtils.toString(httpEntity);
                Log.e("Entity Response  : ", entityResponse);

                jsonArray = new JSONArray(entityResponse);

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

        return jsonArray;


    }


}


   
GingerFish
  • 457
  • 3
  • 11
  • 26
  • you can send JSONObject to the server by converting that into a String. I am not sure what issue you are facing. It would be better if you can elaborate more – Mukesh Rana Feb 14 '16 at 11:13
  • I was told we can only send it as an object, i know how to send it as a string but no clue how to send it as an object – GingerFish Feb 14 '16 at 11:22

4 Answers4

23

You need to be using an AsyncTask class to communicate with your server. Something like this:

This is in your onCreate method.

Button submitButton = (Button) findViewById(R.id.submit_button);

submitButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        JSONObject postData = new JSONObject();
        try {
            postData.put("name", name.getText().toString());
            postData.put("address", address.getText().toString());
            postData.put("manufacturer", manufacturer.getText().toString());
            postData.put("location", location.getText().toString());
            postData.put("type", type.getText().toString());
            postData.put("deviceID", deviceID.getText().toString());

            new SendDeviceDetails().execute("http://52.88.194.67:8080/IOTProjectServer/registerDevice", postData.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

This is a new class within you activity class.

private class SendDeviceDetails extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        String data = "";

        HttpURLConnection httpURLConnection = null;
        try {

            httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes("PostData=" + params[1]);
            wr.flush();
            wr.close();

            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char current = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                data += current;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data
    }
}

The line: httpURLConnection.setRequestMethod("POST"); makes this an HTTP POST request and should be handled as a POST request on your server.

Then on your server you will need to create a new JSON object from the "PostData" which has been sent in the HTTP POST request. If you let us know what language you are using on your server then we can write up some code for you.

Nikhil Dinesh
  • 3,359
  • 2
  • 38
  • 41
Tom Alabaster
  • 965
  • 6
  • 12
  • 1
    So i've made all these changes but it doesn't seem to be sending anything , and nothing is showing in the logcat saying it's sending. and help would be apreciated – GingerFish Feb 14 '16 at 11:53
  • 1
    @TomFisher You should add in some `Log.e("TAG", variable);` in the code I have given you. Above the line `String data = "";`, add in `Log.e("TAG", params[0]);` and `Log.e("TAG", params[1]);` to check that the SendDeviceDetails class is being executed correctly, also add `Log.e("TAG", data);` above the line `return data;`. If there is nothing in the logcat then it makes me think that it is not being executed. Also make sure you have added the internet permission in your manifest. – Tom Alabaster Feb 14 '16 at 13:14
  • 1
    Yeah I did that but there is nothing showing up in the logcat, so i've put them all over the place and it seems that the button isn't responding to being clicked. – GingerFish Feb 14 '16 at 13:26
  • 1
    Ahh, I've just noticed there is no `@Override` above `public void onClick(View v) {`, try adding this back in or rewrite the whole `setOnClickListener` part of the code using suggestions from your IDE (assuming your IDE provides you with suggestions like with Android Studio). – Tom Alabaster Feb 14 '16 at 13:30
  • 1
    I just get an error when i add the @overide, tried redoing it and still nothing. no errors, it just doesn't recognize the click at all – GingerFish Feb 14 '16 at 14:09
  • @TomFisher What is the error it gave you? Try adding in `Log.e("TAG", "buttonClicked");' as the first line within the button's `onClick` method to confirm whether the button is working or not. Also anything displayed in the logcat will be incredibly useful. – Tom Alabaster Feb 14 '16 at 14:53
  • It's not showing any error, it's just as though the buttons not being clicked at all. it's really frustrating me haha – GingerFish Feb 14 '16 at 15:04
  • this is the only thing i get when the activity loads 'E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab750ce0' – GingerFish Feb 14 '16 at 15:11
  • That is most bizarre, the only thing I can think of is there being a problem with your XML layout but I must admit I haven't come across the problem you are facing at the moment haha! – Tom Alabaster Feb 14 '16 at 15:14
  • i like your answer but how i would receive json-data in php? – kcire_eae Mar 05 '17 at 18:59
  • how to send json data to soap services – Jyoti Sharma Apr 27 '18 at 11:17
  • I couldn't used the JSON sent to server. After changing this line, `wr.writeBytes("PostData=" + params[1]);` by removing `"PostData=" + ` and just using `params[1]`I was able to use JSON in my .php file. – tekin beyaz Jan 25 '19 at 23:28
  • @TomAlabaster i am using django server. could please write a code for me how to recieve POST data on server side? kindly check last paragraph of your answer. – Noman marwat Oct 24 '19 at 10:08
1

As per your current code implementation you have onPostExecute method but there is no onPreExecute and doInBackgound method. Starting from Android 3.0 all network operations need to be done on the background thread. So you need to use Asynctask that will perform the actual sending of the request in the background and in the onPostExecute handle the result returned by the doInbackground method.

Here is what you need to do.

  1. Create a Asynctask class and override all the necessary methods.
  2. The sendDeviceDetails method will eventually go inside the doInBackgound method.
  3. onPostExecute will handle the result returned.

As far as sending a JSON object is concerned, you can do it as follows,

Code snippet borrowed from here

 protected void sendJson(final String email, final String pwd) {
    Thread t = new Thread() {

        public void run() {
            Looper.prepare(); //For Preparing Message Pool for the child Thread
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
            HttpResponse response;
            JSONObject json = new JSONObject();

            try {
                HttpPost post = new HttpPost(URL);
                json.put("email", email);
                json.put("password", pwd);
                StringEntity se = new StringEntity( json.toString());  
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                /*Checking response */
                if(response!=null){
                    InputStream in = response.getEntity().getContent(); //Get the data in the entity
                }

            } catch(Exception e) {
                e.printStackTrace();
                createDialog("Error", "Cannot Estabilish Connection");
            }

            Looper.loop(); //Loop in the message queue
        }
    };

    t.start();      
}

This is just one of the ways. You can go for an Asynctask implementation as well.

Ali Khaki
  • 1,184
  • 1
  • 13
  • 24
Parth Doshi
  • 4,200
  • 15
  • 79
  • 129
1

You should use web service to send data from your app to your server because it will make your work easy and smooth. For that you have to create web service in any server side language like php,.net or even you can use jsp(java server page).

You have to pass all items from your Edittexts to web service.Work of adding data to server will be handled by web service

Parsania Hardik
  • 4,593
  • 1
  • 33
  • 33
0
Button submitButton = (Button) findViewById(R.id.submit_button);

submitButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {

        JSONObject postData = new JSONObject();

        try {
            postData.put("name", name.getText().toString());
            postData.put("address", address.getText().toString());
            postData.put("manufacturer", manufacturer.getText().toString());
            postData.put("location", location.getText().toString());
            postData.put("type", type.getText().toString());
            postData.put("deviceID", deviceID.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Dima Kozhevin Jul 29 '20 at 15:22