0

My project involve Android Studio for the implementation of an app running in my phone and a nodejs server. As how you can see in my app code I print the address but never enter in the function onSuccess neither onfailure. Just it get stucked in new AsyncHttpClient().get(url+beaconHash, new JsonHttpResponseHandler(). What should I do to connect my app with the server? Server code app.js:

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const cors = require("cors")

// Import base routes
const indexRouter = require('./routes/index');


// Database configuration
const host = 'localhost';
const dbName = 'foldersdb';

const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
mongoose.connect('mongodb://' + host + '/' + dbName);

const db = mongoose.connection;
db.on('error', function () {
  console.error('Connection error!')
});
db.once('open', function () {
  console.log('DB connection Ready');
});

// Init express app
const app = express();

// Enable CORS
app.use(cors())

// Setup logger and body parser
app.use(morgan('dev'));
app.use(bodyParser.json());

// Setup static public folder
app.use(express.static(path.join(__dirname, 'public')));

// Setup base routes
app.use('/', indexRouter);

// Catch 404 errors
app.use(function (req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// Error handler
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: err
  });
});

module.exports = app;

Server code www.js:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

const app = require('../app');
const http = require('http');

/**
 * Get port from environment and store in Express.
 */

const port = process.env.PORT || '4000';
app.set('port', port);

/**
 * Create HTTP server.
 */

const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

module.exports.server = server;


/**
 * Event listener for HTTP server "error" event.
 */
function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
    case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
    case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
    default:
        throw error;
    }
}

/**
 * Event listener for HTTP server "listening" event.
 */
function onListening() {
    var addr = server.address();
    var bind = 'port ' + addr.port;
    console.log('Listening on ' + bind);
}

App code:

private static String url = "http://192.168.x.xxx:4000/"; //my ipv4 address 
public static final Set<String> DEFAULT = new HashSet<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_beacon_results);
    Log.d("Stato:", "Sono su onCreate");
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        //actionBar.setTitle("Prova");
        if(getIntent().getStringExtra("BeaconHash").equals("6472324")){
            Log.d("Stato:", "Sto creando la cartella");
            actionBar.setTitle("Folder1");
        }
    }

    final View progressBar2 = findViewById(R.id.progressBar2);
    String beaconHash = getIntent().getStringExtra("BeaconHash");
    Log.d("Stato:", "URL" + " " + url + " " + "beaconHash" + " " + beaconHash);
    new AsyncHttpClient().get(url+beaconHash, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray responseBody) {
            Log.d("Stato:", "success");
            progressBar2.setVisibility(View.GONE);
            showResults(responseBody);
            Log.d("Risultati:", "response Body:" + responseBody);
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.d("Stato:", "failure");
            progressBar2.setVisibility(View.GONE);
            Toast.makeText(BeaconResultsActivity.this, "Error to load info", Toast.LENGTH_LONG).show();
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    });
}
Giulia
  • 11
  • 4
  • Did you allow insecure HTTP connections? By default, only HTTPS is permitted for android apps. – Alexander Hoffmann Mar 11 '22 at 07:56
  • How can I do this in API 21? – Giulia Mar 11 '22 at 10:53
  • https://stackoverflow.com/questions/51902629/how-to-allow-all-network-connection-types-http-and-https-in-android-9-pie – Alexander Hoffmann Mar 11 '22 at 11:26
  • Nothing changed :( In addition my friend tried the same code and the same server with his pc and his phone and he managed to eneter in the onsuccess method. Maybe some of my configuration is not well setted but I don't know which one – Giulia Mar 11 '22 at 11:38
  • Check logcat for errors/exceptions and their stack trace. – Robert Mar 11 '22 at 13:12
  • I checked logat and I get the Log.d with url, then nothing. It prints me neither "success" nor "failure". It's like it get stucked in AsyncHttpClient. My phone e my pc are using the same wifi and the server is listening at port 4000. – Giulia Mar 11 '22 at 13:24
  • It's like the get request can't reach the server – Giulia Mar 11 '22 at 13:25

0 Answers0