ginc0de
ginc0de

Reputation: 161

Socket.isConnected() make my android app force close

I don't know what happen with my source code about Socket in Android, when I use method

.isConnected()

My app always force close. And here my source code

public class MyActivity extends Activity {
    private String IP;
    private int PORT;
    private Socket socket;
    private PrintWriter printWriter;
    private TextView text;

    private EditText fieldIp;
    private EditText fieldPort;


    private Button connect;
    private FrameLayout frameIP;

    private String message;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        frameIP = (FrameLayout)findViewById(R.id.frameIP);
        connect = (Button)findViewById(R.id.connect);
        fieldIp = (EditText)findViewById(R.id.ip);
        fieldPort = (EditText)findViewById(R.id.port);
        text = (TextView)findViewById(R.id.keterangan);
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IP = fieldIp.getText().toString();
                PORT = Integer.parseInt(fieldPort.getText().toString());
                SocketConnect socketConnect = new SocketConnect(IP,PORT);
                socketConnect.execute();
            }
        });
    }


    private class SocketConnect extends AsyncTask<Void, Void, Boolean> {

        String ip;
        int port;

        public SocketConnect(String a, int b){
            this.ip = a;
            this.port = b;
        }


        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                socket = new Socket();
                socket.connect(new InetSocketAddress(ip,port));
                if(socket.isConnected())
                {
                    text.setText("Connected!");
                }
                else
                {
                    text.setText("Failed to connect!");
                }
            } catch (IOException e) {
                Log.e("MyActivity",e.getMessage());
            }
            finally {
                startActivity(new Intent(getApplicationContext(),ListViewText.class));
            }
            return null;
        }
    }
}

And I use this in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

I hope you can help me guys :(

Upvotes: 0

Views: 205

Answers (2)

VizGhar
VizGhar

Reputation: 3128

First thing you are calling UI operation outside of UI thread (that is why AsyncTask was created, to handle background job only in doInBackground) So problem about displaying text un TextView is solved...

But more important thing:

Never open Socket in AsyncTask. On Android developer site you can find following:

If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.)

And that is exactly what you want to do. So use Service, Thread or those mentioned above instead.

Upvotes: 1

Squonk
Squonk

Reputation: 48871

Change the doInBackground method as follows...

@Override
protected Boolean doInBackground(Void... params) {

    boolean success = true;

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port));
    } catch (Exception e) {
        success = false;
        Log.e("MyActivity", e.getMessage());
    }
    return success;
}

Then add an onPostExecute method...

@Override
protected void onPostExecute(boolean result) {
    if(result) {
        text.setText("Connected!");
        startActivity(new Intent(MyActivity.this, ListViewText.class));
    }
    else {
        text.setText("Failed to connect!");
    }
}

Upvotes: 1

Related Questions