0

I am doing a project which sends data over a WiFi router to a destination IP. I have placed a switch button. When the switch button is turned on, some pre-written data is sent to the IP.

I am unable to listen anything at the destination. I have attached the code.

MainActivity.java:

package com.project.saket.switchsocket;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.CompoundButton.OnCheckedChangeListener;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {

        private Switch switch1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
            switch1 = (Switch) findViewById(R.id.switch1);
            switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                    if (isChecked) {
                        new SuriSocket("$ASAS,F1#");
                    } else {
                        new SuriSocket("$ASAS,F0#");
                    }
                }
            });
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

SuriSocket.java:

package com.project.saket.switchsocket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SuriSocket {
    private Socket output;
    private static final int SERVERPORT = 8080;
    private static final String SERVER_IP = "192.168.0.131";

    private boolean setup() {
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            output = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
            return false;
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }
        return true;
    }


    public SuriSocket(String sMessage) {
        if (setup()) {
            try {
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(output.getOutputStream())),
                        true);
                out.println(sMessage);
                out.flush();
                out.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

1

You have a NetworkOnMaiThreadException clearly visible in the LogCat of your IDE. Place network and socket code in an AsyncTask or thread.

greenapps
  • 11,154
  • 2
  • 16
  • 19
  • Can you guide me as to how to put my code into an Async Task? – Saket Suri Feb 13 '16 at 01:46
  • Yes i can but will not do as its better you read a lot of pages on this forum for that. There are so many examples to find if you just look around. And you are not the first one who encountered this problem. – greenapps Feb 13 '16 at 08:56
  • I have some trouble in including the AsyncTask. Help please.. – Saket Suri Feb 14 '16 at 07:05
  • Which trouble exactly? – greenapps Feb 14 '16 at 10:15
  • I read about AsyncTask and its implementation. Now, which part of my code should go into the doInBackground() of the AsyncTask? The UI part cannot be put in the AsyncTask. So I have to implement it in SuriSocket.java. But where? I am not able to figure it out. Which method should I be calling in the doInBackground() ? – Saket Suri Feb 16 '16 at 02:35
  • You should do all socket and network calls in doInBackground of an AsyncTask. Then update the gui in the onPostExecute of the same AsyncTask. You will need several AsyncTasks or threads if the user can do a number of network actions. – greenapps Feb 16 '16 at 07:39
  • You can also update the gui calling publishProgress in doInBackground and implementing onProgressUpdate. But this is only usefull for ... a progress indicator. Like when you are downloading a lot of data. – greenapps Feb 16 '16 at 07:45
  • I get it. But in my code, where is that I have to include the AsyncTask? – Saket Suri Feb 16 '16 at 12:02
  • Include?? What do you mean? One creates an async task with new() and then execute() it. So do that where you need it. – greenapps Feb 16 '16 at 12:34