How To Send json Object to the server from my android app

前端 未结 4 886
盖世英雄少女心
盖世英雄少女心 2020-11-30 09:25

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 gon

相关标签:
4条回答
  • 2020-11-30 09:38
    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();
            }
        }
    });
    
    0 讨论(0)
  • 2020-11-30 09:45

    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.

    0 讨论(0)
  • 2020-11-30 09:52

    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.

    0 讨论(0)
  • 2020-11-30 09:55

    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

    0 讨论(0)
提交回复
热议问题