Reputation: 1959
I have a webview that is owned by an Activity class. I access the webview via findViewId(). That works well. Now i'd like to have the webview persist globally. So I've extended the Application class. How can i access the webView from there though. Because the Application class doesnt allow findViewId() method. The WebView is defined in the activity_layout.xml so I suppose this is true of any View, not just webview, which is defined this way.
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top" />
The reason for this is that i need the webview to persist even when the activity is destroyed such that the webview doesnt refresh after OnDestroy of the Activity.
Thank you.
Upvotes: 0
Views: 103
Reputation: 83557
The reason for this is that i need the webview to persist even when the activity is destroyed
This is a bad idea. Even if you are able to keep a reference to the WebView after the parent Activity is destroyed, it will be invalid because the WebView object that it references will be destroyed along with the Activity. This is a good example of why global data is frowned upon in Object Oriented languages like Java.
One possible solution is to cache the web page and all its resources (images etc) to the local file system. Then when your Activity restarts, you can check if there is a cache and load it directly from disk if it exists. This will give you a significant increase in response time.
Upvotes: 2
Reputation: 2221
Why don't you use inheritance?
You can create a base activity with the WebView
as a property.
class BaseActivity Extends Activity{
protected WebView webview;
// and so on and so forth
}
Upvotes: 0