Socket object value is null [closed] - android

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm having trouble using the sockets library.
import java.io.*;
import java.net.*;
public class SocketAdapter{
Socket mySocket=null;
PrintWriter out=null;
BufferedReader in=null;
public SocketAdapter(String host,int port){
try {
InetAddress serverAddr = InetAddress.getByName(host);
mySocket = new Socket(serverAddr, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(mySocket.getOutputStream(), true);
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeto(String data){
out.println(data);
}
public String readdata(){
String fromSocket=null;
try {
fromSocket = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// blocking
return fromSocket;
}
public void close(){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I access this class via a 2nd thread in my main activity. In the debugger the value of mySocket is always null. I have no idea what I'm doing wrong but I'm pretty sure its something basic.
EDIT: Turns out it the sockets object was null because of an IOException triggered by the app not having internet permission.
in the manifest fixed it.

There's not much point in catching exceptions in constructors. It just misleads the rest of the code into assuming that the object has been completely constructed, when it hasn't. Change the constructor to throw those exceptions and remove all the try/catches, and catch the exceptions accordingly at the calling sites. Then you can never get a null Socket reference from this code again.

use Socket variable as static may be it will work.
static Socket mySocket = null;
or
use a separate function to get the socket Connection.
public Socket getSocketConnection(String strServerIP , int iPort)
{
try
{
Socket s = new Socket(strServerIP,iPort);
return s;
}
catch (Exception e)
{
return null;
}
}// End getSocketConnection Method.

If you are working multiple threads, you need to be synchronized over the contractor.
You can implement it by your self or define the SocketAdapter class instance as volotile.
Also please read this

Related

OutputStreamWrite is not appending to file

My OutputStreamWrite refuses to append to my file. It only overwrites the first line constantly.
The String lightRowValues are sent from another method that goes through a table and gets one row at a time, sends that row data here, where that row is written to this file. Then the method loops back and gets the next row. SO I should have a list of rows but instead only have one line of the very last entry.
public static void appendToLtCSV(String lightRowValues, String CSVFinalFileName){
try {
csvfos = new FileOutputStream(CSVFinalFileName, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter sensorCSVWriter = new OutputStreamWriter(csvfos);
try {
sensorCSVWriter.append(lightRowValues);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sensorCSVWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have set the append flag to true and still the same problem....

Problem in connection code

this is my class to connect and send commands to server i try separate connect code in method
but when i test the (SocketConnect) method i found it doesn't work.
my code
public class ConnAndSend {
static Socket socket = null;
static void SendCommand(String cmnd) {
DataOutputStream dataOutputStream = null;
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(cmnd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
};
}
// method to connect to server
static void SocketConnect(String SrvrIP,int SrvrPrt) {
// Socket socket = null;
try {
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}
Remove the static modifier!!
Remove all the occurances of the word static
In your code:
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
you are closing the socket in finally (why?) this is wrong also!
Have you made sure your manifest file has the correct permissions?
<uses-permission android:name="android.permission.INTERNET" />
It looks like you are closing the socket before you even get a chance to use it or you are'nt calling SocketConnect before . Do you see how you you make the socket, then you close it?
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
You need to make the socket, use it to connect in your SendCommand, then close it. I'm not quite sure why you need to keep the two separate, but I believe that is your problem, you are calling close before you use the socket to connect or you simply aren't making the socket and SendCommand is using "null" to connect.

android app connects to robot via ip address and port number

I need to code to connect between my android app and robot via ip address and port number using wifi connection.
I have part of code but I think that it need to commands to create connection.
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.10.5", 2525);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
You should call flush on your output stream after writing.
Also, close the streams before closing the socket in the finally block.
What is you problem exactly ?
Did you look at the logs on the server side to see if connection was established ?
Do you see that your server accepts the connection ?
Do you reecive any data on the server side ?
Regards,
Stéphane

Android: how to take over message loop of Activity, like GetMessage/PostMessage in Win32?

My original goal is to build my own modal dialog. At some point, I have to run an inner loop, which would do really close to what GetMessage/PostMessage do in Win32, if you got Win32 experience then you are quite familiar with this. The inner loop will block current workflow but still process events. The pseudo code would be like,
private void doModal() {
doSth();
// start loop and process events
while (!isQuit) {
Message msg = nextMessage();
// process all wanted msgs, and simply discard all unexpected msgs
if (isWantedMsg) {
sendToTarget(msg);
}
}
}
I've looked into source code, Looper.loop(), which was,
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next(); // might block
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
msg.target.dispatchMessage(msg);
msg.recycle();
}
}
}
Basically I'd like to write such a loop, then I'm able to receive all msgs and process or drop them accordingly. Unfortunately, MessageQueue belongs to package android.os, I have no privilege to access most of its interfaces. Activity.dispatchTouchEvent is just a handler, not my case.
How could I do? Thanks.
==========================SOLUTION=====================================
I solved it by reflection, I exactly copied source of Looper.loop(), see below,
private void startModal() {
Class clsMsgQueue = null;
Method nextMethod = null;
Class clsMsg = null;
mQuitModal = false;
MessageQueue queue = Looper.myQueue();
clsMsgQueue = queue.getClass();
try {
nextMethod = clsMsgQueue.getDeclaredMethod("next", new Class[]{});
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nextMethod.setAccessible(true);
while (!mQuitModal) {
Message msg = null;
try {
msg = (Message)nextMethod.invoke(queue, new Object[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (msg != null) {
clsMsg = msg.getClass();
Field targetFiled = null;
try {
targetFiled = clsMsg.getDeclaredField("target");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
targetFiled.setAccessible(true);
Handler target = null;
try {
target = (Handler) targetFiled.get(msg);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (target == null) {
// No target is a magic identifier for the quit message.
mQuitModal = true;
}
target.dispatchMessage(msg);
msg.recycle();
}
}
}
When dialog was dismissed, mQuitModal was set to true either.
If don't care much about performance issue, it worked.
Sorry, Android deliberately does not support nested event loops like this. You just will have to structure your code a different way -- for dialogs you will typically start the dialog, return to the event loop, and implement callbacks to handle the result from it.

StreamCorruptedException with Android-Java Communication

I need to send serialized Data from an Android Device to a Java Server.
I don't know why, but the communication seems to be very unstable. In the Debugger, the java.io.StreamCorruptedException: is thrown immediately after the start. not one Object is passing.
Without the debugger, nearly 10 Messages are passed until the same Exception is thrown.
Anyone got an idea, please help me:)
Thank you!
Fabian
Exception:
java.io.StreamCorruptedException: invalid type code: 2F
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at androidAnbindung.AndroidVerwalter.run(AndroidVerwalter.java:114)
java-code:
public void Nachrichtenaustausch(){
port ++;
try {
serverSocket = new java.net.ServerSocket(port);
System.out.println("Warte auf 2. Verbindungsaufbau...");
client = serverSocket.accept();
System.out.println("Verbindung 2 ist eingegangen...");
in = new ObjectInputStream(new ObjectInputStream(client.getInputStream()));
Nachricht n;
// starte den regulären Verkehr mit dem Androidgerät
new Thread(this).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
Nachricht speicher;
while (true) {
try {
speicher = (Nachricht) in.readObject();
if (speicher != null) {
System.out.println(speicher.getName()+"..............................."+speicher.getWerte().get(0));
}synchronized (objekliste) {
for (AndroidObject ao : this.objekliste) {
if (speicher.getName().equals(ao.name)) {
ao.abstrakter_Wert = speicher.getAktuellerWert();
if (speicher.getWerte()!=null) {
ao.werte = speicher.getWerte();
}
}
}
}
Thread.sleep(50);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
}
}
}
and the android thread:
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
if (!nachrichtenliste.isEmpty()) {
Nachricht speicher = nachrichtenliste.get(0);
try {
out.writeObject(speicher);
out.flush();
synchronized (nachrichtenliste) {
nachrichtenliste.remove(speicher);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Thread.sleep(50);
handler.post(this);
}
} catch (Exception e) {
// TODO: handle exception
}
}
I can imagine that Android and Java are not exactly serialization compatible here. So that one side sends a code that the other does not expect.
I'd rather go with some more textual protocol (json, xml) here, than with serialization.

Categories

Resources