-1

I have the code below in my androidStudio and whenever I click on the button I get the Error : "NetworkOnMainThreadException".

I also use AsyncTask too. I've added to my manifest too... I'll be glad if you tell me how to fix my problem . And tell me if there is any problem in My code that doesn't work or is wrong.

package stach;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.io.*;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.net.InetAddress;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class UserPassCon extends AppCompatActivity {

    public static String ServerKind;
    public static Button b;
    public static TextView t;
    public static EditText U;
    public static EditText P;
    TextView editText;
    String PassCode;
    String Username;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_pass_con);
        b = (Button) findViewById(R.id.Connect);
        t = (TextView) findViewById(R.id.textView2);
        U = (EditText) findViewById(R.id.UserName);
        P = (EditText) findViewById(R.id.PassWord);

        editText = (TextView) findViewById(R.id.textView2);
        editText.setText(ServerKind);
        new GetI().execute();

    }
}




class GetI extends AsyncTask<URL, Void, String> {

    protected void sendPost() throws Exception {

        String url = "https://www..google.com/";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("ServerKind", UserPassCon.ServerKind);
        con.setRequestProperty("Password", UserPassCon.P.getText().toString());
        con.setRequestProperty("Username", UserPassCon.U.getText().toString());
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        String[] Res = response.toString().split("=");

        if (Res[0] == "error") {
           UserPassCon.t.setText("error");
        }
        if (Res[0] == "ok") {
            Socket s = new Socket();
            try {
                s.connect(new InetSocketAddress(Res[1], 510));
            }
            //Host not found
            catch (UnknownHostException e) {

                UserPassCon.t.setText("host not found !");

            }
            UserPassCon.b.setText("Connected");
        }
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        UserPassCon.b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    sendPost();
                } catch (Exception e) {
     UserPassCon.t.setText(e.toString());//the Exception will be caught here .
                }
            }
        });
    }

    @Override
    protected String doInBackground(URL... params) {

        return null;
    }

}

As I said I've tried AsyncTask... I should run the http request in GetI class on button click... If you know any other way please leave your answers here... Thanks in Advance!

MD Naseem Ashraf
  • 1,030
  • 2
  • 9
  • 22

1 Answers1

1

The problem is found in your code. You are calling sendPost() in onPostExecute method rather in doInBackground. You must call your sendPost() in doInBackground else you will get NetworkOnMainThreadException. This happens because onPostExecute() is called on Main thread. Any network related task is not allowed to be executed on Main Thread. You are indeed using AsynTask. but this is not useful because to perform task on different thread or separate thread one need to use doInBackground() . Hope this helps you .

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58
  • Thank you Sir... But I should change all of my OnClickListener place to doInBackground but now I get the errror "Method setOnClickListener must be called from the UI thread, currently inferred thread is worker" in my code. – Zanyar Ghazali Apr 03 '19 at 18:33
  • You want to perform netwrok task when onclick listeners is called? – Abdul Waheed Apr 03 '19 at 18:35
  • if this is the case then when OnClickListener is called use your code ' new GetI().execute();' inside that click listener event – Abdul Waheed Apr 03 '19 at 18:35
  • Excuse me Sir to have troubled you ! When I click on my button now i'm thrown to my main activity page ! I did as you said ! I needed another "try set post catch" in my do In Background and I think it throws me to activity main ! Any Idea ? – Zanyar Ghazali Apr 04 '19 at 07:58
  • please post your code with onclick handling event – Abdul Waheed Apr 04 '19 at 11:48
  • Excuse Abdul Waheed is there any other way i can contact you ? Like Instagram or other thing... I should ask you some questions that I can't ask them all here.... I'll be so glad if you tell me where I can contact you... – Zanyar Ghazali Apr 04 '19 at 14:58