Rohit Pothuraju
Rohit Pothuraju

Reputation: 83

android post request using volley

I have used Volley, HttpClient and HttpUrlConnection in my android code that takes sensor metrics from sensor manager. I need to export these metrics through POST request to a nodejs server. Whenever there is a change in sensor values I need a post request to go asynchronously to the http server

MainActivity.java

package com.example.rpothuraju.gyrometrics;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

public class MainActivity extends Activity implements SensorEventListener{
TextView textView;
private SensorManager sensorManager;
//private Sensor sensor;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.metrics);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    //sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);


}

protected void onResume()
{
    super.onResume();
    sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),SensorManager.SENSOR_DELAY_FASTEST);
}

protected void onStop()
{
    sensorManager.unregisterListener(this);
    super.onStop();
}

public void onAccuracyChanged(Sensor arg0, int arg1)
{
    //Do nothing.
}

public void onSensorChanged(SensorEvent event)
{
    if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
    {
        return;
    }

    String url ="http://localhost:8080/?X=" + event.values[0] + "&&Y= " + event.values[1] + "&&Z=" + event.values[2];

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    });

    textView.setText("Orientation X (Roll) :"+ Float.toString(event.values[0]) +"\n"+
            "Orientation Y (Pitch) :"+ Float.toString(event.values[1]) +"\n"+
            "Orientation Z (Yaw) :"+ Float.toString(event.values[2]));

}
}

server.js

const util = require('util');
const http = require('http');

const port = 8080;

var server = http.createServer(function(request, response) {

response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
response.setHeader('Access-Control-Allow-Headers', 'Content-Type');

var values = (request.url).replace(/[`~!@#$%^&*()_|+\-?;:'",.<>\{\}\[\]\\\/]/gi, '');
response.end(values);
console.log(values);
});

server.listen(port, (err) => {
if (err) {
    return console.log('something bad happened', err)
}

console.log(`server is listening on ${port}`)
});

I am not able to see any response from the server...??

Upvotes: 1

Views: 679

Answers (2)

shubhamjuneja
shubhamjuneja

Reputation: 387

In your url, try using http://10.0.2.2/ instead of http://localhost

This will work in emulator.

Upvotes: 0

Abdullah Tellioglu
Abdullah Tellioglu

Reputation: 1474

You create the request object but never send it to server.
You should set up a request queue for it.

RequestQueue queue;
//inside the oncreate method 
queue = Volley.newRequestQueue(mCtx.getApplicationContext());
//and for sending request
String url ="http://localhost:8080/?X=" + event.values[0] + "&&Y= " + event.values[1] + "&&Z=" + event.values[2];

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    });
<br>
queue.add(stringRequest);

To better approach(create a singleton class for network requests) checkout this link below,
https://developer.android.com/training/volley/requestqueue.html

Upvotes: 1

Related Questions