Socket connection test, not working and receive data from hyperterminal - android

I am creating a socket connection in android eclipse for receiving data first i need to test the connection but the page is not opening on my app, i use a listactivity for my classes.
I want to receive data from my pc(hyperterminal), i have connected a hardware device to my computer which behaves like a router and i want to connect my android phone to the router via Wifi and receive data on my phone as i type on the hyperterminal.
package com.exa.bullseye;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.OutputStream;
public class WifiReceive extends Activity {
EditText ip;
EditText s_port;
Button connect;
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.wifireceive);
ip = ((EditText)findViewById(R.id.ip));
s_port = ((EditText)findViewById(R.id.port));
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String address = ip.getText().toString();
InetAddress addr = InetAddress.getByName(address);
int port = Integer.parseInt(s_port.getText().toString());
// Creates a stream socket and connects it to the specified port
// number at the specified IP address. Blocks until the connection succeeds.
Socket socket = new Socket(addr, port);
Toast.makeText(getApplicationContext(), "Socket Connected",
Toast.LENGTH_LONG).show();
socket.close();
}
catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Host not found",
Toast.LENGTH_LONG).show();
}
catch (IOException ioe) {
Toast.makeText(getApplicationContext(), "I/O Exception",
Toast.LENGTH_LONG).show();
}
}
});
}
}

Related

How to return variables from AsyncTask to Google Map activity in Android

I have an async task that fetches a JSON array from a url and then parses it to a String.
My problem is that i cannot move the fetched data from URL to my Google Maps activity (Map Activity). When i tried Intent in Asynctask i could not make it.
Please help!! Thanks in advance
Async Task:
package com.example.panos.fleet_management;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import static android.app.PendingIntent.getActivity;
import static android.content.ContentValues.TAG;
import static android.support.v4.content.ContextCompat.startActivity;
/**
* Created by panos on 18/8/2018.
*/
public class MapRequest extends AsyncTask<Void,Void, Void> {
String data="";
String dataParsed="";
String singleParsed="";
double lon[],lat[];
String reg;
private Context context;
public MapRequest(Context context){
this.context=context;
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url= new URL("xxx.xxx");
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream= httpURLConnection.getInputStream() ;
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line= "";
while(line != null) {
line = bufferedReader.readLine();
data=data + line;
}
JSONArray JA=new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO= (JSONObject) JA.get(i);
singleParsed="Registration:"+ JO.get("Registration") + "\n"+
"Longitude:"+ JO.get("Longitude") + "\n"+
"Latitude:"+ JO.get("Latitude") + "\n";
dataParsed= dataParsed + singleParsed + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent(context, MapActivity.class);
intent.putExtra("dat",dataParsed);
}
}
JSON File
[{
"Registration": "YHB6595",
"Longitude": "11.00000000",
"Latitude": "3.00000000"
}, {
"Registration": "YMK3540",
"Longitude": "41.00000000",
"Latitude": "2.00000000"
}]
Map Activity :
package com.example.panos.fleet_management;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import java.util.Map.Entry;
import static com.example.panos.fleet_management.R.id.map;
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
new MapRequest(this).execute();
}
#Override
public void onMapReady (GoogleMap googleMap){
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(40,41);
LatLng location2 = new LatLng(11,41);
mMap.addMarker(new MarkerOptions().position(sydney).title(getIntent().getStringExtra("dat")));
mMap.addMarker(new MarkerOptions().position(location2).title("dsader"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
First, why you have the Volley imports and you're not using them? It's a very simple way to get data from network asynchronously, without the AsyncTask and right from your Activity.
Also you're creating the Intent and doing nothing with it. If you insist in using it the way you are, use the Intent to send a LocalBroadcastManager and register the receiver for it in your activity where the map is
At last I found a very simple answer to my question. The only thing that i needed to do was to make mMap variable public static and then access it from onPostexecute and put the data there.

my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?

i am new by android.I have started work with a simple chat app. I wrote a short code by UDP socket one for client and one for server.Now i have some issues at connectivity android real device which client app installed on it , and emulator device which server app run on it.
Client app is a simple code which must set IP for connection to emulator and also has a EditText for sending a message.(I at this point set 10.0.2.2 or 10.0.2.15. But my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?)
Server app has only a textView for getting and showing recived message.
here is Client code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClienttextchatActivity extends Activity
{
private String udpMsg=null;
Handler hand=new Handler();
EditText edtSetIp=null , edtText=null;
Button btnSetIp=null , btnSend=null;
static String ip=null;
static final String LOG_TAG = "UdpStream";
static final int PORT = 8888;
static final int BUF_SIZE=4096;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edtText=(EditText)findViewById(R.id.edtText);
edtSetIp=(EditText)findViewById(R.id.edtSetIp);
btnSetIp=(Button)findViewById(R.id.btnSetIp);
btnSend=(Button)findViewById(R.id.btnSend);
btnSetIp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
ip=edtSetIp.getText().toString();
}
});
btnSend.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread mythread=new Thread(new th1() );
mythread.start();
}
});
}
//#############################################
public class th1 implements Runnable
{
public void run()
{
udpMsg =edtText.getText().toString();
Log.d(LOG_TAG,udpMsg);
DatagramSocket ds = null;
try
{
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName(ip);
Log.d(LOG_TAG,"address server address created.");
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, PORT);
ds.send(dp);
Log.d(LOG_TAG,"packet send.");
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
}//end run
}//end class th
}
Make sure emulator is started, then in ADB shell, type this command, it will show ip address of emulator.
adb shell
ifconfig etho

how to send data (a string) to a paired device in android?

I am working on bluetooth for the first time. I got the list of paired devices. Now my requirement is I need to send some data (a string) to the device. how can I do that? I tried searching but didn't find anything useful. Could anyone help out this?
Something like this might suffice:
DataOutputStream os;
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
BluetoothDevice remoteDevice;
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(), "Discovered: " + remoteDeviceName + " address " + remoteDevice.getAddress(), Toast.LENGTH_SHORT).show();
try{
BluetoothDevice device = bluetooth.getRemoteDevice(remoteDevice.getAddress());
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
BluetoothSocket clientSocket = (BluetoothSocket) m.invoke(device, 1);
clientSocket.connect();
os = new DataOutputStream(clientSocket.getOutputStream());
new clientSock().start();
} catch (Exception e) {
e.printStackTrace();
Log.e("BLUETOOTH", e.getMessage());
}
}
};
registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
bluetooth.enable();
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
public class clientSock extends Thread {
public void run () {
try {
os.writeBytes("anything you want"); // anything you want
os.flush();
} catch (Exception e1) {
e1.printStackTrace();
return;
}
}
}
You will also need a lot of imports such as these:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
note that not all imports are necessary for this example code, your IDE might help you to sort them out for you.
Pass data on the os.writeBytes("anything you want"); // anything you want line.
You will also need Permissions

SocketTimeoutException in android-socket Communication

I'm trying to connect my 'Galaxy S' to my Panasonic PLC(or even other PC itself) but I always get an SocketTimeoutException. My android version is 2.3.3:
IP-PLC: 192.168.2.99
IP-GalaxyS: I don't know how to check it
Mask of the network: 255.255.255.0
The PLC is connected directly with the wi-fi router, and I connect my cell phone to this network.
package com.example.communication;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import android.util.Log;
public class TryConnection implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.2.99");
Socket socket = new Socket(serverAddr, 9094);
Log.e("SUCESS", "SUCESS");
} catch(SocketTimeoutException e) {
Log.e("SOCKET TIMEOUT", "SOCKET TIMEOUT", e);
} catch (IOException e) {
Log.e("CONNECTION ", " ERROR", e);
}
}
and my MainActivity Class:
package com.example.communication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendTag(View view) {
TryConnection tryconnection = new TryConnection();
Thread thread = new Thread(tryconnection);
thread.start();
}
}
Do you have any idea for why is it happening ?
It happened with me also, restarted eclipse to resolve the issue.

Connecting android client to C server

I am having trouble connecting my android client to a C server that I wrote. I found another thread with a similar question but unfortunately it was closed saying that it was too narrow. I hope that somebody can answer it here since this is relevant to me as well and all sample codes that I could find online only had the android client connecting to an android server. My client code is the following:
package edu.upenn.seas.cis542;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Try_uiActivity extends Activity
{
//private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "MY IP ADDRESS";
private boolean connected = false;
private Handler handler = new Handler();
final int SERVERPORT = 8080;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker3);
//t1.setRange(1, 5);
setContentView(R.layout.main);
}
/*
* When the Submit button is clicked, this method
* gets called.
*/
public void onSubmitClick(View view) {
int item1, item2, item3;
NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker1);
item1 = t1.getCurrent();
NumberPicker t2 = (NumberPicker)findViewById(R.id.numberPicker2);
item2 = t2.getCurrent();
NumberPicker t3 = (NumberPicker)findViewById(R.id.numberPicker3);
item3 = t3.getCurrent();
String userInput = "" + item1 + item2 + item3;
//Log.out("Before connecting");
if (!connected) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Toast toast=Toast.makeText(this, serverAddr.toString(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Socket socket = new Socket(serverAddr, SERVERPORT);
connected = true;
} catch (Exception e) {
Toast toast=Toast.makeText(this, "Error2", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
e.printStackTrace();
connected = false;
}
}
}
}
I omitted what I want to do after it is connecting because just creating the socket already gives me an error. My C server opens a connection on the same port that the android program is connecting to. When I tested the server with a java client file, it worked fine. Does anybody know a solution to this? I also added the permissions to the Android Manifest, but that didn't solve the issue. Thanks!

Categories

Resources