I'm new to android application development. I tried to develop an android server client chat
for my first project. This is the code for the client side. When the client press btnJoin,
it will connect to the server and send a string. I've read many example and many of them
looks like this. I got a networkOnMainThreadException. How do I make an asyncTask to prevent
this problem? Any help would be much appreciated.
btnJoin = (Button) findViewById(R.id.buttonJoin);
btnJoin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.4", 9092);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
txtIP.append(dataInputStream.readUTF() + "\n");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
Change your code as:
btnJoin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
new LongOperation().execute("");
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
Socket socket = null;
String strresult="";
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
#Override
protected String doInBackground(String... params) {
try {
socket = new Socket("192.168.1.4", 9092);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
strresult.append(dataInputStream.readUTF() + "\n");
// txtIP.append(dataInputStream.readUTF() + "\n");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strresult;
}
#Override
protected void onPostExecute(String result) {
TextView txtIP= (TextView) findViewById(R.id.txtIP);
// txtIP.append(result + "\n");
txtIP.setText(result + "\n");
}
#Override
protected void onPreExecute() {
}
}
Use AsyncTask like this :
First have it nested in your class, it should look similar to :
private class Communicator extends AsyncTask<Void, Void, Boolean> {
String tmp;
String err;
#Override
protected Boolean doInBackground() {
try {
socket = new Socket("192.168.1.4", 9092);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Boolean result) {
txtIP.append(dataInputStream.readUTF() + "\n");
}
}
When you have AsyncTask,you can start it like this :
...
#Override
public void onClick(View v) {
Communicator c=new Communicator();
c.execute();
}
....
try to implement this code in your app
private class LongOperation extends AsyncTask<Object, Integer, Object> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
//do hard work here
return params;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
}
}
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
for more details refer below links...
http://www.vogella.com/articles/AndroidPerformance/article.html
http://developer.android.com/reference/android/os/AsyncTask.html
Related
I am doing a simple chat application between two android devices using sockets (TCP connection) the problem is it works only over LAN but doesn't work over WAN how can i fix this problem ?
ClientSide::
public class MainActivity extends AppCompatActivity {
TextView tv_device, tv_receive, tv_transmit;
Button btn_connect, btn_GPS;
EditText et_IP_Address, et_port, et_message;
Socket S;
DataOutputStream DOS;
DataOutputStream DOS2;
DataInputStream DIS;
Thread TH;
Thread TH2;
String data;
int q=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_IP_Address= (EditText) findViewById(R.id.et_IP_Address);
et_port= (EditText) findViewById(R.id.et_port);
et_message= (EditText) findViewById(R.id.et_message);
et_message.setText("GPS");
btn_connect = (Button) findViewById(R.id.btn_connect);
btn_GPS= (Button) findViewById(R.id.btn_send);
tv_transmit=(TextView) findViewById(R.id.tv_transmit);
tv_receive = (TextView) findViewById(R.id.tv_receive);
tv_device = (TextView) findViewById(R.id.tv_device);
// connection
btn_connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TH=new Thread(new Runnable() {
#Override
public void run() {
try {
S = new Socket(et_IP_Address.getText().toString(),Integer.parseInt(et_port.getText().toString()));
DOS = new DataOutputStream(S.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
});// End of thread
TH.start();
}
}); // end of buutton
// Sending
btn_GPS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TH2=new Thread(new Runnable() {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
DOS2 = new DataOutputStream(S.getOutputStream());
DOS2.writeUTF(et_message.getText().toString());
} catch (IOException e) {
e.printStackTrace();
}
tv_transmit.post(new Runnable() {
#Override
public void run() {
tv_transmit.setText(et_message.getText());
}
});
try {
DOS2.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
DIS = new DataInputStream(S.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
while (DIS!=null) {
try {
data = DIS.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
data = data.toString();
tv_receive.post(new Runnable() {
public void run() {
tv_receive.setText(data);
}
});
try {
DOS2.close();
DIS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}); // end of thread
TH2.start();
}
}); // end of button
}
#Override
protected void onStop() {
super.onStop();
try {
if(S != null)
S.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server Side::
public class MainActivity extends AppCompatActivity {
Thread TH;
String data;
Socket S;
ServerSocket ss;
DataOutputStream DOS;
String recieved="GPS";
String Response;
TextView et_port; TextView tv_receive; TextView tv_transmit; TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_port = (TextView) findViewById(R.id.et_port);
tv_receive = (TextView) findViewById(R.id.tv_receive);
tv_transmit = (TextView) findViewById(R.id.tv_transmit);
status = (TextView) findViewById(R.id.status);
Intent intent = new Intent(this, MyService.class);
startService(intent);
establishconnection();
}
public void establishconnection() {
TH = new Thread(new Runnable() {
#Override
public void run() {
status.setText(MyService.getIpAddress());
try {
ss = new ServerSocket(8080);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
S = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}
status.post(new Runnable() {
#Override
public void run() {
status.setText("connected");
}
}
);
CommunicationThread commThread = null;
try {
commThread = new CommunicationThread(S);
} catch (IOException e) {
e.printStackTrace();
}
new Thread(commThread).start();
}
}
});
TH.start();
}
class CommunicationThread implements Runnable {
private Socket ClientSocket;
DataInputStream DIS;
public CommunicationThread(Socket ClientSocket) throws IOException {
this.ClientSocket = ClientSocket;
DIS = new DataInputStream(ClientSocket.getInputStream());
data = DIS.readUTF();
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
data = data.toString();
tv_receive.post(new Runnable() {
public void run() {
tv_receive.setText(data);
}
});
while (recieved.equals(data)) {
sendMessage();
try {
DOS = new DataOutputStream(S.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
if (Response !=null){
DOS.writeUTF(Response);
}
} catch (IOException e) {
e.printStackTrace();
}
tv_transmit.post(new Runnable() {
#Override
public void run() {
tv_transmit.setText(Response);
}
});
try {
DOS.flush();
DOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
S.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendMessage() {
Intent i = new Intent(this,Gps.class);
startActivityForResult(i, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
// Bundle bundle = getIntent().getExtras();
if (data!=null) {
String x = data.getStringExtra("Latitude");
String y = data.getStringExtra("Longitude");
Response = x + "\n" + y;
}
}
}
}
}
Here the client suppose to send a word to server when the server recieves it it will open another intent and return back some data "GPS" to client
I have an AsyncTask which acts as a client and get a string from a server and puts it in a String. After the task I use the response from the server but the data haven't changed yet - it's null.
connectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
Client myClient = new Client(responseTV);
myClient.execute();
if (responseStr.charAt(0) == '1') { <----- responseStr is null
changeBrightness(Integer.parseInt(responseStr.substring(1)));
}
}
});
I assume the code keeps going after .execute() which is not very good in my situation.
Update: Added code for Client class.
public class Client extends AsyncTask<Void, Void, Void> {
String response = "";
TextView responseTV;
public Client(TextView responseTV) {
this.responseTV = responseTV;
}
#Override
protected Void doInBackground(Void... params) {
Socket socket = null;
try {
socket = new Socket(IP, PORT);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
responseTV.setText(response);
responseStr = response;
super.onPostExecute(aVoid);
}
}
if (responseStr.charAt(0) == '1') { <----- responseStr is null
changeBrightness(Integer.parseInt(responseStr.substring(1)));
}
Use this code in onPostExecute() method of AsyncTask. It runs on the UI thread and is exactly the method you need after finishing work in doInBackground().
Someone please read my code its given below,
the process dialog is not showing up,
seems like a minor mistake :D
Thanks in advance.
public class InternalData extends Activity implements OnClickListener {
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String FILENAME = "internalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
InitializeVars();
}
public void InitializeVars() {
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bSave:
String data = sharedData.getText().toString();
/*
* //Saving data via File File f = new File(FILENAME); try { fos =
* new FileOutputStream(f); fos.close(); } catch(IOException e) {
* e.printStackTrace(); }
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.bLoad:
new loadSomeStuff().execute(FILENAME);
break;
}
}
public class loadSomeStuff extends AsyncTask<String, Integer, String> {
ProgressDialog dialog = new ProgressDialog(InternalData.this);
protected void onPreExecute(String f) {
// dialog = new ProgressDialog(InternalData.this)
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// all this can be done without making this whole AsyncTask class,
// but it will exaust our activity user interface, / slow it down
String collected = null;
FileInputStream fis = null;
for (int i = 0; i < 20; i++) {
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1) {
collected = new String(dataArray);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
return collected;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
dialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result) {
dataResults.setText(result);
}
}
}
Change your onPreExecute() you're using it wrong, you should this instead
#Override
protected void onPreExecute() {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
I am using an asynctask while I am doing some telnet operations. However, the progressdialog is not shown, and I am almost 100% sure that Telnet is the cause.
Please take a look to my code and help me to find where is the problem.
Thanks
public class TelnetManager extends AsyncTask<String, Void, String>{
private TelnetClient telnet;
private int port;
private String IP;
private ProgressDialog dialog;
private Context context;
public TelnetManager(Context c,String IP, int port, String user, String pass)
{
context=c;
this.IP=IP;
this.port=port;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(context);
dialog.setMessage(context.getResources().getString(R.string.msg_wait));
dialog.show();
}
public String readString() throws IOException
{
InputStream in = new BufferedInputStream(telnet.getInputStream());
int read=0;
String s=null;
do
{
byte[] buffer = new byte[1024];
read = in.read(buffer);
if(read > 0)
{
if(s==null)s=new String(buffer, 0, read);
else s+=new String(buffer, 0, read);
Log.e("S",s);
}
}
while (read > 0);
in.close();
return s;
}
public void writeString(String command) throws IOException
{
OutputStream out = telnet.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
writer.write(command+'\n');
writer.flush();
}
#Override
protected String doInBackground(String... params) {
telnet = new TelnetClient();
String s="";
try {
telnet.setConnectTimeout(10000);
telnet.connect(IP,port);
telnet.setKeepAlive(true);
writeString("password");
writeString(params[0]);
writeString("exit");
String aux=readString();
telnet.getInputStream().close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
telnet.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(dialog!=null && dialog.isShowing())
{
dialog.dismiss();
}
}
}
And here is where I call the AsyncTask:
String list=null;
try {
list=new TelnetManager(this,"192.168.11.30", 10010, null, null).execute("son").get();
construirLayout(list,R.id.containerON);
list=new TelnetManager(this,"192.168.11.30", 10010, null, null).execute("soff").get();
construirLayout(list,R.id.containerOFF);
}
catch (InterruptedException e) {
Toast.makeText(this,"InterruptedException",3000).show();
e.printStackTrace();
}
catch (ExecutionException e) {
Toast.makeText(this,"ExecutionException",3000).show();
e.printStackTrace();
}
If you call get() on an AsyncTask, you're telling the UI thread to block and wait for the AsyncTask results. Since the UI thread is blocked, it cannot show the ProgressDialog.
You should instead provide a callback to the AsyncTask, to be fired in onPostExecute().
i've done an application in which the android application send datas to java desktop swing application as well as send datas from desktop to android using TCP socket programming through wifi.
Th application is a Hotel Kitchen order booking system
The problem describes that Dine_Tables class contains buttons which represents each tables in a hotel, on clicking table1 button for example it starts the BackgroundServers Asyntask which runs a server for receiving desktop application datas also it takes the activity from Dinein_Tables.java to Food_Customizer.java.
In Food_Customizer.java on clicking submit button it starts ServersendAsyncAction Asyntask which sends some datas to desktop swing application.
The desktop application after processing sends some datas to android application, The server that runs in the android application on receiving the datas goes again from Food_Customizer.java to Dinein_Tables.java activity in the BackgroundServers Asyntask onPostExecute method.
The problem is that when i do this process a two or three times the application stop due to address-in use and Null-Pointer exception at socket = serverSocket.accept(); in the BackgroundServers Asyntask.
Can anyone please tell me some solution for this problem
Dinein_Tables.java
public class Dinein_Tables extends Activity {
:
:
table1.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
Food_Customizer.BackgroundServers ob = new Food_Customizer().new BackgroundServers(contexts);
ob.execute("");
Intent toAnotherActivity = new Intent(v.getContext(), Food_Customizer.class);
startActivity(toAnotherActivity);
finish();
}
}, 100L);
}
});
}
Food_Customizer.java
public class Food_Customizer extends Activity {
:
:
submit= (Button)findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd = ProgressDialog.show(contexts, "Sending to Server...","Please Wait...", true, false);
new ServersendAsyncAction().execute();
}
});
:
:
/****************************** AsyncTask ********************************************************/
private class ServersendAsyncAction extends AsyncTask<String, Void, String> {
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
boolean flag = true;
while (flag) /******** If data is send flag turn to be false *******/
{
try {
socket = new Socket("192.168.1.74", 4444);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(datastosend);
flag = false;
} catch (UnknownHostException e) {
flag = true;
e.printStackTrace();
} catch (IOException e) {
flag = true;
e.printStackTrace();
}
/******** CLOSING SOCKET *****************/
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAOUTPUTSTREAM *******/
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAINPUTSTREAM ********/
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
protected void onPostExecute(String result) {
}
/********************* ENDING OF ASYN TASK CLASS ServersendAsyncAction ***************************/
}
public Context con;
public static ServerSocket serverSocket = null;
public class BackgroundServers extends AsyncTask<String, Void, String> {
public BackgroundServers(Context context) {
con=context;
}
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(9999);
System.out.println("Listening :9999");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
String incoming_message=(dataInputStream.readUTF());
incoming_message=incoming_message.replace("/", "");
String recdatas[]=incoming_message.split("#");
if(recdatas[0].equalsIgnoreCase("success"))
{
DatabaseConnection dbs=new DatabaseConnection(con);
int status=dbs.update("UPDATE hotel_pub_tables SET status='occupied' WHERE tableno='"+recdatas[1]+"'");
if(status>0)
{
tabelstatus=1;
//msg.obj="Table status changed!!!";
System.out.println("Table status changed!!!");
if (true) {
System.out.println("entered 222");
System.out.println(tabelstatus);
if(tabelstatus==1)
{
System.out.println(tabelstatus);
Food_Customizer.pd.dismiss();
System.out.println("success");
}
else if(tabelstatus==2)
{
Food_Customizer.pd.dismiss();
Intent intent = new Intent(Food_Customizer.this, Dinein_Tables.class);
startActivity(intent);
finish();
}
}
}
else
tabelstatus=2;
dbs.close();
}
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
#Override
protected void onPostExecute(String result) {
System.out.println("eneterd on posttttttttttttttt");
con.startActivity(new Intent(con, Dinein_Tables.class));
finish();
}
}
}
/********************* ENDING OF ASYN TASK CLASS BackgroundServers ***************************/
}
Well it's obvious that you setup your server on port 9999:
serverSocket = new ServerSocket(9999);
But you connect with the server on port 4444:
socket = new Socket("192.168.1.74", 4444);
Make sure you connect to the correct port-number otherwise it wont work. Hope this helps.