I have some confusion regarding where you put regular java code in an android application.
I'm using the Eclipse SDK and by default when you create an application it makes a .java file with an OnCreate() method. Is this where I would put my code, inside this method?
Right now in my layout I have an imageButton, once this button is clicked I want to open a new WebView page that gets it's HTML code from the index.html file found in the assets folder. This is what I have so far...
Button button = (Button)findViewById(R.id.imagebutton1);
if(button.isPressed())
{
开发者_开发技巧 WebView webview = new WebView(null);
setContentView(webview);
try {
InputStream fin = getAssets().open("index.html");
byte[] buffer = new byte[fin.available()];
fin.read(buffer);
fin.close();
webview.loadData(new String(buffer), "text/html", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
I have this block of code at the end of the onCreate() method right under the line:
setContentView(R.layout.main);
However, once I run the program it crashes and tells me that it failed to start. I'm assuming that it has to do with the fact that the code is in the onCreate. I know that its not where I'm supposed to put it, but I can't think of anywhere else the code should go. Am I supposed to make a new .java file and have a main method there? I'm currently taking classes for C++ and C# so this android thing is still new to me.
Have you done the tutorials? If not I would start there to learn about the basics of creating and working with an Android Activity
. Once you have worked your way through them, read the application fundamentals to understand the lifecycle more fully.
You shouldn't be calling setContentView more than once in onCreate. The WebView should be in your main.xml layout file or else launch a new Activity that's layout contains the WebView. And also to hand the onClick on the button you need to call setOnClickListener().
Please see Handling UI Events.
Also, if your program crashes, it would be helpful if you provided error messages from logcat.
精彩评论