onClick方法有什么问题

时间:2019-10-10 12:57:15

标签: java android json

im试图构建仅用于培训的应用程序。 我在类中使用JSON对象。 (我知道班级代码还可以,因为我的老师写了它)。 我试图在oncreate方法中将内容打印到textview中,但是失败了。所以我试图打电话给 onClick方法中的print方法。但是它一直崩溃,我也不知道为什么。

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

日志猫:

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类:

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


}

2 个答案:

答案 0 :(得分:1)

您正在主线程中进行网络操作,这在Android中是不允许的

Logcat显示以下内容:

android.os.NetworkOnMainThreadException

答案 1 :(得分:0)

实际错误与您发布的第一个代码无关,这就是为什么导入并发布实际错误(最好是logcat)的原因。崩溃的原因是网络调用正在主线程上运行,这将锁定ui。

您最好需要在AsyncTask中运行network命令。