有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA网安卓中的URL。。新手问题

我是一名java新手,正在尝试安卓开发。下面的代码生成了malformedURLException。有人能帮我确定例外情况吗。 任何暗示都会非常有用

package com.example.hello安卓;

import 安卓.app.Activity;
//import 安卓.widget.TextView;
import 安卓.os.Bundle;
import java.net.*;
import java.io.*;
import 安卓.widget.TextView;

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        String outdata = "";
        URL url_g = new URL("http://www.google.com/");
        URLConnection ukr = url_g.openConnection();

        BufferedReader in = new BufferedReader(new InputStreamReader(ukr.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            outdata += inputLine;
        in.close();
       tv.setText(outdata);
       setContentView(tv);
    }
}

共 (3) 个答案

  1. # 2 楼答案

    这是因为URL构造函数(新URL(“http://www.google.com/“”)引发选中的异常,在本例中为MalformedURLException,这意味着您必须捕获它或在方法中声明它

    在onCreate方法中使用try/catch或throws子句

    尝试/捕获解决方案:

    public void onCreate(Bundle savedInstanceState) {
        ...
        try {
            URL url_g = new URL("http://www.google.com/");
        } catch(MalformedURLException e) {
            //Do something with the exception.
        }
        ...
    }
    

    抛出解决方案:

    @Override
    public void onCreate(Bundle savedInstanceState) throws MalformedURLException {
        ...
        URL url_g = new URL("http://www.google.com/");
        ...
    }
    

    有关异常的更多信息,请选中此项

    http://download.oracle.com/javase/tutorial/essential/exceptions/

  2. # 3 楼答案

    首先,您需要在try/catch方法中执行代码。试试看,让c知道你还有什么