-2

I looked up my error online and people are telling to run the networking stuff on another thread or asyncTask but i have no clue how to fix this... So everything works, app launches but then crashed and tells me "android.os.NetworkOnMainThreadException"

Here is my code:

public class Activity2 extends AppCompatActivity {
    private static final String TAG = Activity2.class.getSimpleName();
    private TextView fileContent;
    String endstring = "";

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);
        fileContent = (TextView) findViewById(R.id.content_from_server);
        try {
            loadstuff();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private void loadstuff() throws IOException {


        URL url = new URL("http://ipaddress/login.php"); // URL to your application
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("username", "test"); // All parameters, also easy
        params.put("password", "test");

        StringBuilder postData = new StringBuilder();
        // POST as urlencoded is basically key-value pairs, as with GET
        // This creates key=value&key=value&... pairs
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        // Convert string to byte array, as it should be sent
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        // Connect, easy
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        // Tell server that this is POST and in which format is the data
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        // This gets the output from your server
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)

            endstring = endstring + (char)c;
            fileContent.setText(endstring);


    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135

3 Answers3

0

This exception occurs from API 11 or Android version 3.0, such as the real name, the process of discussion of chain messages in the main process (hence the name MainThread), in previous histories this operation is allowed although it is not recommended, depending on the time the process is needed, ANR (Application Not Responding).

The ideal solution is called this way because it is the form indicated by the android community, to implement this solution we must implement an inheritance of the class AsyncTask, this class allows to perform operations in the background

You can use too some library like retrofit, coroutine etc..

let me know if you resolved this issue :)

Henrique
  • 36
  • 2
  • so i'm supposed to put loadstuff() into the asynctask class, but where do i put that class and how do i call it where my loadstuff() previously used to be? – AndroidSpirit Mar 14 '19 at 19:55
0

Hi like Henrique says you need to use an AsyncTask, its a class inside your class something like this

public class NameOfTask extends AsyncTask<Void, Void, Boolean>{

    @Override
    protected Boolean doInBackground(Void... voids) {
        /*your code goes here*/
        return true;
    }
    @Override
    protected void onPostExecute(final Boolean success) {
       /*If you need to do something after the task*/
    }

    @Override
    protected void onCancelled() {
        //if cancel you may need to do something in here
    }
}

And calling you just need to call the class that you created. something like this:

 NameOfTask task = new NameOfTask();
 task.execute((Void)null);
950CA
  • 1
  • 3
0
public class Activity2 extends AppCompatActivity {
    private static final String TAG = Activity2.class.getSimpleName();
    private TextView fileContent;
    String endstring = "";

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);

        fileContent = (TextView) findViewById(R.id.content_from_server);

        new AsyncLoadStuff().execute()


    }

    private void loadstuff() throws IOException {


        URL url = new URL("http://ipaddress/login.php"); // URL to your application
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("username", "test"); // All parameters, also easy
        params.put("password", "test");

        StringBuilder postData = new StringBuilder();
        // POST as urlencoded is basically key-value pairs, as with GET
        // This creates key=value&key=value&... pairs
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        // Convert string to byte array, as it should be sent
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        // Connect, easy
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        // Tell server that this is POST and in which format is the data
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        // This gets the output from your server
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)

            endstring = endstring + (char)c;
            fileContent.setText(endstring);


    }
}


You can do something like this ...

//Its may be a inner class
// LoadStuff inside this class, it will be executed on separated class 
 private class AsyncLoadStuff extends AsyncTask<String, String, String> {


        @Override
        protected String doInBackground(String... params) {
             try {
                loadstuff();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(String result) {
            //put load wait
        }

    }
Henrique
  • 36
  • 2