I'm making an app that, after reading a Qr code, has to send the UUID, Manufacturer, Serial and Model of the phone to a WebService, to get that data I use this method:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Obtain information from the qr scanned
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
// Obtain data
String dataLink = result.getContents(); // Convert the information from the qr into a string
uniqueID = UUID.randomUUID().toString(); // Generate an UUID
phoneModel = Build.MODEL; // Returns the model of the phone
phoneManufacturer = Build.MANUFACTURER; // Returns the manufacturer
// Adding the values obtained to their respective TextViews to display them in the app.
txtLink.append(" "+dataLink);
txtUuid.append(" "+uniqueID);
txtSerial.append(" "+ serialNumber);
txtManufacturer.append(" "+phoneManufacturer);
txtModel.append(" "+phoneModel);
// Send the obtained data to the webservice
sd.sendData(uniqueID, serialNumber, phoneManufacturer, phoneModel);
}
It works fine until the moment where I have to use the sendData() method, that's where it crashes. I implemented that method in the following class:
public class SyncData {
public void sendData(String uuid, String serial, String manufacturer, String model) {
try {
URL url = new URL("https://demo.cbus.com.mx/api/v4/qr-vin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
JSONObject json = new JSONObject();
json.put("uuid", uuid);
json.put("manufacturer", manufacturer);
json.put("serial", serial);
json.put("model", model);
String jsonInputString = "{\"uuid\": \"" + uuid + "\", \"manufacturer\": \"" + manufacturer + "\", \"serial\": \"" + serial + "\", \"model\": \"" + model + "\"}";
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
//byte[] input = json.getBytes("utf-8");
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
}
When I run the application I get the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.fiverr.qrscanner, PID: 20265
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=49374, result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has extras) }} to activity {app.fiverr.qrscanner/app.fiverr.qrscanner.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:4940)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4981)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2046)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7564)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1571)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:262)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:219)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:30)
at app.fiverr.qrscanner.SyncData.sendData(SyncData.java:30)
at app.fiverr.qrscanner.MainActivity.onActivityResult(MainActivity.java:71)
at android.app.Activity.dispatchActivityResult(Activity.java:8274)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4933)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4981)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2046)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7564)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
D/OOMEventManagerFK: checkEventAndDumpForJE: 0 I/Process: Sending signal. PID: 20265 SIG: 9
I have been trying different methods to send the data to the WebService but I have not found a solution, I tried the options on this page but they did not work either. The error says that it is in line 30 of my SyncData class, which corresponds to the beginning of this try/catch:
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
//byte[] input = json.getBytes("utf-8");
os.write(input, 0, input.length);
}
Although I consider that it could probably be in this part:
String jsonInputString = "{\"uuid\": \"" + uuid + "\", \"manufacturer\": \"" + manufacturer + "\", \"serial\": \"" + serial + "\", \"model\": \"" + model + "\"}";
In any case, I would appreciate any help you can give me.