0

im trying to build an app just for training. im using JSON object in a class. (i know the class code is okay because my teacher wrote it). i tried to print things to the textview in the oncreate methond but failed. so i tried to call the print method from the onClick method. but it keep crashing and i have no idea why.

 Button boilerBtn;

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

    boilerBtn = findViewById(R.id.openBoilerBtn);
    boilerBtn.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View view) {
            MyBoiler myData = null;
            try {
                myData = new MyBoiler("0e3a4cef498bc2ad18a97e1817c79e87", "50.4019514,30.6727719", "Ramat-Gan");
                boolean tof = myData.openBoiler(30, 20);
                printToTV(tof);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    });
}


public void printToTV(boolean turnOnOrNot){
    int cloud = 0;
    int temp = 0;
    LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info);
    TextView tvToF = new TextView(this);
    TextView tvCloud = new TextView(this);
    TextView tvTemp = new TextView(this);

    tvToF.setText(turnOnOrNot ? "Turn On" : "Dont Turn On");
    String cloudString = String.valueOf(cloud);
    tvCloud.setText(cloud + "% cloud coverage");
    String tempString = String.valueOf(temp);
    tvTemp.setText(temp + " Celsius Degrees");
    linearLayout.addView(tvToF);
    linearLayout.addView(tvCloud);
    linearLayout.addView(tvTemp);
}

the logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myturnonboilerapp, PID: 22068
    android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
        at java.net.InetAddress.getAllByName(InetAddress.java:1154)
        at com.android.okhttp.Dns$1.lookup(Dns.java:39)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26)
        at java.net.URL.openStream(URL.java:1072)
        at com.example.myturnonboilerapp.MyBoiler.readJsonFromUrl(MyBoiler.java:32)
        at com.example.myturnonboilerapp.MyBoiler.openBoiler(MyBoiler.java:72)
        at com.example.myturnonboilerapp.SecondActivity$1.onClick(SecondActivity.java:32)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 22068 SIG: 9
Process 22068 terminated.

MyBoiler class:

    package com.example.myturnonboilerapp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

    public class MyBoiler {
        public final String API_URL = "https://api.darksky.net/forecast/"; // url of the site
        private String apiKey; // api key from the site
        private String GPSlocation; // gps location -_-
        private String rawData; // the raw data
        private String fullURL; // the full url location
        private String cityName; // name of the city
        JSONObject jsonObject;

        public MyBoiler(String apiKey, String GPSlocation, String cityName) throws IOException, JSONException {
            this.apiKey = apiKey;
            this.GPSlocation = GPSlocation;
            this.cityName = cityName;
            // create the full url
            fullURL = API_URL + this.apiKey + "/" + this.GPSlocation;
        }

        private JSONObject readJsonFromUrl()throws IOException, JSONException{
            //open a connection to the internet
            InputStream is = new URL(this.fullURL).openStream();
            // create a buffer for collection of all data
            BufferedReader buf = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            // read all data and append it to one happy string
            String jsonText = readAll(buf);
            //convert to json object so we can use the json power
            jsonObject = new JSONObject(jsonText);
            // returns the json object
            return jsonObject;
        }

        private String readAll(BufferedReader rd) throws IOException {
            // create a string builder
            StringBuilder sb = new StringBuilder();
            // create a char point
            int cp;
            while((cp = rd.read()) != -1){
                sb.append(cp);
            }
            // sets the rawData value to the string
            rawData = sb.toString();
            // return the result
            return sb.toString();
        }

        public String getRaw(){
            return rawData;
        }

        private int getCloud(JSONObject cur) throws  IOException, JSONException{
            int cloud = (int)(cur.getDouble("cloudCover")*100);
            return cloud;
        }

        private int getTemp(JSONObject cur) throws IOException, JSONException{
           int temp = (int)(cur.getDouble("temperature"));
           return (int)((temp-32)/1.8);
        }

        public boolean openBoiler(int tolerance, int minTemp)throws IOException, JSONException{
            JSONObject myData = readJsonFromUrl();
            JSONObject currently = myData.getJSONObject("currently");

            return getCloud(currently) > tolerance && getTemp(currently) < minTemp;
        }


}
flutternewb
  • 17
  • 1
  • 5
  • 1
    Where is your logcat ? – M D Oct 10 '19 at 12:59
  • 1
    Post your error logcat. – Sebastian Pakieła Oct 10 '19 at 13:00
  • 1
    post logcat and full code of activity – PJain Oct 10 '19 at 13:05
  • 1
    without any errormessage it is hard to know what is crashing, might be that R.id.info is not actually a LinearLayout or does not exist. on a side note, you do not actually have to explicitly convert integer to string via String.valueOf, 0+"" will automatically convert the integer to a string. – Joachim Haglund Oct 10 '19 at 13:06
  • the main activity is just a working button to get me to second activity. i will edit the logcat now plus the MyBoiler class – flutternewb Oct 10 '19 at 13:07
  • you are using hte layout called second setContentView(R.layout.activity_second); so perhaps you are using the wrong xml for layout? that would explain the application crashing when you try to use elements that doesnt exist in it – Joachim Haglund Oct 10 '19 at 13:09
  • Never do networking on MainThread. Use `AsyncTask` for example to handle network requests. Then you won't have that error – jle Oct 10 '19 at 13:13

2 Answers2

1

You are doing Network Operation in your Main Thread, which not permitted in Android

Logcat showing that:

android.os.NetworkOnMainThreadException
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
0

the actual error does not have anything to do with the first code you posted, this is why its importand to post the actual error and preferably the logcat. The reason for the crash is that the network call is being run on the mainthread which will lock up the ui.

you need to run the network command in an AsyncTask preferably.

Joachim Haglund
  • 775
  • 5
  • 15