Android application does not connect to the server - java

I had a question, I built the server part and the client with a socket and did not receive any errors. When I type the local address in the browser, it shows the information in cmd, but when I run the Android application in the emulator or mobile, it does not connect to the server.
The permissions I used:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Server codes:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//app.use(express.static(__dirname + '/static')
app.get('/', function (req, res, next) {
res.sendFile(__dirname + '/static/index.html');
});
io.on('connection', function (socket) {
console.log('one user connected ' + socket.id);
socket.on('message',function (data) {
console.log(data);
var sockets=io.sockets.sockets;
sockets.forEach(function (item) {
item.emit('message',{message:data});
});
});
socket.on('disconnect', function (){
console.log('user disconnected');
})
});
http.listen(8000)
console.log('server run on port 8000');
The MainActivity.java is:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
private Socket socket;
{
try {
socket = IO.socket("http://192.168.42.51:8000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Button btnSend;
EditText edtTextMessage;
LinearLayout linearMessage;
LinearLayout.LayoutParams layoutParams;
public Handler handler;
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button) findViewById(R.id.btnSend);
handler =new Handler();
edtTextMessage = (EditText) findViewById(R.id.edtTextMessage);
linearMessage=(LinearLayout)findViewById(R.id.linearMessage);
socket.connect();
socket.on("message", handlerIncomingMessage);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = edtTextMessage.getText().toString();
sendMessage(message);
}
});
}
public Emitter.Listener handlerIncomingMessage = new Emitter.Listener() {
#Override
public void call(Object... args) {
handler.post(new Runnable() {
#Override
public void run() {
JSONObject jsonObject=(JSONObject)args[0];
String message="";
try {
message=jsonObject.getString("message").toString();
TextView textView=new TextView(getApplicationContext());
textView.setText(message);
textView.setTextSize(18);
layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
linearMessage.addView(textView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
};
private void sendMessage(String message) {
socket.emit("Message", message);
}
}
please guide me.

I had the same issue before, it is because you are running the application on a emulator. Try to run it on a local phone on your local network with the API also running.

In emulator Localhost Ip is :http://10.0.2.2 use it if u are running in localhost.

Related

Connect MainActivity to a python server (Android Studio)

I'm trying to develop my first app in Android Studio and connect it to a server in python. I wrote a Client class and MainActivity with java in Android Studio and I wrote the Server in Pycharm. When I create a client object in different class, the connection between the client and the server works fine. However, when i do the same thing in the MainActivity it doesnt work and i get this error:
" E/m.example.mage: Unknown bits set in runtime_flags: 0x8000 ".
Do i need to do something else or is there a way to fix it?
package com.example.magen;
import android.widget.TextView;
import java.util.*;
import java.net.*;
import java.io.*;
public class Client {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("connected to server");
}
catch(Exception e){
System.out.println("error 1 " + e.getMessage());
}
}
public String sendMessage(String msg) {
String resp="";
try {
out.println(msg);
System.out.println("client: "+msg);
resp = in.readLine();
}
catch(Exception e){
System.out.println("error 2 " + e.getMessage());
}
return resp;
}
public void stopConnection() {
try {
in.close();
out.close();
clientSocket.close();
}
catch(Exception e){
System.out.println("error 3 " + e.getMessage());
}
}
}
import socket
import select
import datetime
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 6969))
server_socket.listen(10)
open_client_sockets = []
def main():
while True:
rlist, wlist, xlist = select.select([server_socket]+open_client_sockets, open_client_sockets, [])
for current_socket in rlist:
if current_socket is server_socket:
(new_socket, address) = server_socket.accept()
open_client_sockets.append(new_socket)
else:
full_msg = current_socket.recv(1024).decode()
print(full_msg)
current_socket.send("hi".encode())
...
...
...
...
...
if __name__ == '__main__':
main()
package com.example.magen;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText username;
private EditText password;
private Button loginButton;
private Button registerButton;
private TextView tvInfo;
private Client client = new Client();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.etUsername);
password = (EditText)findViewById(R.id.etPassword);
loginButton = (Button)findViewById(R.id.loginButton);
registerButton = (Button)findViewById(R.id.registerButton);
tvInfo = (TextView)findViewById(R.id.tvInfo);
connectToServer(client);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThirdActivity.class);
startActivity(intent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(username.getText().toString(), password.getText().toString(),tvInfo);
}
});
}
private void connectToServer(Client client){
client.startConnection("127.0.0.1", 6969);
String resp = client.sendMessage("hello");
tvInfo.setText(resp);
}
private void validate(String name, String password, TextView tvInfo){
if(name.equals("king_mageni") && password.equals("123456789")){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("username",name);
startActivity(intent);
}
else{
String errorMassage = "Incorrect username or password!";
tvInfo.setText(errorMassage);
}
}
}

Create a listener, pass value from a BroadcastReceiver

I'm with some doubt how I can execute one action.
When receive one income call, I want to pass the number for my class it manager the Bluetooth connection with Arduino.
After send the number, I'd like to send it by bluetooth connection
I tried use intent but maybe I am using deprecated version.
Android Api 7.1
Brodcaster Receiver Class
package com.jidea.glass;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class TelephonyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
try {
if (intent != null && intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
//Toast.makeText(context, "Outgoign call", 1000).show();
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
} else {
//get the phone state
String newPhoneState = intent.hasExtra(TelephonyManager.EXTRA_STATE) ? intent.getStringExtra(TelephonyManager.EXTRA_STATE) : null;
Bundle bundle = intent.getExtras();
if (newPhoneState != null && newPhoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//read the incoming call number
String phoneNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i("PHONE RECEIVER", "Telephone is now ringing " + phoneNumber);
//Toast.makeText(arg0, "Tele disponivel " + phoneNumber, Toast.LENGTH_LONG).show();
if(phoneNumber!=null | phoneNumber.equals("")){
PASS HERE TO BLUETOOTH
}
}
Bluetooth class
package com.jidea.glass;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.UUID;
public class CustomProcess extends AppCompatActivity
{
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//observable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
setContentView(R.layout.activity_custom_process);
//msg(address);
new ConnectBT().execute(); //Call the class to connect
}
public void isConnected() {//View view
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("Conectado".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
public void haveCall(String Phone) {//View view
Object aLig="Ligação \n"+Phone;
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(aLig.toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(CustomProcess.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Conectado");
isBtConnected = true;
isConnected();
}
progress.dismiss();
}
}
}
First you should create an intent in your BroadcastReceiver and then use LocalBroadcastManager in order to be able to send that intent wherever you want to listen.
val intent = Intent(ACTION)
intent.putExtra("DATA KEY", DATA)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
don't forget to register your broadcast receiver in where you want to listen
LocalBroadcastManager.getInstance(context).registerReceiver(your broadcast receiver instance, IntentFilter(ACTION))
I solved it done a Java Internal Listener with Interface the codes.
package com.jidea.glass;
public interface TelephonyListener
{
/**
* To call this method when new message received and send back
* #param message Message
*/
void callReceived(String message);
}
public class CustomProcess extends AppCompatActivity implements MessageListener, TelephonyListener
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MessageReceiver.bindListener(this);
TelephonyReceiver.bindListener(this);
Intent newint = getIntent();
address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
setContentView(R.layout.activity_custom_process);
//msg(address);
new ConnectBT().execute(); //Call the class to connect
#Override
public void messageReceived(String message)
{
Toast.makeText(this, "Nova Mensagem: " + message, Toast.LENGTH_SHORT).show();
}
#Override
public void callReceived(String message) {
Toast.makeText(this , "Tele disponivel " + message, Toast.LENGTH_LONG).show();
haveCall(message);
}
Continues in my class Receiver it extends BroadcastReceiver I Donw
public class TelephonyReceiver extends BroadcastReceiver
{
private static TelephonyListener mListener;
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
}
public static void bindListener(TelephonyListener listener){
mListener = listener;
}

NullPointerException with TCP Connection [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to implement a TCP connection for one of my projects. Following a few tutorials I found an example that is used quite often. I've been trying to make it work but even in a minimalistic project I'm getting an NullPointerException.
The Code for my MainActivity is as following:
package f.l.tcptest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
TcpClient mTcpClient;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ConnectTask().execute("");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTcpClient.sendMessage("testing");
}
});
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
TcpClient mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
}
And for the TCPClient:
package f.l.tcptest;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import static android.content.ContentValues.TAG;
public class TcpClient {
public static final String SERVER_IP = "192.168.1.102"; //server IP address
public static final int SERVER_PORT = 1337;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(final String message) {
Runnable runnable = new Runnable() {
#Override
public void run() {
if (mBufferOut != null) {
Log.d(TAG, "Sending: " + message);
mBufferOut.println(message + "\r\n");
mBufferOut.flush();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
/**
* Close the connection and release the members
*/
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
When i start the app, it connects to the server and maintains the connection. If i press the button to send the test message the app crashes and shows the following:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: f.l.tcptest, PID: 16391
java.lang.NullPointerException: Attempt to invoke virtual method 'void f.l.tcptest.TcpClient.sendMessage(java.lang.String)' on a null object reference
at f.l.tcptest.MainActivity$1.onClick(MainActivity.java:28)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
You declared the field in your activity, but you never initialize it. Check your AsyncTask's doInBackground method. You are creating a new local field called mTcpClient, you are not accessing the MainActivity's field. This is why you got NullPointException.
Here is the fixed code:
package f.l.tcptest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
TcpClient mTcpClient;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ConnectTask().execute("");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTcpClient.sendMessage("testing");
}
});
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
// You should use the global one, do not create the local instance if you want to use it on click event
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
}
Additional Note for Android:
But this approach is not good. You should follow best practices. Maybe you can use the intent service instead of AsyncTasks and sending message on UI thread.

Issues in Android app while sending string to Java Application

Was trying to make a simple application that receives text from speech API and send it over to a java server.Tried debugging from traces. The code does not go beyond TRY block where i opened my socket.
Code Updated : Now the application is not crashing.But no message flow.
package info.androidhive.speechtotext;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import static java.sql.DriverManager.println;
public class MainActivity extends Activity {
/**
* Declarations
*/
private TextView txtSpeechInput;
private ImageButton btnSpeak;
String str;
private final int REQ_CODE_SPEECH_INPUT = 100;
private String serverIpAddress = "";
private boolean connected = false;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
*/
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
str = result.get(0);
setContentView(R.layout.activity_main);
Log.d("1- naval", " client oncreate");
Button button = (Button) findViewById(R.id.send);
textIn = (TextView) findViewById(R.id.textin);
/**
* Setting the text box with default value
*/
textIn.setText(str);
Log.d("settext", " 2-naval");
/**
* Here we need to fill in textin from MainActivity,
* where we received the speech API text
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!connected) {
serverIpAddress = "192.168.0.4";
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
}
);
}
}
}
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8888);
PrintWriter out = null;
out.println(str);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
Since, at the time of writing this answer, the author has yet to add a stacktrace I'll go over some basic solutions:
Make sure you've added INTERNET permission to your android manifest, otherwise your socket wont open <uses-permission android:name="android.permission.INTERNET" />
Open your socket on a background thread. Networking on the UI thread (eg. inside the onClick method) is prohibited on android
Add a stack trace if the above didn't solve your problem

Nanohttpd in android do not serve files

i am developing a android application which uses nanohttpd to create a webserver my code do not give me any error but the server is not running because when i go to xx.xxx.xxx.xxx:8765/index.htm then it gives my no result this is my code:
Please Help...
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import dolphin.devlopers.com.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class AlertDialogActivity extends Activity {
private static final int PORT = 8765;
private MyHTTPD server;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
public class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
public Response serve( String uri, String method, Properties header, Properties parms, Properties files ) {
File rootsd = Environment.getExternalStorageDirectory();
File path = new File(rootsd.getAbsolutePath() + "/samer");
Response r = super.serveFile("/index.htm", header, path, true);
return r;
}
}
}
Looks like a simple fix --- in onResume() you create the server but you still need to call "start()" on it.

Categories