Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Extended WebView class causing ClassCastException on Initialization

My problem is really straight forward. I can't seem to figure out why it's throwing an error of this kind (to add, I've never really used Java but have to for a simple android app now).

In my activity class I declare:

private MyWebView web;

Inside the 'onCreate' method I do this:

try {
    web = (MyWebView)findViewById(R.id.webview);
}
catch(Exception e) {
    Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
}

The class 'MyWebView' looks like this:

import android.app.AlertDialog;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;


public class MyWebView extends WebView {
    public MyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
    }
}

This throws an a 'ClassCastException' with detailMessage = "android.webkit.WebView.

I'd really appreciate some help.

Thanks

like image 366
Ke Vin Avatar asked Nov 28 '22 17:11

Ke Vin


2 Answers

the name in the layout was the one thing which was wrong. After I tried it again it errored again, but this time it triggered a 'MethodNotFoundException'. It seems like you have to implement this constrcutor

MyWebView(Context context, AttributeSet attrs)

instead of this one

MyWebView(Context context, AttributeSet attrs, int defStyle)

like eclipse suggests...

like image 170
Ke Vin Avatar answered Dec 06 '22 11:12

Ke Vin


you have to name your custom WebView like this in your layout:

<yourpackagename.MyWebView
  android:id="@+id/webview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 
 />

yourpackagename: is the name of the package in wich you decalred your MyWebView Class

like image 40
K_Anas Avatar answered Dec 06 '22 09:12

K_Anas