Reputation: 954
I'm currently struggling to create a mobile (Android) version of a "battleship" program I recently coded. While my GUI is finished by now and most parts of the program should work, I have (at least) one main problem left: the main part of my program besides the server part (which will react to user input, etc.) relies on Java NIO, i.e. network access. However, since it's running on the main thread, I receive
java.lang.RuntimeException: Unable to start activity ComponentInfo{x.battleship/x.battleship.BattleshipMain}: android.os.NetworkOnMainThreadException`
(I replaced the package name with x for privacy reasons).
Hence, my question is: how can I start an activity as a new Thread? so far, i have used
Intent i = new Intent(getApplicationContext(), BattleshipMain.class);
startActivity(i);
i.putExtra("ip",joinip);
i.putExtra("port",joinport);
at first, i thought this would be an alternative:
new Thread(new Runnable() {
@Override
public void run() {
Intent i = new Intent(getApplicationContext(), BattleshipMain.class);
startActivity(i);
i.putExtra("ip",joinip);
i.putExtra("port",joinport);
}
});
However, it doesn't seem to work - I get a message in the console, that BattleshipMain
has been started, but nothing actually shows up on the display (except whatever was there already).
does anybody have an idea what to do? I really don't know how to solve this; I'm still new to Android, though, and not really a long-term expert in java either.
Thanks in advance!
//edit: I'm not too familiar if I'm supposed to do this, but after I moved the networking code to a separate thread, it seems to me that I'm unable to connect the app on my phone to a server running on my PC. They're in the same network & the server should be compatible with the mobile app, but considering the errors / freeze screens I receive, I don't see what else could be the problem. Does Java NIO work normally on android at all / could I possibly connect a client on my phone (which is a Galaxy S3, btw -> API 18) to a server on a PC with Windows? Thank you! :)
//edit: nevermind, the error was 100% dumb. When using an Intent to create a new activity, i created the intent, launched it, and THEN used intentname.putExtra(key, value) - which obviously didn't work. Right now, I got another error because I tried to change a checkBox from a different thread, but the network part worked, so I guess I'll be done soon.
Upvotes: 2
Views: 97
Reputation: 6610
The problem you're having is that you're doing networking on the main thread, which is prohibited. Move all networking and network/api calls into AsyncTask
s and it should be good to go.
EDIT: apart from that, please, abandon the idea of starting activities as threads, as Activities have their own lifecycle which is described here
EDIT2: perhaps if you manage to turn off StrictMode (available in developer options) you could do networking on the main thread but... i wouldn't count on it.
Upvotes: 2