0

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 :(

ginc0de
  • 151
  • 1
  • 2
  • 12
  • Can you post your logcat stacktrace? – ataulm Jan 25 '15 at 21:29
  • possible duplicate of [Unfortunately MyApp has stopped. How can I solve this?](http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) ... but it is pretty obvious that, in fact, it is yet another NOMTE question – Selvin Jan 25 '15 at 21:29
  • 2
    @Selvin : No. This isn't a NOMTE issue - there's nothing in the OP's code which shows any network operations on the main thread. It's actually the other way around - the thread running `doInBackground` is attempting to modify the text in a `TextView`. – Squonk Jan 25 '15 at 22:11
  • This problem has exactly nothing to do with the `isConnected()` method, as a little more investigation on your part would have disclosed. You don't even have to call it at all here: see my comment under @Squonk's answer. – user207421 Jan 25 '15 at 22:35

2 Answers2

1

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!");
    }
}
Squonk
  • 48,735
  • 19
  • 103
  • 135
  • 1
    The `isConnected()` call is completely pointless here. It cannot possibly return false at the point you are calling it. You just called `connect():` there was no exception; *ergo* it is connected. If you don't enter the exception handler, setup to display 'success': if you do enter the exception handler, setup to display 'failure'. – user207421 Jan 25 '15 at 22:15
  • @EJP : Valid point. I'll admit it's been a while since I worked with `Sockets` and I was just working with the OP's code. – Squonk Jan 25 '15 at 22:25
  • It works guys, thanks @Squonk and all who have answered my question. Do you have any blog as my reference to learn socket android? – ginc0de Jan 26 '15 at 12:34
1

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.

VizGhar
  • 3,036
  • 1
  • 25
  • 38