Using OnSuccessListener and then use a PrintStream in the method gets me an error
I'm using Google API to get the location of a device and I have to use OnSuccessListener but I tried to use a PrintStream so it sends the location when its successful but it gives me a NetworkOnMainThreadException
I tried using handlers and I saw that i can use an AsyncTask but i dont know where, I really think the problem is the onSuccess but i couln't find anything that helped
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
clientConnection.sendtoServer("loc",addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea());//this line is the problem
}
else
clientConnection.sendtoServer("loc","Not Found!");
}
clientConnection.sendtoServer is the problem
//this is used for a Socket the class of the socket is clientConnection
public static void sendtoServer(String TextCode,String message){
os.println(TextCode+" "+message);
os.flush();
}
this is my error
2019-01-01 19:24:51.037 7077-7077/com.example.victor.zactarget E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.victor.zactarget, PID: 7077
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:157)
at java.io.PrintStream.write(PrintStream.java:492)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.write(PrintStream.java:543)
at java.io.PrintStream.print(PrintStream.java:687)
at java.io.PrintStream.println(PrintStream.java:824)
at com.example.victor.zactarget.ClientConnection.sendtoServer(ClientConnection.java:118)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:66)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:54)
at com.google.android.gms.tasks.zzn.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
android google-maps socket.io
add a comment |
I'm using Google API to get the location of a device and I have to use OnSuccessListener but I tried to use a PrintStream so it sends the location when its successful but it gives me a NetworkOnMainThreadException
I tried using handlers and I saw that i can use an AsyncTask but i dont know where, I really think the problem is the onSuccess but i couln't find anything that helped
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
clientConnection.sendtoServer("loc",addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea());//this line is the problem
}
else
clientConnection.sendtoServer("loc","Not Found!");
}
clientConnection.sendtoServer is the problem
//this is used for a Socket the class of the socket is clientConnection
public static void sendtoServer(String TextCode,String message){
os.println(TextCode+" "+message);
os.flush();
}
this is my error
2019-01-01 19:24:51.037 7077-7077/com.example.victor.zactarget E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.victor.zactarget, PID: 7077
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:157)
at java.io.PrintStream.write(PrintStream.java:492)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.write(PrintStream.java:543)
at java.io.PrintStream.print(PrintStream.java:687)
at java.io.PrintStream.println(PrintStream.java:824)
at com.example.victor.zactarget.ClientConnection.sendtoServer(ClientConnection.java:118)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:66)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:54)
at com.google.android.gms.tasks.zzn.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
android google-maps socket.io
add a comment |
I'm using Google API to get the location of a device and I have to use OnSuccessListener but I tried to use a PrintStream so it sends the location when its successful but it gives me a NetworkOnMainThreadException
I tried using handlers and I saw that i can use an AsyncTask but i dont know where, I really think the problem is the onSuccess but i couln't find anything that helped
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
clientConnection.sendtoServer("loc",addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea());//this line is the problem
}
else
clientConnection.sendtoServer("loc","Not Found!");
}
clientConnection.sendtoServer is the problem
//this is used for a Socket the class of the socket is clientConnection
public static void sendtoServer(String TextCode,String message){
os.println(TextCode+" "+message);
os.flush();
}
this is my error
2019-01-01 19:24:51.037 7077-7077/com.example.victor.zactarget E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.victor.zactarget, PID: 7077
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:157)
at java.io.PrintStream.write(PrintStream.java:492)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.write(PrintStream.java:543)
at java.io.PrintStream.print(PrintStream.java:687)
at java.io.PrintStream.println(PrintStream.java:824)
at com.example.victor.zactarget.ClientConnection.sendtoServer(ClientConnection.java:118)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:66)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:54)
at com.google.android.gms.tasks.zzn.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
android google-maps socket.io
I'm using Google API to get the location of a device and I have to use OnSuccessListener but I tried to use a PrintStream so it sends the location when its successful but it gives me a NetworkOnMainThreadException
I tried using handlers and I saw that i can use an AsyncTask but i dont know where, I really think the problem is the onSuccess but i couln't find anything that helped
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
clientConnection.sendtoServer("loc",addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea());//this line is the problem
}
else
clientConnection.sendtoServer("loc","Not Found!");
}
clientConnection.sendtoServer is the problem
//this is used for a Socket the class of the socket is clientConnection
public static void sendtoServer(String TextCode,String message){
os.println(TextCode+" "+message);
os.flush();
}
this is my error
2019-01-01 19:24:51.037 7077-7077/com.example.victor.zactarget E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.victor.zactarget, PID: 7077
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:157)
at java.io.PrintStream.write(PrintStream.java:492)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.write(PrintStream.java:543)
at java.io.PrintStream.print(PrintStream.java:687)
at java.io.PrintStream.println(PrintStream.java:824)
at com.example.victor.zactarget.ClientConnection.sendtoServer(ClientConnection.java:118)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:66)
at com.example.victor.zactarget.Code$2.onSuccess(Code.java:54)
at com.google.android.gms.tasks.zzn.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
android google-maps socket.io
android google-maps socket.io
edited Jan 3 at 0:13
Vspoke91
asked Jan 2 at 1:13
Vspoke91Vspoke91
11
11
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
I found the Answer but is still I think it can be done better
public static void sendLocation(final ClientConnection clientConnection) throws InterruptedException
{
final boolean ready = new boolean[1];
final String locationString = new String[1];
client = LocationServices.getFusedLocationProviderClient(activityContext);
if (ActivityCompat.checkSelfPermission(activityContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
clientConnection.sendtoServer("loc","Denied");
}
client.getLastLocation().addOnSuccessListener(activityContext, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationString[0] = addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea();
/*
String address = addresses.get(0).getSubLocality();
String cityName = addresses.get(0).getLocality();
String stateName = addresses.get(0).getAdminArea();
String countryName = addresses.get(0).getCountryName();
*/
}
else
locationString[0] ="Not Found!";
ready[0] = true;
}
});
while (ready[0] != true){
TimeUnit.MILLISECONDS.sleep(500);
}
clientConnection.sendtoServer("loc", locationString[0]);
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000216%2fusing-onsuccesslistener-and-then-use-a-printstream-in-the-method-gets-me-an-erro%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I found the Answer but is still I think it can be done better
public static void sendLocation(final ClientConnection clientConnection) throws InterruptedException
{
final boolean ready = new boolean[1];
final String locationString = new String[1];
client = LocationServices.getFusedLocationProviderClient(activityContext);
if (ActivityCompat.checkSelfPermission(activityContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
clientConnection.sendtoServer("loc","Denied");
}
client.getLastLocation().addOnSuccessListener(activityContext, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationString[0] = addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea();
/*
String address = addresses.get(0).getSubLocality();
String cityName = addresses.get(0).getLocality();
String stateName = addresses.get(0).getAdminArea();
String countryName = addresses.get(0).getCountryName();
*/
}
else
locationString[0] ="Not Found!";
ready[0] = true;
}
});
while (ready[0] != true){
TimeUnit.MILLISECONDS.sleep(500);
}
clientConnection.sendtoServer("loc", locationString[0]);
}
add a comment |
I found the Answer but is still I think it can be done better
public static void sendLocation(final ClientConnection clientConnection) throws InterruptedException
{
final boolean ready = new boolean[1];
final String locationString = new String[1];
client = LocationServices.getFusedLocationProviderClient(activityContext);
if (ActivityCompat.checkSelfPermission(activityContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
clientConnection.sendtoServer("loc","Denied");
}
client.getLastLocation().addOnSuccessListener(activityContext, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationString[0] = addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea();
/*
String address = addresses.get(0).getSubLocality();
String cityName = addresses.get(0).getLocality();
String stateName = addresses.get(0).getAdminArea();
String countryName = addresses.get(0).getCountryName();
*/
}
else
locationString[0] ="Not Found!";
ready[0] = true;
}
});
while (ready[0] != true){
TimeUnit.MILLISECONDS.sleep(500);
}
clientConnection.sendtoServer("loc", locationString[0]);
}
add a comment |
I found the Answer but is still I think it can be done better
public static void sendLocation(final ClientConnection clientConnection) throws InterruptedException
{
final boolean ready = new boolean[1];
final String locationString = new String[1];
client = LocationServices.getFusedLocationProviderClient(activityContext);
if (ActivityCompat.checkSelfPermission(activityContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
clientConnection.sendtoServer("loc","Denied");
}
client.getLastLocation().addOnSuccessListener(activityContext, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationString[0] = addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea();
/*
String address = addresses.get(0).getSubLocality();
String cityName = addresses.get(0).getLocality();
String stateName = addresses.get(0).getAdminArea();
String countryName = addresses.get(0).getCountryName();
*/
}
else
locationString[0] ="Not Found!";
ready[0] = true;
}
});
while (ready[0] != true){
TimeUnit.MILLISECONDS.sleep(500);
}
clientConnection.sendtoServer("loc", locationString[0]);
}
I found the Answer but is still I think it can be done better
public static void sendLocation(final ClientConnection clientConnection) throws InterruptedException
{
final boolean ready = new boolean[1];
final String locationString = new String[1];
client = LocationServices.getFusedLocationProviderClient(activityContext);
if (ActivityCompat.checkSelfPermission(activityContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
clientConnection.sendtoServer("loc","Denied");
}
client.getLastLocation().addOnSuccessListener(activityContext, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location)
{
if(location != null){
Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationString[0] = addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea();
/*
String address = addresses.get(0).getSubLocality();
String cityName = addresses.get(0).getLocality();
String stateName = addresses.get(0).getAdminArea();
String countryName = addresses.get(0).getCountryName();
*/
}
else
locationString[0] ="Not Found!";
ready[0] = true;
}
});
while (ready[0] != true){
TimeUnit.MILLISECONDS.sleep(500);
}
clientConnection.sendtoServer("loc", locationString[0]);
}
answered Jan 3 at 0:42
Vspoke91Vspoke91
11
11
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000216%2fusing-onsuccesslistener-and-then-use-a-printstream-in-the-method-gets-me-an-erro%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown