I'm trying to make a connection between my galaxy tab and my laptop. So I'm trying to run server activity on my laptop and client activity on my tab, but it doesn't work. Here is the server and client code. Where is the mistake?
SERVER:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = (TextView)findViewById(R.id.textView1);
int port = 12345;
byte [] message = new byte [1500];
DatagramPacket p = new DatagramPacket (message,message.length);
try {
InetAddress serveraddr = InetAddress.getByName("192.168.1.116");
DatagramSocket s = new DatagramSocket (port,serveraddr);
while (true){
s.receive(p);
String text = new String (message,0,p.getLength());
txt.setText(text);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CLIENT:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edt = (EditText)findViewById(R.id.editText1);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String msg = edt.getText().toString();
int port = 12345;
try {
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("192.168.1.116");
int msg_lenght = msg.length();
byte []message = msg.getBytes();
DatagramPacket p = new DatagramPacket(message,msg_lenght,local,port);
s.send(p);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Here is the log:
09-17 23:49:55.190: D/dalvikvm(5892): Late-enabling CheckJNI 09-17
23:49:55.690: D/CLIPBOARD(5892): Hide Clipboard dialog at Starting
input: finished by someone else... ! 09-17 23:49:59.590:
D/AndroidRuntime(5892): Shutting down VM 09-17 23:49:59.590:
W/dalvikvm(5892): threadid=1: thread exiting with uncaught exception
(group=0x40c4f1f8) 09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL
EXCEPTION: main 09-17 23:49:59.590: E/AndroidRuntime(5892):
android.os.NetworkOnMainThreadException 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
libcore.io.IoBridge.sendto(IoBridge.java:463) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
java.net.DatagramSocket.send(DatagramSocket.java:307) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
com.example.udpclient.MainActivity$1.onClick(MainActivity.java:36)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
android.view.View.performClick(View.java:3620) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.view.View$PerformClick.run(View.java:14322) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Handler.handleCallback(Handler.java:605) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Handler.dispatchMessage(Handler.java:92) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Looper.loop(Looper.java:137) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.app.ActivityThread.main(ActivityThread.java:4507) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
java.lang.reflect.Method.invokeNative(Native Method) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
java.lang.reflect.Method.invoke(Method.java:511) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
dalvik.system.NativeStart.main(Native Method) 09-17 23:50:34.320:
I/Process(5892): Sending signal. PID: 5892 SIG: 9
09-17 23:49:59.590: E/AndroidRuntime(5892): android.os.NetworkOnMainThreadException
09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-17 23:49:59.590: E/AndroidRuntime(5892): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
You shouldn't do network or time intensiv operations in ui thread
See also:
Android: NoClassDefFoundError for some app users or
android developers information
Checkout:
activity.runOnUi
You have an infinite loop in onCreate of the Server. You shouldn't! Create a thread for polling the socket.
you cannot send udp packets on ui thread, so a new seperate thread must be created.
Just a quick solution...
create a udpOutputData string:
String udpOutputData;
create a new thread in your code:
//-----UDP send thread
Thread udpSendThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(100);
}
catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (sendUdp == true) {
try {
// get server name
InetAddress serverAddr = InetAddress.getByName(outputIP);
Log.d("UDP", "C: Connecting...");
// create new UDP socket
DatagramSocket socket = new DatagramSocket();
// prepare data to be sent
byte[] buf = udpOutputData.getBytes();
// create a UDP packet with data and its destination ip & port
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, broadcastPort);
Log.d("UDP", "C: Sending: '" + new String(buf) + "'");
// send the UDP packet
socket.send(packet);
socket.close();
Log.d("UDP", "C: Sent.");
Log.d("UDP", "C: Done.");
}
catch (Exception e) {
Log.e("UDP", "C: Error", e);
}
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendUdp = false;
}
}
}
});
create a method to call everytime you want to send some udp data:
public void sendUdp(String udpMsg) {
udpOutputData = udpMsg;
sendUdp = true;
}
call the method and pass a string for the output data everytime you want to send a udp packet:
String s = "hello from app";
sendUdp(s);
Have 2 problems with your code
Work with Network on Main thread (UI Thread)
09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL EXCEPTION: main
09-17 23:49:59.590: E/AndroidRuntime(5892):
android.os.NetworkOnMainThreadException
Loop while(true) on the Main thread:
while(true) {
s.receive(p);
String text = new String (message,0,p.getLength());
txt.setText(text);
}
Related
I try my app on acer Z120 smartphone (vers. Android 4.1.1) and I have this runtime error:
09-09 12:03:24.827: W/dalvikvm(6414): threadid=11: thread exiting with uncaught exception (group=0x419af908)
09-09 12:03:24.830: E/AndroidRuntime(6414): FATAL EXCEPTION: Thread-546
09-09 12:03:24.830: E/AndroidRuntime(6414): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
09-09 12:03:24.830: E/AndroidRuntime(6414): at android.os.Handler.<init>(Handler.java:121)
09-09 12:03:24.830: E/AndroidRuntime(6414): at android.app.Dialog.<init>(Dialog.java:107)
09-09 12:03:24.830: E/AndroidRuntime(6414): at android.app.AlertDialog.<init>(AlertDialog.java:114)
09-09 12:03:24.830: E/AndroidRuntime(6414): at android.app.AlertDialog$Builder.create(AlertDialog.java:913)
09-09 12:03:24.830: E/AndroidRuntime(6414): at android.app.AlertDialog$Builder.show(AlertDialog.java:931)
09-09 12:03:24.830: E/AndroidRuntime(6414): at aqua.example.aquasalt.MainActivity.setAlertMsg(MainActivity.java:753)
09-09 12:03:24.830: E/AndroidRuntime(6414): at aqua.example.aquasalt.MainActivity$ConnectedThread.run(MainActivity.java:250)
09-09 12:03:24.931: W/MMUMapper(6414): fail to register MVA, unsupported format(0x5)
App works well on my smartphone (Samsung Galaxy S Advance).
Can I do?
You are attempting to show a dialog in a background thread. Only the main UI thread may show dialogs and touch the UI otherwise.
To post a Runnable to the main UI thread handler, you can use runOnUiThread() in an activity.
This is my code:
public void connect() {
// address is public variable
BluetoothDevice device = myBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
}
myBluetoothAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
connesso = true;
} catch (IOException e) { //here I have exception
try {
btSocket.close();
connesso = false;
} catch (IOException e2) {}
}
if(connesso){
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
BluetoothSocket socket = null;
if (Build.VERSION.SDK_INT >= 10) {
try {
socket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
} catch (Exception e) {
System.out.println(e);
}
}
return socket;
}
This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 9 years ago.
The idea is when the TCP server receives a String message, if it is equal to "::turnOnBluetoothOn::". Will simply turn on the bluetooth on the device. By using the runCommand Method of the MessageHandler class. The problem is that I am getting the error Can't create handler inside thread that has not called Looper.prepare()
Here is my code:
import android.os.Looper;
import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClient
{
private String serverMessage;
// <<<<<<< .mine
public static final String SERVERIP = "xx.xxx.xx.xx"; // your computer IP
public static final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedReader in;
// Test for Thread
private volatile Looper mMyLooper;
/**
* 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(String message)
{
if (out != null && !out.checkError())
{
out.println(message);
out.flush();
}
}
public void stopClient()
{
mRun = false;
}
public void run()
{
mRun = true;
try
{
// here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
// create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try
{
// send the message to the server
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
// receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// in this while the client listens for the messages sent by the
// server
while (mRun)
{
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null)
{
// call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
System.out.println(serverMessage);
MessageHandler handler = new MessageHandler(serverMessage);
handler.runCommand();
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '"
+ serverMessage + "'");
} 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);
}
}
//AND THIS IS THE HANDLER CLASS
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
public class MessageHandler extends Activity
{
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private String Instruction;
MessageHandler(String Command)
{
Instruction = Command;
}
public void runCommand()
{
if (Instruction.equals("::turnBluetoothOn::"))
{
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
return;
}
}
}
Update:
Here is the LogCat:
03-01 18:16:09.486: I/System.out(4752): ::turnBluetoothOn::
03-01 18:16:09.526: D/AndroidRuntime(4752): Shutting down VM
03-01 18:16:09.526: W/dalvikvm(4752): threadid=1: thread exiting with uncaught exception (group=0x4193a700)
03-01 18:16:09.546: E/AndroidRuntime(4752): FATAL EXCEPTION: main
03-01 18:16:09.546: E/AndroidRuntime(4752): java.lang.NullPointerException
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.example.myactivity.MessageHandler.runCommand(MessageHandler.java:22)
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.example.myactivity.TCPClient$1.run(TCPClient.java:108)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.os.Handler.handleCallback(Handler.java:730)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.os.Handler.dispatchMessage(Handler.java:92)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.os.Looper.loop(Looper.java:137)
03-01 18:16:09.546: E/AndroidRuntime(4752): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-01 18:16:09.546: E/AndroidRuntime(4752): at java.lang.reflect.Method.invokeNative(Native Method)
03-01 18:16:09.546: E/AndroidRuntime(4752): at java.lang.reflect.Method.invoke(Method.java:525)
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-01 18:16:09.546: E/AndroidRuntime(4752): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-01 18:16:09.546: E/AndroidRuntime(4752): at dalvik.system.NativeStart.main(Native Method)
try this:
if (serverMessage != null && mMessageListener != null)
{
// call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
MessageHandler handler = new MessageHandler(serverMessage);
handler.runCommand();
}
});
}
According to the error information,you create handler inside a non-ui thread, you have declared mMyLooper,why not use it?
so my advice is that add this code:
mMyLooper = Looper.getMainLooper();
Looper.prepare();
before while (mRun).
I have a thread class when I start the thread and create the instance of thread class in the main class my app get crash. My main activity code for creating the thread is:
broadcast broadcastobject=new broadcast(messages);
broadcastobject.start();
My thread class is :
public class broadcast extends Thread {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public broadcast(String to) {
// TODO Auto-generated constructor stub
str = to;
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// socket.setSoTimeout(TIMEOUT_MS);
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My log cat error is:
09-01 08:23:47.949: D/gralloc_goldfish(1720): Emulator without GPU emulation detected.
09-01 08:24:01.941: W/System.err(1720): java.net.SocketException: socket failed: EACCES (Permission denied)
09-01 08:24:01.941: W/System.err(1720): at libcore.io.IoBridge.socket(IoBridge.java:573)
09-01 08:24:01.979: W/System.err(1720): at java.net.PlainDatagramSocketImpl.create(PlainDatagramSocketImpl.java:91)
09-01 08:24:01.979: W/System.err(1720): at java.net.DatagramSocket.createSocket(DatagramSocket.java:131)
09-01 08:24:01.979: W/System.err(1720): at java.net.DatagramSocket.<init>(DatagramSocket.java:78)
09-01 08:24:01.989: W/System.err(1720): at soft.b.peopleassist.broadcast.run(broadcast.java:65)
09-01 08:24:01.989: W/System.err(1720): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
09-01 08:24:01.999: W/System.err(1720): at libcore.io.Posix.socket(Native Method)
09-01 08:24:01.999: W/System.err(1720): at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:169)
09-01 08:24:01.999: W/System.err(1720): at libcore.io.IoBridge.socket(IoBridge.java:558)
09-01 08:24:02.009: W/System.err(1720): ... 4 more
09-01 08:24:02.149: W/dalvikvm(1720): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
09-01 08:24:02.149: E/AndroidRuntime(1720): FATAL EXCEPTION: Thread-114
09-01 08:24:02.149: E/AndroidRuntime(1720): java.lang.NullPointerException
09-01 08:24:02.149: E/AndroidRuntime(1720): at soft.b.peopleassist.broadcast.run(broadcast.java:92)
09-01 08:24:03.329: W/IInputConnectionWrapper(1720): showStatusIcon on inactive InputConnection
The thread is not the issue, the real issue is the EACCES (Permission denied), add this permission to your manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
This question already has an answer here:
Application crashes while starting the new thread
(1 answer)
Closed 9 years ago.
I have a class where I have implemented runnable and I start the thread in one of the function of this class, and I call this function from the main activity,I create the object of this class and call the method of thread class.My main activity code from where I call this class method is:
broadcast broadcastobject.threadfunc(messages);
My class where I create threads is:
public class broadcast {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public void threadfunc(String message){
str=message;
new Thread(new ClientThread()).start();
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My log cat is:
08-31 21:55:56.277: D/gralloc_goldfish(1669): Emulator without GPU emulation detected.
08-31 21:56:02.467: D/AndroidRuntime(1669): Shutting down VM
08-31 21:56:02.467: W/dalvikvm(1669): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-31 21:56:02.517: E/AndroidRuntime(1669): FATAL EXCEPTION: main
08-31 21:56:02.517: E/AndroidRuntime(1669): java.lang.NullPointerException
08-31 21:56:02.517: E/AndroidRuntime(1669): at soft.b.peopleassist.Send$1.onClick(Send.java:113)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View.performClick(View.java:3480)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View$PerformClick.run(View.java:13983)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.handleCallback(Handler.java:605)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Looper.loop(Looper.java:137)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-31 21:56:02.517: E/AndroidRuntime(1669): at dalvik.system.NativeStart.main(Native Method)
This simply means that the emulator you are using does not have GPU emulation enabled. In Android SDK Tools R15 you can enable GPU emulation.You need to create a new emulator virtual device and set GPU emulation to true in Hardware properties.
I am new to android programming.I have been trying to establish connection between two emulators.While my server emulator is up and running,client has a problem.Here is the code and logcat error description.Please tell me the error in this.
public class SocketClient extends Activity
{
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "192.168.0.5";
private static final int REDIRECTED_SERVERPORT = 5000;
public void connect()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
tv.setText((CharSequence) serverAddr);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
System.out.println("Here");
}
catch (IOException e1)
{
e1.printStackTrace();
System.out.println("Here too");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
connect();
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception e)
{
tv.setText("Error3");
e.printStackTrace();
}
}
}
);
}
}
The logcat error is
01-31 04:42:51.170: W/dalvikvm(529): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-31 04:42:51.187: E/AndroidRuntime(529): FATAL EXCEPTION: main
01-31 04:42:51.187: E/AndroidRuntime(529): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.ServerClient/com.app.ServerClient.SocketClient}: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Looper.loop(Looper.java:137)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invoke(Method.java:511)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-31 04:42:51.187: E/AndroidRuntime(529): at dalvik.system.NativeStart.main(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): Caused by: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.connect(SocketClient.java:25)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.onCreate(SocketClient.java:48)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Activity.performCreate(Activity.java:4465)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-31 04:42:51.187: E/AndroidRuntime(529): ... 11 more
Thanks in advance.
Thank You David and Jitendra.
I corrected the error and I get a nullPointerException in one part of the code.What did I do wrong?
public void onClick(View v)
{
try // The error is in this block
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception f) // I get the error here. java.lang.NullPointerException
{
tv.setText("Error3");
tv.setText(f.toString());
f.printStackTrace();
}
}
Your error is on this line:
tv.setText((CharSequence) serverAddr);
serverAddr is of type InetAddress, and you're trying to cast it to a CharSequence which cannot be done. Perhaps you meant:
tv.setText(serverIpAddress);
Exception is in following line:
tv.setText((CharSequence) serverAddr);
and it is because you are trying to cast serverAddr into CharSequence.
If you really want to print serverAddr use
tv.setText((CharSequence) serverAddr.toString());