开发者

java.net.URL in android .. newbie question

I am a newbie in java and was trying android development . The following code generated malformedURLException.can someone help me identify the exception. Any hint would be highly helpful

package com.example.helloandroid;

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

public class HelloAndroid extends Activity {
    /** Calle开发者_开发知识库d 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);
    }
}


This is because URL constructor ( new URL("http://www.google.com/") ) throws a Checked Exception, in this case MalformedURLException, which means that you have to catch it or declare it in your method.

Use a try/catch or the throws clause in the onCreate method.

try/catch solution:

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

Throws solution:

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

Check this for more information on exceptions.

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


Well you need to execute your code in a try/catch method for first. Try it and let c what you have more?


One thing to note about OP code is that even after you add the required exception handling, the code won't run because Android doesn't allow network activities in the main thread. You need to use an AsyncTask, as described here: http://developer.android.com/resources/articles/painless-threading.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜