I'm getting android.os.NetworkOnMainThreadException and another unknown exception from the OutputStreamWriter()

By | October 30, 2018
Questions:

I am getting exceptions for NetworkOnMainThreadException and an unknown exception from the OutputStreamWriter(). This class is responsible for connecting to an SQL database via PHP script http://213.251.43.215/addContact.php which will return values from the database if matched. It does not appear to be connecting successfully.

package com.example.a_phi.nowswap;

import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class EstablishConnection extends AsyncTask<String, Void, String>{

    StringBuilder sb = new StringBuilder();

    public String doInBackground(String... id) {

        String link = "http://213.251.43.215/addContact.php";

        try {
            URL url = new URL(link);
            String data = URLEncoder.encode("id", "UTF-8")
                    + "=" + URLEncoder.encode(id[0], "UTF-8");

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));

            String line;

            // Read Server Response
            while((line = reader.readLine()) != null) {
                sb.append(line);
                break;
            }

        }catch(MalformedURLException e) {
            System.out.print("MalformedURLException" + e.getMessage());
            e.printStackTrace();
        }
        catch(IOException e){
            System.out.print("IOException"+e.getMessage());
            e.printStackTrace();
        }

        return sb.toString();
}

}

The Pilot class…

package com.example.a_phi.nowswap;

import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.nfc.Tag;
import android.content.Intent;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class Pilot extends AppCompatActivity {

    private String mParentPath;
    // Incoming Intent
    private Intent mIntent;
    public Timer timer1 = new Timer();
    NfcAdapter nfcadapter;
    public String idReceived;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pilot);
        View buttonPersonal = findViewById(R.id.buttonPersonal);
        View buttonProfessional = findViewById(R.id.buttonProfessional);
        View buttonUserGuide = findViewById(R.id.userGuide);
        //phone is put into reader mode to prevent android beam interfering
        enableReaderMode();
        //executes createContact() method periodically every second to refresh
        getData accessGetData = new getData();
        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                createContact();
            }
        }, 500, 500);




        PackageManager pm = this.getPackageManager();
        if(!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
            Toast.makeText(this, "The device does not have NFC hardware.",
                    Toast.LENGTH_SHORT).show();
        } else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            Toast.makeText(this, "Android Beam is not supported.",
                    Toast.LENGTH_SHORT).show();
        }

            buttonPersonal.setOnClickListener(new View.OnClickListener(){

                public void onClick(View v){
                    Intent loadPersonal = new Intent(Pilot.this, personalHome.class);
                        startActivity(loadPersonal);

                }
            });

        buttonProfessional.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v){
                Intent loadProfessional = new Intent(Pilot.this, professionalHome.class);
                startActivity(loadProfessional);
            }

        });


    }



    private byte[] selectApdu(byte[] aid) {
        byte[] commandApdu = new byte[6 + aid.length];
        commandApdu[0] = (byte)0x00; //CLA
        commandApdu[1] = (byte)0xA4; //INS
        commandApdu[2] = (byte)0x04; //P1
        commandApdu[3] = (byte)0x00; //P2
        commandApdu[4] = (byte)(aid.length & 0xFF); //Lc
        System.arraycopy(aid, 0, commandApdu, 5, aid.length); //DATA
        commandApdu[commandApdu.length - 1] = (byte)0x00; //Le
        return commandApdu;
    }



    /**enableReaderMode essentially turns off services such as Android Beam and ensures the device only READS nfc tags
     * allowing a smoother user interaction
     */
    @TargetApi(19)
    private void enableReaderMode() {
        nfcadapter = NfcAdapter.getDefaultAdapter(this);
        Bundle options = new Bundle();
        options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 5000);
        nfcadapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
            @Override
            public void onTagDiscovered(Tag tag) {
                System.out.println("NFC onTagDiscovered " + tag.toString());
                IsoDep isoDep = IsoDep.get(tag);
                if (isoDep != null) {
                    try {
                        isoDep.connect();
                        //SelectAID command is sent to phone with HCE
                        byte[] result = isoDep.transceive(selectApdu(SelectAID));
                        idReceived = new String(result, "US-ASCII");
                        System.out.println("s outputs this "+ idReceived.substring(0,10));
                        idReceived = idReceived.substring(0,10);
                        checkProfile();
                        isoDep.close();
                        EstablishConnection accessEC = new EstablishConnection();
                        System.out.println("hello");
                        System.out.println("Dataset is "+accessEC.doInBackground(idReceived));
                    } catch(IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            isoDep.close();
                        } catch(Exception ignored) {}
                    }
                }
            }
        }, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
                options);
    }

    public String getIdReceived(){
        return idReceived;
    }

    public void checkProfile(){
        getData accessGetData = new getData();
     //   System.out.println("hashlist value is "+accessGetData.doInBackground());
    }


    public static byte[] SelectAID = new byte[]{ (byte) 0xF2, (byte) 0x39, (byte) 0x85, (byte) 0x63,
            (byte) 0x24, (byte) 0x89, (byte) 0x73};

    public void createContact() {

        File newContact = new File("/storage/emulated/0/beam/", "personalInfoC.txt");

        /**there is a glitch on android beam with the file naming - sometimes it calls the file professionalInfoC.txt
        and other times professionalInfoC-0.txt **/
        if(!newContact.exists()) {
            newContact = new File("/storage/emulated/0/beam", "personalInfoC-0.txt");
            if(!newContact.exists()){
                File newContactProf = new File("/storage/emulated/0/beam", "professionalInfoC.txt");
                if(newContactProf.exists()){
                    //new activity will only be loaded if the file exists
                    Intent loadNewContact = new Intent(Pilot.this, receivedContact.class);
                    finish();
                    timer1.cancel();
                    startActivityForResult(loadNewContact, 1);

                }
                else if(!newContactProf.exists()){
                    newContactProf = new File("/storage/emulated/0/beam", "professionalInfoC-0.txt");
                    if(newContactProf.exists()) {
                        Intent loadNewContact = new Intent(Pilot.this, receivedContact.class);
                        finish();
                        timer1.cancel();
                        startActivityForResult(loadNewContact, 1);

                    }
                }
            }
        }
    };




}

Here is the stack trace

   07-19 00:53:14.436 13679-13692/com.example.a_phi.nowswap W/System.err: android.os.NetworkOnMainThreadException
              at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1315)
      07-19 00:53:14.437 13679-13692/com.example.a_phi.nowswap W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
              at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
              at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
              at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
              at java.net.Socket.connect(Socket.java:592)
              at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
              at com.android.okhttp.Connection.connectSocket(Connection.java:196)
              at com.android.okhttp.Connection.connect(Connection.java:172)
              at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
              at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
              at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
              at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
              at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
              at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
              at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:257)
              at com.example.a_phi.nowswap.EstablishConnection.doInBackground(EstablishConnection.java:29)
              at com.example.a_phi.nowswap.Pilot$4.onTagDiscovered(Pilot.java:121)
              at android.nfc.NfcActivityManager.onTagDiscovered(NfcActivityManager.java:450)
              at android.nfc.IAppCallback$Stub.onTransact(IAppCallback.java:83)
              at android.os.Binder.execTransact(Binder.java:565)

How do I resolve this issue? Any help would be much appreciated.

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *