Liglo App
Liglo App

Reputation: 3819

Android App with WebView not working

Trying to use WebView, I have the following code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.places.xt.MainActivity$PlaceholderFragment" >

    <WebView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

and

(...)
import android.webkit.WebView;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        WebView webview = (WebView) findViewById(R.id.webview);
        setContentView(webview);

        String summary = "<html><body style=\"background-color: yellow\">You scored <b>192</b> points.</body></html>";
        webview.loadData(summary, "text/html", null);

    }
(...)

When I click on "Run" to force building APK file and then download and start it on my phone, it says "App has been stopped". The app has the size of only about 760 kB. I think it's not very much, I guess the WebView package is not correctly imported. What can be the reason?

Tested on 4.4 Kitkat, Eclipse, Win 7 32 bit

Upvotes: 0

Views: 190

Answers (1)

laalto
laalto

Reputation: 152927

First, your webview is in the fragment layout and not in the activity layout. Move the code that accesses the webview to the fragment's onCreateView(). See NullPointerException accessing views in onCreate().

Second, remove the setContentView(webview). It serves no practical purpose to find a view from the current content view and set it as the content view.

Upvotes: 1

Related Questions