2

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 {
    /** 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);
    }
}
Anuj
  • 9,222
  • 8
  • 33
  • 30
  • I think it should be `URL url_g = new URL("://www.google.com/");` – MByD Jul 13 '11 at 17:37
  • do you have tried with another url?? I can not see any bug – JAiro Jul 13 '11 at 17:39
  • Your code runs successfully on my machine over here, looks fine to me as well (though you should use a `StringBuilder` instead of `+= String`). Always include the stack trace when you ask for help with an exception, that may help here. – LeffelMania Jul 13 '11 at 17:42

3 Answers3

7

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/

Alfredo Osorio
  • 11,297
  • 12
  • 56
  • 84
1

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

Rovin
  • 84
  • 10
1

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

Tiberiu Ichim
  • 641
  • 7
  • 7