android socket client/server disconnect - java

I'm writing a simple client server for android, it works super until I reran the client. Then nothing happens. The server runs continuously and the client must be connected and disconnected. Any some help would be very useful. Thank you.
Server
public class MyService extends Service {
String line = null;
String temp_comand = null;
Socket client;
public static String SERVERIP = "10.0.2.15";
public final static int DISPATCH_KEY_FROM_IME = 1011;
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.i("SERVISE", "STARTED");
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
Log.v("wlan0", Utils.getMACAddress("wlan0"));
Log.v("eth0", Utils.getMACAddress("eth0"));
Log.v("<< IP4 >>", Utils.getIPAddress(true));
Log.v("<< IP6 >>", Utils.getIPAddress(false));
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// LISTEN FOR INCOMING CLIENTS
client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
if (line.equals("next")){
simulateKey(22);
}
if (line.equals("beack")){
simulateKey(21);
}
if (line.equals("up")){
simulateKey(19);
}
if (line.equals("down")){
simulateKey(20);
}
if (line.equals("ok")){
simulateKey(23);
}
if (line.equals("power")){
simulateKey(170);
}
if (line.equals("exit")){
simulateKey(4);
}
if (line.equals("vol_m")){
simulateKey(25);
}
if (line.equals("vol_up")){
simulateKey(24);
}
if (line.equals("menu")){
simulateKey(82);
}
if (line.equals("left")){
simulateKey(88);
}
if (line.equals("right")){
simulateKey(87);
}
if (line.equals("home")){
simulateKey(3);
}
if (line.equals("close")){
simulateKey(4);
}
// Log.d("ServerActivity", line);
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
}
});
e.printStackTrace();
}
}
}
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
public void simulateKey(final int KeyCode) {
new Thread() {
#Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyCode);
} catch (Exception e) {
Log.e("Exception when sendKeyDownUpSync", e.toString());
}
}
}.start();
}
}
Client
public class ClientActivity extends Activity {
String comand = "Жду команду";
private Button right, left, up, dn, menu, pow, min, plus, ok, sw_l, sw_r, close, home;
private String serverIpAddress = "";
String serverIp;
Socket socket;
private boolean connected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.client);
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
serverIp = Formatter.formatIpAddress(dhcp.gateway);
if (!connected) {
serverIpAddress = serverIp;
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
right = (Button) findViewById(R.id.btn_right);
left = (Button) findViewById(R.id.btn_left);
up= (Button) findViewById(R.id.btn_up);
dn= (Button) findViewById(R.id.btn_dn);
menu= (Button) findViewById(R.id.btn_menu);
pow= (Button) findViewById(R.id.btn_pow);
min= (Button) findViewById(R.id.btn_min);
plus= (Button) findViewById(R.id.btn_plus);
ok= (Button) findViewById(R.id.btn_ok);
sw_l= (Button) findViewById(R.id.btn_sw_left);
sw_r= (Button) findViewById(R.id.btn_sw_rig);
close = (Button) findViewById(R.id.btn_close);
home= (Button) findViewById(R.id.btn_home);
Log.e("KeyEvent.KEYCODE_HOME", String.valueOf(KeyEvent.KEYCODE_HOME));
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "next";
}});
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "beack";
}});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "up";
}});
dn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "down";
}});
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "menu";
}});
pow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "power";
}});
min.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "vol_m";
}});
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "vol_up";
}});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "ok";
}});
sw_l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "left";
}});
sw_r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "right";
}});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "home";
}});
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "close";
}});
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, 8080);
connected = true;
while (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
if(out.checkError())
{Log.d("ClientActivity", "Error transmitting data");
throw new Exception("Error transmitting data.");
}
if (comand.equals("next")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("beack")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("up")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("down")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("ok")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("power")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("exit")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("vol_m")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("vol_up")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("menu")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("left")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("right")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("home")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("close")){
out.println(comand);
comand = "Жду";
}
} 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;
}
}
}
protected String wifiIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
// Convert little-endian to big-endianif needed
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
} catch (UnknownHostException ex) {
Log.e("WIFIIP", "Unable to get host address.");
ipAddressString = null;
}
return ipAddressString;
}
}

If the client does not disconnect the server stays in this loop: while ((line = in.readLine()) != null) waiting and waiting for the next line. In the mean time no other client can connect.

Related

Why am I getting a java.lang.NullPointerException error in a wifip2p connection

Here is the error - java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.wdchat.MainActivity$SendReceive.write(byte[])' on a null object reference.
I have included my mainactivity class code and wifibroadcastreceover class code as well. The code is actually from wifip2p tutorial on youtube made by sarthi technology
Here is my MainActivity class.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
AppCompatEditText editText;
ImageView wifi_on_off_iv, wifi_descovery_iv, send_btn_iv, save_ic_iv, brd_msg_iv;
TextView username, sentMessage, connectionStatus, tallytext, tallyno;
WifiManager wifiManager;
WifiP2pManager p2pManager;
WifiP2pManager.Channel mchannel;
String messageText;
LinearLayout nestedLinearlayout;
ListView listView;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
BroadcastReceiver broadcastReceiver;
IntentFilter intentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] devicenameArray;
WifiP2pDevice[] wifiP2pDeviceArray;
static final int MESSAGE_READ = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
switch (message.what){
case MESSAGE_READ:
byte[] readBuff = (byte[]) message.obj;
String temMsg = new String(readBuff, 0, message.arg1);
sentMessage.setText(temMsg);
break;
}
return true;
}
});
private void exqListener() {
wifi_on_off_iv.setOnClickListener(view -> {
if (wifiManager.isWifiEnabled()) {
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
wifiManager.setWifiEnabled(false);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
} else {
wifiManager.setWifiEnabled(true);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
}
});
wifi_descovery_iv.setOnClickListener(view -> p2pManager.discoverPeers(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText(R.string.discovery_on);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.purple_500));
}
#Override
public void onFailure(int i) {
connectionStatus.setText(R.string.discovery_off);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red));
}
}));
p2pManager.createGroup(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int i) {
}
});
listView.setOnItemClickListener((adapterView, view, i, l) -> {
final WifiP2pDevice device = wifiP2pDeviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
p2pManager.connect(mchannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected to " + device.deviceName, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int i) {
Toast.makeText(MainActivity.this, "Not connected", Toast.LENGTH_SHORT).show();
}
});
});
send_btn_iv.setOnClickListener(view -> {
// sendReceive = new SendReceive(sock);
messageText = Objects.requireNonNull(editText.getText()).toString().trim();
sendReceive.write(messageText.getBytes());
Toast.makeText(MainActivity.this, "you sent"+ messageText, Toast.LENGTH_SHORT).show();
});
}
private void initializeViews() {
intentFilter = new IntentFilter();
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
toolbar = findViewById(R.id.mdboard_toolbar);
wifi_on_off_iv = findViewById(R.id.md_wifi);
wifi_descovery_iv = findViewById(R.id.md_wifi_descov);
brd_msg_iv = findViewById(R.id.md_broadcast_mesaage);
editText = findViewById(R.id.md_editext);
sentMessage = findViewById(R.id.md_tally_message);
send_btn_iv = findViewById(R.id.md_send_btn);
save_ic_iv = findViewById(R.id.md_save);
username = findViewById(R.id.md_profile_username);
connectionStatus = findViewById(R.id.md_status_text);
listView = findViewById(R.id.md_list_view);
tallytext = findViewById(R.id.md_tally_text);
tallyno = findViewById(R.id.md_tally_no);
nestedLinearlayout = findViewById(R.id.nestedscroll_linearlayout);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.dashboard);
ViewCompat.setNestedScrollingEnabled(nestedLinearlayout, true);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
p2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mchannel = p2pManager.initialize(this, getMainLooper(), null);
broadcastReceiver = new WifiDirectBroadcastReceiver(p2pManager, mchannel, this);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
if (!wifiP2pDeviceList.getDeviceList().equals(peers)) {
peers.clear();
peers.addAll(wifiP2pDeviceList.getDeviceList());
devicenameArray = new String[wifiP2pDeviceList.getDeviceList().size()];
wifiP2pDeviceArray = new WifiP2pDevice[wifiP2pDeviceList.getDeviceList().size()];
int index = 0;
for (WifiP2pDevice device: wifiP2pDeviceList.getDeviceList()) {
devicenameArray[index] = device.deviceName;
wifiP2pDeviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, devicenameArray);
listView.setAdapter(adapter);
}
if (peers.size()==0) {
Toast.makeText(MainActivity.this, "No device found", Toast.LENGTH_SHORT).show();
return;
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener(){
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwner = wifiP2pInfo.groupOwnerAddress;
if (wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass = new ServerClass();
serverClass.start();
} else if (wifiP2pInfo.groupFormed){
connectionStatus.setText("CLient");
clientClass = new ClientClass(groupOwner);
clientClass.start();
}
}
};
#Override
protected void onStart(){
super.onStart();
exqListener();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
public class ServerClass extends Thread {
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
try {
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt) {
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (socket!=null) {
try {
bytes = inputStream.read(buffer);
if (bytes>0){
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
outputStream = new OutputStream() {
#Override
public void write(int i) throws IOException {
outputStream.write(bytes);
}
};
}
}
public class ClientClass extends Thread {
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress) {
hostAdd = hostAddress.getHostAddress();
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd, 8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// requestGroupInfo
private void requestGroupInfo() {
p2pManager.requestGroupInfo(mchannel, new WifiP2pManager.GroupInfoListener() {
#Override
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
connectionStatus.setText("request group info");
}
});
}
}
Here is my wifibroadcastReceiver class
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
WifiP2pManager wifiP2pManager;
WifiP2pManager.Channel channel;
MainActivity mainActivity;
public WifiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mchannel, MainActivity mActivity) {
this.wifiP2pManager = mManager;
this.channel = mchannel;
this.mainActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
mainActivity. wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
Toast.makeText(context, "Wifi is on", Toast.LENGTH_SHORT).show();
} else {
mainActivity.wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
Toast.makeText(context, "Wifi is off", Toast.LENGTH_SHORT).show();
}
} else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// do somethimg
if (wifiP2pManager != null) {
wifiP2pManager.requestPeers(channel, mainActivity.peerListListener);
}
} else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// do somthing
if (wifiP2pManager == null) {
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
wifiP2pManager.requestConnectionInfo(channel, mainActivity.connectionInfoListener);
mainActivity.connectionStatus.setText("[Device connected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
} else {
mainActivity.connectionStatus.setText("[Device disconnected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}

Failed to send data from arduino

I have connected the android application to the arduino successfully but it seems that i can't get the data even though I used the input stream ... I dont know whats wronge been looking and trying other solution for couple of days ..
Android Studio Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetooth = new BluetoothSPP(this);
text = (TextView) findViewById(R.id.textView2);
connect = (Button) findViewById(R.id.connect);
on = (Button) findViewById(R.id.on);
BluetoothSocket socket = null;
mAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetooth.isBluetoothAvailable()) {
Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();
finish();
}
bluetooth.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
public void onDeviceConnected(String name, String address) {
connect.setText("Connected to " + name);
}
public void onDeviceDisconnected() {
connect.setText("Connection lost");
}
public void onDeviceConnectionFailed() {
connect.setText("Unable to connect");
}
});
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetooth.getServiceState() == BluetoothState.STATE_CONNECTED) {
bluetooth.disconnect();
} else {
Intent intent = new Intent(getApplicationContext(), DeviceList.class);
startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
}
}
});
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
/*off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetooth.send(OFF, true);
}
});*/
}
public void onStart() {
super.onStart();
if (!bluetooth.isBluetoothEnabled()) {
bluetooth.enable();
} else {
if (!bluetooth.isServiceAvailable()) {
bluetooth.setupService();
bluetooth.startService(BluetoothState.DEVICE_OTHER);
}
}
}
< /* class ConnectedThread extends Thread {
private InputStream mInStream;
public ConnectedThread(BluetoothSocket socket) throws IOException {
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
mInStream = tmpIn;
}
}
public void run() {
BufferedReader r = new BufferedReader(new InputStreamReader(mInStream));
while (true) {
try {
int a = r.read();
Log.d(TAG, Integer.toString(a));
} catch (IOException e) {
break;
}
}
}
}*/
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
text.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
text.setText("Bluetooth Closed");
}
public void onDestroy() {
super.onDestroy();
bluetooth.stopService();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
if (resultCode == Activity.RESULT_OK)
bluetooth.connect(data);
} else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
bluetooth.setupService();
} else {
Toast.makeText(getApplicationContext()
, "Bluetooth was not enabled."
, Toast.LENGTH_SHORT).show();
finish();
}
}
}
Arduino Code:
You don't need InputStream and OutputStream as you are not using native android RFCOMM bluetooth api. I googled BluetoothSPP class and find out you were using this github library for blutooth spp communication: akexorcist/Android-BluetoothSPPLibrary
Your code seem to work for connecting / disconnecting to your arduino device. So, I deem you proprely integrated the library. What is missing is the code to send / receive bluetooth data. I updated your code as following:
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetooth.send("ON", true);
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetooth.send("OFF", true);
}
});
bluetooth.setOnDataReceivedListener(new OnDataReceivedListener() {
public void onDataReceived(byte[] data, String message) {
Toast.makeText(getApplicationContext(), String.format("Data Received: %s", message), Toast.LENGTH_SHORT).show();
}
});

Connecting with server using smack API in MainActivity android

I am trying to receive and send messages using Smack API but not been able to do it in a separate class due to some threads issue may be. But when now i ported all the code in MainActivity i wont be able to make a connection with server.Below is my MainActivity.class.
public class chatActivity extends AppCompatActivity {
private static final String DOMAIN = "192.168.0.109";
private static final String HOST = "192.168.0.109";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
ChatManager chatManager;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
Context context;
private MultiUserChat multiUserChat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
init("user123","user123");
}
});
t.start();
}
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
this.context = context;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
System.out.println("Hellooooooooo11111");
login();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// // TODO Auto-generated method stub
//new MainActivity().updateText(context);
}
});
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
// joinChatRoom();
// sendMsg();
chat_created = false;
//sendMessage("body","jid");
//sendMsg();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
// sendMsg();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
public void login() {
try {
connection.login(userName, passWord);
// sendMsg();
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
}
My Question is how can I use smack API, I am not getting it at all that how to handle this network operations in main class.
I did try to run it in Asynch too.
Okay I found the solution i forgot to add the following method in my main class.
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}

Android Need help! How to make Tcp Client receive data from server?

I want to make a TCP client that can sent and receive data for server. I use Hercules(TCP/UDP test program) as Server. My code can send string "Submit" to Server. I try to make my code can receive data from Hercules but it not work.what I have to do for edit it?
This is my MainActivity code
public class MainActivity extends Activity {
// Used to reference UI elements of main.xml
private TextView text,serverResponse;
private EditText ipBox;
private EditText portBox;
private ToggleButton connect;
private Button send;
private static final String TAG = "CClient";
private String ipAddress;
private Socket client;
private DataOutputStream outToServer;
private DataInputStream inFromServer;
private boolean connected = false;
private final int START = 0xffffff;
private final int msgBoxHint = START;
private final int appendText = START + 1;
Toast mytoast , savetoast;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(TAG, "Here 1");
ipAddress = getLocalIpAddress();
Log.d(TAG, "Get local IP="+ ipAddress);
text = (TextView) findViewById(R.id.text);
ipBox = (EditText) findViewById(R.id.ipBox);
serverResponse = (TextView) findViewById(R.id.response);
portBox = (EditText) findViewById(R.id.portBox);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(buttonsendOnClickListener);
connect = (ToggleButton) findViewById(R.id.connect);
connect.setOnClickListener(buttonConnectOnClickListener);
Button buttonExit = (Button) findViewById(R.id.btnExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "Exit");
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
}
finish();
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.connect:
if(connect.isChecked())
{
Log.d(TAG, "Connect" );
EditText edIP = (EditText) findViewById(R.id.ipBox);
String ed_textIP = edIP.getText().toString().trim();
if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null )
{
Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
Log.d(TAG, "IP Address or PORT is incorrect");
}
setValues(R.id.connect,true);
setValues(R.id.send,true);
setValues(R.id.ipBox,false);
String tMsg = welcomeMsg.toString();
MyClientTask myClientTask = new MyClientTask(ipBox
.getText().toString(), Integer.parseInt(portBox
.getText().toString()),
tMsg);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
myClientTask.execute();
}
else
{ /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
setText(R.id.text,"Press the connect button to start the client");
setText(msgBoxHint,"");
setValues(R.id.connect,false);
setValues(R.id.ipBox,true);
setValues(R.id.send,false);
}
else
{
setValues(R.id.connect,false);
}
}
break;
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String msgToServer;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
}
protected Void doInBackground(Void... Arg0) {
Log.d(TAG, "InBackground");
Socket socket = null;
DataOutputStream outToServer = null;
DataInputStream inFromServer = null;
try {
client = new Socket(dstAddress, dstPort);
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream())); // Input stream <- from server
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.d(TAG, "InBackground 1");
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error UnknownHostException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
} catch (IOException e) {
Log.d(TAG, "InBackground 2");
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error IOException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.connect,false);
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
}finally {
Log.d(TAG, "InBackground 3");
if (socket != null) {
try {
socket.close();
Log.d(TAG, "InBackground 3.11");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "InBackground 3.12");
}
}
Log.d(TAG, "InBackground 3.1");
}
Log.d(TAG, "InBackground 4");
return null;
}
#Override
protected void onPostExecute(Void result) {
serverResponse.setText(response);
super.onPostExecute(result);
}
}
OnClickListener buttonsendOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.send:
Log.d(TAG, "Sent" );
String sentence = "Submit";
String recieve = "";
serverResponse = (TextView) findViewById(R.id.response);
try {
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream()));
Log.d(TAG, "Sent 1-1" );
if(sentence != null){
outToServer.writeUTF(sentence);
outToServer.flush();
}
/*
*
*
*
*
*
*/
Log.d(TAG, "Sent 1-2"+ recieve);
} catch (IOException e) {
setValues(R.id.ipBox,true);
setValues(R.id.connect,false);
setValues(R.id.send,false);
}
break;
}
}
};
private String getLocalIpAddress() {
Log.d(TAG, "Here 2");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Log.d(TAG, "Here 3");
WifiInfo info = wifi.getConnectionInfo();
Log.d(TAG, "Here 4");
return Formatter.formatIpAddress(info.getIpAddress());
}
private void setText(int view, String content)
{
switch(view)
{
case R.id.ipBox: ipBox.setText(content); break;
case R.id.text: text.setText(content+"\n\n"); break;
case appendText: text.append(content+"\n\n"); break;
}
}
private void setValues(int view, boolean value)
{
switch(view)
{
case R.id.ipBox: ipBox.setEnabled(value); break;
case R.id.send: send.setEnabled(value); break;
case R.id.connect: connect.setChecked(value); break;
}
}
}
I think, I have to add receive code in buttonsendOnClickListener near /*****/.
Do not work with sockets in main (gui) thread. Use AsyncTask!
Android fails if work with sockets in main (gui) thread.
Example:
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
// do in main thread before
}
#Override
protected Void doInBackground(Void... v) {
// do in thread, use sockets
return null;
}
#Override
protected void onPostExecute(Void v) {
super.onPostExecute(integer);
// do in main thread after
}
}.execute();
Learn about AsyncTask advance.

Link java class to xml file in android

I would like to link java class to my xml file.
There is no error in the coding however, it gave me force close.
I would like to know what's wrong with it.
Can anyone please advice me?
I've one main java class, having the same code as this, as I would like to display the same thing for both xml layout.
The main java class work perfectly fine, however, when I try to convert the coding to second java class, the force close error occurs.
Here is my coding.
public class event extends ListActivity{
ArrayList<String> psi;
public TextView psi_text;
TextView weather;
ImageView image;
private static Handler mHandler = new Handler();
class MyWeather{
String conditiontext;
String conditiontemp;
String conditiondate;
public String forecastToString(){
return
conditiontext + "\n" + " " + conditiontemp + "°C" ;
}
}
String[] Category = {
"Scientist for a day",
"Science Trail",
"Megalog Return"
};
String [] dates = {
"Today",
"Tomorrow",
"This Week"
};
Spinner s1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event);
weather = (TextView)findViewById(R.id.weather);
image = (ImageView)findViewById(R.id.image);
psi = new ArrayList<String>();
psi_text = (TextView) findViewById(R.id.psi_text);
TabHost th =(TabHost)findViewById(R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1");
specs.setContent(R.id.tab1);
specs.setIndicator("Suggested");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.tab2);
specs.setIndicator("All");
th.addTab(specs);
TabWidget tw = (TabWidget) th.findViewById(android.R.id.tabs);
View tab1 = tw.getChildTabViewAt(0);
TextView tv = (TextView) tab1.findViewById(android.R.id.title);
tv.setTextSize(15);
tv.setPadding(0, 0, 0, 50);
View tab2 = tw.getChildTabViewAt(1);
TextView tv1 = (TextView) tab2.findViewById(android.R.id.title);
tv1.setTextSize(15);
tv1.setPadding(0, 0, 0, 50);
//GridView
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category));
//SpinnerView
s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, dates);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long arg3) {
int index = s1.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have seleted item :" + dates[index] , Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?>arg0) {}
});
try {
URL url = new URL(
"http://app2.nea.gov.sg/data/rss/nea_psi.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList websiteList = fstElmnt.getElementsByTagName("psi");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
psi.add(""+ ((Node) websiteList.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
String temp = Html.fromHtml(psi.get(0)).toString();
String a[] = temp.split("\\)");
psi_text.setText(""+a[0]+")");
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.forecastToString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
String weatherCode = conditionNode.getAttributes()
.getNamedItem("code")
.getNodeValue()
.toString();
// thunderstorms
if(weatherCode.equals("4")){
mHandler.post(new Runnable() {
#Override
public void run() {
// This gets executed on the UI thread so it can safely modify
// Views
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//isolated thunderstorms
else if ( weatherCode.equals("37")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//scattered thunderstorms
else if ( weatherCode.equals("38")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//scattered thunderstorms
else if ( weatherCode.equals("39")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//thundershowers
else if ( weatherCode.equals("45")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//isolated thundershowers
else if ( weatherCode.equals("47")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//drizzle
else if ( weatherCode.equals("9")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//showers
else if ( weatherCode.equals("11")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//showers
else if ( weatherCode.equals("12")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//scattered showers
else if ( weatherCode.equals("40")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//hail
else if ( weatherCode.equals("17")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.hail);
}
});
}
//mixed rain and hail
else if ( weatherCode.equals("35")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.hail);
}
});
}
//foggy
else if ( weatherCode.equals("20")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//haze
else if ( weatherCode.equals("21")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//smoky
else if ( weatherCode.equals("22")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//windy
else if ( weatherCode.equals("24")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.windy);
}
});
}
//cloudy
else if ( weatherCode.equals("26")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//fair (night)
else if ( weatherCode.equals("33")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//fair (day)
else if ( weatherCode.equals("34")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//partly cloudy
else if ( weatherCode.equals("44")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//mostly cloudy (night)
else if ( weatherCode.equals("27")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.night_cloudy);
}
});
}
//partly cloudy (night)
else if ( weatherCode.equals("29")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.night_cloudy);
}
});
}
//mostly cloudy (day)
else if ( weatherCode.equals("28")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.day_cloudy);
}
});
}
//partly cloudy (day)
else if ( weatherCode.equals("30")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.day_cloudy);
}
});
}
//clear(night)
else if ( weatherCode.equals("31")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.moon);
}
});
}
//sunny
else {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.sunny);
}
});
}
myWeather.conditiontext = conditionNode.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString();
myWeather.conditiontemp = conditionNode.getAttributes()
.getNamedItem("temp")
.getNodeValue()
.toString();
return myWeather;
}
private Document convertStringToDocument(String src){
Document dest = null;
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(event.this,
e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return dest;
}
private String QueryYahooWeather(){
String qResult = "";
String queryString = "http://weather.yahooapis.com/forecastrss?w=1062617&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(queryString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return qResult;
}
public void onListItemClick(ListView parent, View v, int position,long id)
{
Toast.makeText(this, "You have selected " + Category[position], Toast.LENGTH_SHORT).show();
}
}
You don't have the
setContentView(R.layout.YOUR_XML_NAME);
in your activity. That's why you could not connect your java class and xml file

Categories

Resources