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);
}
}