Why my java app for android not connect to server?
Posted
by
FredVaz
on Stack Overflow
See other posts from Stack Overflow
or by FredVaz
Published on 2011-11-19T01:39:32Z
Indexed on
2011/11/19
1:50 UTC
Read the original article
Hit count: 149
Why my java app for android not connect to server ?
I run the aplication in android emulator, and the server wich port 9999 and host 127.0.0.1 in my pc, but just not connect and i think this method isn't good for android app.
It is my source code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//Java imports
//import android.util.Log;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends Activity
{
//Variaveis Interface
private Button ligar;
private Button enviar;
private EditText text1;
private TextView text2;
//Variaveis
static Socket cSocket;
static PrintWriter out;
static BufferedReader in;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Declaração butões
ligar = (Button) findViewById(R.id.ligar);
enviar = (Button) findViewById(R.id.enviar);
text1 = (EditText) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
//Interacao
ligar.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
connect();
}
});
enviar.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
out.println("Hello");
text2.setText("");
}
});
}
//Outras Funcoes
public void connect(){
//Funcao ligar
cSocket = null;
out = null;
in = null;
try
{
cSocket = new Socket("127.0.0.1",9999);
out = new PrintWriter(cSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
text2.setText("Estas conectado com sucesso.");
}
catch (IOException ex) {
//Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
text2.setText("Erro! Na conexão");
}
}
//
}
© Stack Overflow or respective owner