android onclick buttons to write strings on Socket - android

Hi I am building an app which requires the user to press buttons (total 8 buttons). These buttons used to send strings to the server onclick . The problem here I'm having is when i press any of the button after connecting to the server it sends the string as it should but the 2nd time nothing happens. I was suggested to use doInBackground() from AsyncTask, to run keep running the socket and write to it each time the buttons are pressed. But i am unable to do so. What should I do ? I don't know where is the problem. Here I'm putting my code.
This is my Activity
public class Acontroller extends Activity {
Button bForward;
Button bBackward;
Button bRight;
Button bLeft;
Button bSelect;
Button bStart;
Button bB;
Button bA;
Socket s;
DataOutputStream os;
String ip;
// MyAppActivity ip = new MyAppActivity();
MyThread start = new MyThread();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.nesskin);
bForward = (Button) findViewById(R.id.bForward);
bBackward = (Button) findViewById(R.id.bBackward);
bRight = (Button) findViewById(R.id.bRight);
bLeft = (Button) findViewById(R.id.bLeft);
bSelect = (Button) findViewById(R.id.bSelect);
bStart = (Button) findViewById(R.id.bStart);
bA = (Button) findViewById(R.id.bA);
bB = (Button) findViewById(R.id.bB);
Bundle gotIP = getIntent().getExtras();
ip = gotIP.getString("ipAddress");
// start.doInBackground(ip);
//start.execute(ip);
// sock.start();
}
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
bForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
start.execute(ip);
}
});
And from the thread.
public class MyThread extends AsyncTask <String, Void, String>{
Socket s;
DataOutputStream os;
String ip;
String cmd;
#Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecute");
}
#Override
protected String doInBackground(String... params) {
int port = 2222;
// TODO Auto-generated method stub
if(s.isConnected()){
try {
os.writeUTF("forward");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
s= new Socket(ip, port);
os = new DataOutputStream(s.getOutputStream());
os.writeUTF("forward");
}catch(Exception e){
e.printStackTrace();
}
finally{
if (s!= null){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
My objective is as many times the user clicks the buttons the respective strings must be send to the server. Here is my server code I'm using PC as server.
public class Server
public static void main(String[] args) throws AWTException {
String msg_received = null;
String fw = "forward";
String bw = "backward";
String l = "left";
String r = "right";
String se = "select";
String st = "start";
String a = "a";
String b = "b";
String fin = "finish";
// Boolean finish = (msg_received.equal(fin));
Robot robot = new Robot();
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Server Started...");
while (true) {
Socket s = ss.accept();
System.out.println("Connection Request Received");
DataInputStream DIS = new DataInputStream(s.getInputStream());
msg_received = DIS.readUTF();
System.out.println(msg_received);
// s.close();
// ss.close();
if (msg_received.equals(fw)) {
// tu yeh kerna
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
}
Please help me it really important to me. Thanks in advance.

You can't re-use an AsyncTask. You have to create a new object and call execute.
Replace
start.execute();
with
start = new MyThread();
start.execute(ip);
or if you can get away with removing the instance when it's done, then you can just do this:
(new MyThread()).start();
EDIT:
To send parameters to AsyncTask, do this:
start.execute(ip, cmd, param3, param4, param5);
in doInBackground collect the parameters like so:
protected Void doInBackground(String... params)
{
String ipParam = params[0];
String cmdParam = params[1];
String thirdParam = params[2];
String fourthParam = params[3];
String fifthParam = params[4];
}
You can pass as many Strings as you want into params and it will automatically create a new array containing all the parameters at runtime. Just note that if you only pass in two, then the params size will only be two. If you pass in 100 parameters, then params will be 100 units in size.

Related

My application is working on emulator but not on real devices

i am using simple asynctask function for getting values from mysql database through json.it was working fine with emulator but if i am trying from the mobile i am getting error. like Java.lang.NullPointerExceprtion:Attempt to invke virtual metho 'java.lang.string.java.lang.stringbuilder.toString() on a null object reference.
I tried with new project but result is same. this application is not working in all the devices except emulator. can you help me on this.
My Code is -
public class MainActivity extends AppCompatActivity {
private static final String Latest_Products7 = "Questions";
JSONArray productsArray7 = null;
public static final int CONNECTION_TIMEOUT7=100000;
public static final int READ_TIMEOUT7=150000;
HashMap<String,ArrayList<WorldPopulation>> hasmap = new HashMap<String,ArrayList<WorldPopulation>>();
ArrayList<WorldPopulation> arraylist7 = null;
StringBuilder result7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncLogin7().execute();
}
private class AsyncLogin7 extends AsyncTask<String, String, StringBuilder> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn7;
URL url7 = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected StringBuilder doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url7 = new URL("http:/Samplesite/****/somephp.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn7 = (HttpURLConnection)url7.openConnection();
conn7.setReadTimeout(READ_TIMEOUT7);
conn7.setConnectTimeout(CONNECTION_TIMEOUT7);
conn7.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn7.setDoInput(true);
conn7.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder7 = new Uri.Builder().appendQueryParameter("reg_id", "hai") ;
String query7 = builder7.build().getEncodedQuery();
// Open connection for sending data
OutputStream os7 = conn7.getOutputStream();
BufferedWriter writer7 = new BufferedWriter(new OutputStreamWriter(os7, "UTF-8"));
writer7.write(query7);
writer7.flush();
writer7.close();
os7.close();
conn7.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
int response_code7 = conn7.getResponseCode();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
result7 = new StringBuilder();
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
}
#Override
protected void onPostExecute(StringBuilder result7) {
super.onPostExecute(result7);
Log.e("dai",result7.toString());
Toast.makeText(MainActivity.this,result7.toString(),Toast.LENGTH_LONG).show();
pdLoading.dismiss();
/* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
intnt.putExtra("task",hasmap);
startActivity(intnt);*/
}
}
}
Change
try {
int response_code7 = conn7.getResponseCode();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
result7 = new StringBuilder();
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
To
try {
int response_code7 = conn7.getResponseCode();
result7 = new StringBuilder();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
Try something like this
Log.e("dai",MainActivity.this.result7.toString());
Toast.makeText(MainActivity.this,MainActivity.this.result7.toString(),Toast.LENGTH_LONG).show();
OR
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(result);
Log.e("dai",result.toString());
Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
pdLoading.dismiss();
/* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
intnt.putExtra("task",hasmap);
startActivity(intnt);*/
}
}

Socket Programming with Broadcast Recevier

I am developing Android application(online marketing), within this project i am using socket programming for communication with server, when i communicate with server if server does not give me any response within 30 sec then my asynctask will close automatically, but now problem is i want to save server response in sqlite on receiving response from server please provide me the necessary help thank
you in advance.
Here is My Asyntask :
public class SendToserver extends AsyncTask<Integer, Integer, Integer>
{
int iReturn;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog(Registartion.this, "Please Wait...");
super.onPreExecute();
}
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
ServerData = runm(IMEINo);
if (ServerData.equalsIgnoreCase("IsNull"))
{
iReturn = 2;
}
else {
iReturn = 1;
}
return iReturn;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
if (iReturn == 1)
{
String ServerIP = edtServerIpAddress.getText().toString();
String ServerPort = edtServerPort.getText().toString();
registartionModel = new RegistartionModel();
registartionModel.setServerIPAdreess(ServerIP);
registartionModel.setPort(ServerPort);
registrationDb = new RegistrationDb(getApplicationContext());
registrationDb.open();
registrationDb.insertData(registartionModel);
registrationDb.close();
Intent i = new Intent(getBaseContext(), LoginActivity.class);
startActivity(i);
Registartion.this.finish();
System.gc();
}
else if (iReturn == 2)
{
showDialogBox("Please Input Correct Server IP and Port");
}
super.onPostExecute(result);
}
}
My Server Communication Method(runm):
#SuppressLint("NewApi")
public String runm(String DId)
{
try {
socket = new Socket(SERVER_IP, SERVERPORT);
out = new PrintStream(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write((DId + "|" +"REG").getBytes());
ServerData = in.readLine();
System.err.println("Server Data in Runm :- " + ServerData);
if(ServerData == null || ServerData.equalsIgnoreCase(""))
{
ServerData="IsNull";
}
}
catch (NetworkOnMainThreadException e)
{
ServerData = "IsNull";
}catch (IOException ex) {
ServerData = "IsNull";
}
return ServerData;
}
Should i use Broadcast Receiver ?

UDP holepunching: PC-to-Android UDP connection does not work with nonlocal addresses

I wrote a simple UDP transfer between an Android App and Python Server. I know that the system is working because when I try to connect on a local ip address (192.168.X.X), the correct message is sent and recieved. However, this does not work when I try to use a public IP address. Does anyone know why and how I can try to fix this?
I am trying to implement UDP holepunching, having the server act as the target client of the Android one, but I cannot get the 2nd client's UDP packet to the Android one, it never gets picked up on the Android's side. Would having a 2nd machine act as the 2nd client fix this, or is my code incomplete?
Does my provider (T-Mobile) matter for UDP packet communication?
Client (Android):
public class CustomizeGatewayActivity extends ActionBarActivity {
AsyncUDPReceiver aReceive = null;
static TextView recieve = null;
public static class PlaceholderFragment extends Fragment {
EditText addressText, portText, messageText;
Button udpsend, tcpsend;
Socket socket = null;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_customize_gateway, container, false);
recieve = (TextView) rootView.findViewById(R.id.textView1);
addressText = (EditText) rootView.findViewById(R.id.editText1);
messageText = (EditText) rootView.findViewById(R.id.editText3);
udpsend = (Button) rootView.findViewById(R.id.UDP);
udpsend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsyncUDPSend aSend = new AsyncUDPSend(addressText.getText().toString(), messageText.getText().toString());
aSend.execute();
}
});
public class AsyncUDPSend extends AsyncTask<Void, Void, Void> {
String address = "";
String message = "";
String response = "";
AsyncUDPSend(String addr, String mes) {
address = addr;
message = mes;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
DatagramSocket dsocket = null;
try {
dsocket = new DatagramSocket();
dsocket.setSoTimeout(10000);
InetAddress dest = InetAddress.getByName(address);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), dest, 5001);
dsocket.send(packet);
System.out.println("Sent");
byte[] resp = new byte[1024];
DatagramPacket recv = new DatagramPacket(resp, resp.length);
System.out.println("Waitng for Response");
dsocket.receive(recv);
System.out.println("Received");
response = new String(recv.getData());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
System.out.println(response);
} finally {
if (dsocket != null) {
dsocket.close();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
recieve.setText(response);
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
aReceive = new AsyncUDPReceiver();
aReceive.start();
}
#Override
protected void onPause() {
super.onPause();
aReceive.kill();
}
public class AsyncUDPReceiver extends Thread {
boolean keepRunning = true;
String response = "";
Runnable updateText = new Runnable(){
public void run() {
if(aReceive == null && recieve == null)
return;
recieve.setText(response);
}
};
public void run() {
android.os.Debug.waitForDebugger();
System.out.println("running");
DatagramSocket dsock = null;
byte[] message = new byte[1024];
DatagramPacket dpack = new DatagramPacket(message, message.length);
try {
dsock = new DatagramSocket(5002);
System.out.println(dsock.toString());
while(keepRunning) {
dsock.receive(dpack);
response = new String(dpack.getData());
System.out.println(response);
runOnUiThread(updateText);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
response = "SocketException: " + e.toString();
System.out.println(response);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
response = "IOException: " + e.toString();
System.out.println(response);
e.printStackTrace();
} finally {
if(dsock != null)
dsock.close();
}
}
public void kill() {
keepRunning = false;
}
}
}
Server (Python):
class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip().decode("utf-8")
print("{} Recieved: ".format(self.client_address) + data)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
response = data.upper()
sock.sendto(bytes(response, "utf-8"), self.client_address)
print("{} Sent: {}".format(self.client_address,response))
class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
pass
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "", 5000
udpserver = ThreadedUDPServer((HOST,PORT+1), ThreadedUDPRequestHandler)
udp_thread = threading.Thread(target=udpserver.serve_forever)
udp_thread.daemon = True
udp_thread.start()
print("UDP serving at port", PORT+1)
while True:
pass
udpserver.shutdown()
Are you supplying the expected value to InetAddress.getByName(address);
Also since you are trying to do something in background,it will be better if you run a service with wake lock so that you eliminate errors caused due to killing of process.

how to show toast in getDataTaskmethod? [duplicate]

This question already has an answer here:
how to fix getDataTask method error?
(1 answer)
Closed 9 years ago.
this is my code below which work perfectly only problem is not show toast mesage code is blast i want to display toast mesage if Status is 0 in this line if (status.equals("1"))
show toast message but code is blast if i comment Toast then code run perfectly help me what do i do??
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this,
fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your toast message is within the parseJsonData method which is called from the doInBackground method of your asynctask.
You can not update the user interface thread from a background thread.
You have two options here
1) You can publish the progress publishProgress(1) of the thread passing in an integer value to be used as a flag which you can pick up on in the onPublishProgress listener and show your toast there
or
2) As your method has finished by this point then make the parseJsonData set an integer variable global to the asynctask and in the onPostExecute method pass something back to the listener to indicate that a toast needs to be shown
Update based on comments
Replace
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
with
{
publishProgress(1);
}
Add the missing onProgressUpdate() method to your asynctask
#Override
protected void onProgressUpdate(Integer... percent) {
//Call your listeners.onProgressUpdate(percent) here and show the
//Or
super.onProgressUpdate(percent);
if (percent[0] == 1){
Toast.makeText(thirdstep.this, message, Toast.LENGTH_SHORT).show();
}
}
I'm not here to write your code for you. Do some research on how to properly write an async task and publish progress
Here is a good starting point
http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
You should be aware of orientation changes and how that will effect your asynctask (I avoid the pitfals of this by using a fragment
This is the design pattern I use for async tasks
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
But for handling web services, be nice to your users and let the android system work out when to download data etc and don't drain their battery and use a sync adapter with an intentservice instead of an asynctask. There are already too many crappy apps out there that take the asynctask approach for consuming web services. Please don't add yours to the list
Do it this way
http://developer.android.com/training/sync-adapters/creating-sync-adapter.html
It's a lot of extra learning curve but your a programmer right? You should be giving your users the best possible experience.
BTW You are getting down votes because you are demanding code to be written for you. I'm hoping this is just a language barrier and not an attitude problem.
Surround your Toast with this
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
}
});

connecting android emulators using tcp sockets

the following is my code. Editor: Eclipse, Platform: Windows.
Its a chat application where 2 android emulators connect through a tcp socket.
UI consists of a send button, a text view and a text box.
Problem: As soon as I type text and hit send, the application crashes.
server port is 8000.
So my redirection is redir add tcp:8081:8000 and redir add tcp:8082:8000.
I donno what is wrong in my code. Please suggest me somthing I need to change.
public class HelloandroidActivity extends Activity
{
/** Called when the activity is first created. */
public int serverport=8000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText nameField = (EditText) findViewById(R.id.editText1);
final Button button2 = (Button) findViewById(R.id.button1);
Integer severport=8000;
new Server().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,severport);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final String name = nameField.getText().toString();
final TextView tv = (TextView) findViewById(R.id.textView1);
//tv.setText(name);
String s=null;
new Client().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,s);
}
});// end onclicklis
}//end oncreate
class Server extends AsyncTask <Integer, String, String>
{
public InetAddress byIpAsName ;
int r=0;
#Override
protected String doInBackground(Integer... serverport) {
//i[0]=serverport;
Integer[] sp=serverport;
BufferedReader in=null;
ServerSocket s=null;
r=sp[0];
String cIn="";
try {
//byIpAsName = InetAddress.getByName("10.2.2.15");
s=new ServerSocket(r);
while(true)
{
Socket client = s.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line=in.readLine();
cIn=null;
while(line!=null){cIn=cIn.concat(line);}
}//while
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
return cIn;
}//end inBackground
//#SuppressWarnings("null")
protected void onPostExecute(String... cIn)
{
}//onpost execute
}//server class
public class Client extends AsyncTask<String, String, String>
{
PrintWriter out = null;
BufferedReader in=null;
String sIn=null;
//Server s1=new Server();
//int q=s1.r;
TelephonyManager tel = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() - 4);
int q = Integer.parseInt(portStr);
Socket socket;
#Override
protected String doInBackground(String... params) {
try
{
//q=8080;
InetAddress byIpAsName1=InetAddress.getByName("10.0.2.2");
socket = new Socket(byIpAsName1, q);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line=in.readLine();
sIn=null;
while(line!=null){sIn=sIn.concat(line);}
}
catch (IOException e) {
e.printStackTrace();
}//catch
return sIn;
}//in background
protected void onPostExecute(String... sIn)
{
String c=null;
final TextView tv = (TextView) findViewById(R.id.textView1);
c=c.concat(sIn[0]);
tv.setText(c);
}
}
}//main class
From your logcat, what is important is this line:
03-16 23:12:23.434: E/AndroidRuntime(571): java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10040 nor current process has android.permission.READ_PHONE_STATE.
This indicates that in order to run your code, you need the READ_PHONE_STATE permission in the android manifest.xml.
Add this line to the manifest, outside of the <application> tag but inside the <manifest> tag.
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
If this does not solve the issue, the problem could be related to this answer.

Categories

Resources