I'm trying to get strings from my Arduino with my Android phone, everything goes well except for when I press my updatebutton the second time, it unfortunately stops.
I can't seem to track the problem and I ran out of options so I'm asking for help to you guys now.
package com.TRY.udp2;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private String rcvStr, serverIP="192.168.0.15";
private TextView textLog;//Log for outputs
private EditText textMsg;
Button updateButton;//(dis)connect Button
Boolean connected=false;//stores the connectionstatus
DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button updateButton = (Button) findViewById(R.id.updateButton);
textMsg = (EditText) findViewById(R.id.textMsg);
textLog = (TextView) findViewById(R.id.textLog);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String textlogMsg = textMsg.getText().toString();
new synchTask().execute(textlogMsg);
}
});
}
private class synchTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String msg=params[0].toString();
InetAddress toAddress = null;
try
{
toAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
int port=5000;
DatagramSocket dtSocket = null;
try
{
dtSocket = new DatagramSocket(port);
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] dataBytes = msg.getBytes();
DatagramPacket sndPacket = new DatagramPacket(dataBytes, dataBytes.length, toAddress, port);
try
{
dtSocket.send(sndPacket);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
return rcvStr;
}
protected void onPostExecute(String result) {
textLog.setText(rcvStr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and if there's a better way of getting strings from arduino please help out.
You probably need to close dtSocket at the end of doInBackground(). Otherwise you will try to create a socket on a bound port when you execute it the second time.
Related
Hello I am trying to write simple client-server application in android.Here is my code for the client.
package com.sudarshan.client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("10.0.2.2", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
Here is the code for server
package com.sudarshan.server;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
The server code crashes.It gives a error as "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sudarshan.server/com.sudarshan.server.MainActivity}: android.os.NetworkOnMainThreadException".
What am i doing wrong?
Solved.
"android.os.NetworkOnMainThreadException" means that Network related tasks are not to be done on main thread directly ie. Activity Class.So, need to make a thread under main thread then do the work.
I'm creating an an Android Application which connects to Python Server and send UP and DOWN command and a Python code response like: light is ON and Light is Off.
Although I add a button to Android application which sends data to Python and a Python server sends back some string or a function to the Android app which shows up in Android TextView (I need to run a function on Raspberry and get the result back to Android in textView).
enter code here
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Button btnUp;
Button btnDown;
Button rButton;
EditText txtAddress;
Socket myAppSocket = null;
public static String wifiModuleIp = "";
public static int wifiModulePort = 0;
public static String CMD = "0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUp = (Button) findViewById(R.id.btnUP);
btnDown = (Button) findViewById(R.id.btnDown);
rButton = (Button) findViewById(R.id.rButton);
txtAddress = (EditText) findViewById(R.id.ipAddress);
btnUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "UP";
Soket_AsyncTask cmd_increase_servo = new Soket_AsyncTask();
cmd_increase_servo.execute();
}
});
btnDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "DOWN";
Soket_AsyncTask cmd_decrease_servo = new Soket_AsyncTask();
cmd_decrease_servo.execute();
}
});
rButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "VIEW";
Socket_Received cmd_received_pi = new Socket_Received();
cmd_received_pi.execute();
}
});
}
public void getIPandPort() {
String iPandPort = txtAddress.getText().toString();
String temp[] = iPandPort.split(":");
wifiModuleIp = temp[0];
wifiModulePort = Integer.valueOf(temp[1]);
//Log.d("MYTEST","IP String" +iPandPort);
//Log.d("MY TEST","IP:"+wifiModuleIp);
// Log.d("MY TEST","PORT"+wifiModulePort);
}
public class Soket_AsyncTask extends AsyncTask<Void, Void, Void> {
Socket socket;
protected Void doInBackground(Void... params) {
try {
InetAddress inetAdress = InetAddress.getByName(MainActivity.wifiModuleIp);
socket = new java.net.Socket(inetAdress, MainActivity.wifiModulePort);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeBytes(CMD);
dataOutputStream.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class Socket_Received extends AsyncTask<String, Void, Void> {
ServerSocket cScoket;
Socket socket;
//public TextView textView;
private DataInputStream in;
#SuppressLint("WrongThread")
protected Void doInBackground(String... params) {
try {
cScoket = new ServerSocket(MainActivity.wifiModulePort);
socket = cScoket.accept();
in = new DataInputStream(socket.getInputStream());
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
final TextView textView = (TextView)findViewById(R.id.txtView);
textView.setText(br.toString());
socket.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
My Python code here:
enter code here
import lighton
from socket import *
from time import ctime
import time
lighton.setUP()
ctrCmd = ['UP','DOWN','VIEW']
HOST = ''
PORT = 5555
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
tcpCliSock,addr = tcpSerSock.accept()
time.sleep(.05)
data = ''
data = tcpCliSock.recv(BUFSIZE).decode()
if not data:
print("there is no data")
break
if data == ctrCmd[0]:
lighton.ledOn()
if data == ctrCmd[1]:
lighton.ledOff()
if data == ctrCmd[2]:
r="hello world"
tcpCliSock.send(r.encode())
tcpSerSock.close();
My Python light on class code here:
import time
def setUP():
print("Setting up...")
def ledOn():
print("led is on")
def ledOff():
print("led is off")
if __name__ == '__main__':
setup()
If I run my app in the emulator my app crashes immediately. I get the error 'Caused by: java.lang.IllegalArgumentException: host=null, port=4444.' Logcat says the error comes from InetSocketAdress. This is my server code:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* Created by Charlie on 26-3-2015.
*/
public class Server extends AsyncTask<Void, Void, String> {
private String message;
private String ip;
public static int port = 4444;
private String serverResponse = null;
public Server(String ip, int port, String message ) {
super();
//IP, Port en bericht om naar server te sturen
this.message = message;
this.ip = ip;
this.port = port;
}
#Override
protected String doInBackground(Void... params) {
try {
Socket serverSocket = new Socket();
serverSocket.connect(new InetSocketAddress(this.ip, this.port), 4444);
this.sendMessage(message, serverSocket);
InputStream input;
try {
input = serverSocket.getInputStream();
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(input));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();
this.serverResponse = stringBuilder.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Response: " + serverResponse);
} catch (UnknownHostException e) {
Log.d("debug", "can't find host");
} catch (SocketTimeoutException e) {
Log.d("debug", "time-out");
} catch (IOException e) {
e.printStackTrace();
}
return serverResponse;
}
private void sendMessage(String message, Socket serverSocket) {
OutputStreamWriter outputStreamWriter = null;
try {
outputStreamWriter = new OutputStreamWriter(serverSocket.getOutputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
if (outputStreamWriter != null) {
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
PrintWriter writer = new PrintWriter(bufferedWriter, true);
writer.println(message);
}
}
}
The code of the class where the user can fill in the IP:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.ExecutionException;
public class GebruikerIP extends Activity {
private Boolean serverCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Slotenbedrijf De Sleutelaar");
//Check voor internet verbinding
if(NetwerkCheck.isInternetAvailable(GebruikerIP.this))
{
}
else
{
Toast.makeText(GebruikerIP.this, "Er is helaas geen internetverbinding geconstateerd, daarom wordt nu de laatst opgehaalde informatie getoond.!", Toast.LENGTH_LONG).show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gebruikerip);
Button ipButton = (Button) findViewById(R.id.serverbutton);
ipButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
verbindServer();
}
});
//Enter key afvangen
EditText ipInvoer = (EditText) findViewById(R.id.ipinvoeren);
ipInvoer.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_ENTER:
verbindServer();
break;
default:
return false;
}
return true;
}
});
}
//server connectie maken voor ophalen van diensten
public void verbindServer() {
TextView ipVeld = (TextView) findViewById(R.id.ipinvoeren);
String ip = ipVeld.getText().toString();
Log.i("ip", ip);
String response = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("slotenlijst", "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
try {
response = new Server(ip,
4444, jsonObject.toString()).execute().get();
//exceptions afvangen
} catch (InterruptedException e)
{
}
} catch (ExecutionException e1)
{
}
if (response == null) {
serverCheck = false;
Toast.makeText(this, "Verbinden met server mislukt, staat server aan?", Toast.LENGTH_LONG).show();
} else {
//doorgaan naar MainActivity
serverCheck = true;
HoofdschermFragment.serverIp = ip;
Intent startApp = new Intent(this, MainActivity.class);
startActivity(startApp);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_gebruiker_ip, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
I can't find out how I can fix this error. Help would me appreciated. Thanks!
change it to
InetAddress inetServer = InetAddress.getByName(IP);
than
Socket socket = new Socket(inetServer, devicePort);
and if you are using for Server Socket than use below line
ServerSocket socket = new ServerSocket(devicePort,int backlognumber, inetServer);
I'm trying to develop a simple app that gets data from web service and displays it
It throws exception exactly when he calls response.execute(client)
package com.example.webbasedapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class GETMethods {
public String getInternetData() throws Exception{
BufferedReader in=null;
String Data=null;
try{
HttpClient client=new DefaultHttpClient();
URI web=new URI("http://www.mybringback.com/");
HttpGet request = new HttpGet();
request.setURI(web);
HttpResponse reponse=client.execute(request);
Log.v("response code", reponse.getStatusLine()
.getStatusCode() + "");
InputStream inp=reponse.getEntity().getContent();
in=new BufferedReader(new InputStreamReader(inp));
StringBuffer buf=new StringBuffer();
String l="";
String nl=System.getProperty("line.separator");
while((l=in.readLine())!=null){
buf.append(l+nl);
}
in.close();
Data=buf.toString();
return Data;
}finally{
if(in!=null){
try{
in.close();
return Data;
}catch (Exception e){
Log.d("error",e.toString());
}
}
}
}
}
And this is my main activity
package com.example.webbasedapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
TextView test = (TextView) findViewById(R.id.data);
GETMethods data = new GETMethods();
String d = null;
try {
d = data.getInternetData();
// test.setText(d);
} catch (Exception e) {
// TODO Auto-generated catch block
d = "bla";
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
// Log.d("testW",e.getMessage());
}
test.setText(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
You are attempting to access the network on the UI thread which is not allowed due to potential hangup issues. Look into AysncTask and implement GETMethods as one of them. It will look something like this:
public class GETMethods extends AsyncTask<String, Void, String>{
protected void doInBackground(String... params){
YourNetworkCode
}
}
package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
new Incomingdata().execute();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
private class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
setMyIp(ipaddress.getText().toString());
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
while(s.isConnected())
{
String input =r.nextLine();
System.out.println(""+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
So this is where i am, i can flush data out but can not seem to receive it back in from the server i am fairly new at this and have got help in the past from this site. I am really stuck and running out of time
Any help would be great
And Thank you
There are two different types of Socket, one is used for connecting to a host, and the other one is used to listen for connections. What you want to do is before trying to connect, make a ServerSocket that listens to incoming connections to a specific port number and wait for a new connection, as such:
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
This should be done in your AsyncTask before trying to connect to it (accept() is blocking so it will wait for an incoming connection). So, changing the following two lines with the above and calling the AsyncTask before trying to connect to it should do the trick:
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);