Android - WebView refreshing when scrolling down - java

This is probably a stupid question at this stage but I've been looking through the threads online and none of the solutions have worked for me so far.
I have an Activity that has a Webview nested inside a SwipeRefreshLayout to enable the Pull-To-Refresh functionality to refresh the page. The problem arises where when I try to scroll to the top the web page, the OnRefresh callback is being called. Below is some snippets of the relevant code I have tried related to fixing the problem. I tried to implementing the ViewTreeObserver.OnScrollChangedListener interface to enable the refresh function when the scroll is at the top. I am wondering if I am missing something.
Browser.java
public class Browser extends AppCompatActivity implements Common, ViewTreeObserver.OnScrollChangedListener {
private final String TAG = getClass().getSimpleName();
private ProgressBar loadingPageBar;
private Toolbar toolbar;
private WebView browser;
private WebSettings webSettings;
private SwipeRefreshLayout refreshLayout;
private String urlLink;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
Log.i(TAG, "onCreate: Called");
declareVariables();
getIntentData();
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setNavigationOnClickListener(view -> onBackPressed());
toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
toolbar.setSelected(true);
webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setDomStorageEnabled(true);
webSettings.setSaveFormData(true);
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
refreshLayout.setRefreshing(false);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
});
browser.setWebChromeClient(new ChromeClient());
enableHtml5Features();
browser.clearCache(true);
browser.loadUrl(urlLink);
refreshLayout.setRefreshing(true);
refreshLayout.getViewTreeObserver().addOnScrollChangedListener(this);
refreshLayout.setOnRefreshListener(() -> browser.reload());
}
#Override
public void onScrollChanged() {
System.out.println(browser.getScrollY());
if (browser.getScrollY() == 0)
refreshLayout.setEnabled(true);
else
refreshLayout.setEnabled(false);
}
}
activity_browser.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Browser">
<androidx.appcompat.widget.Toolbar
android:id="#+id/webview_toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/white"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ColoredBackArrow"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/view3"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/greyDark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/webview_toolbar" />
<ProgressBar
android:id="#+id/loadingBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="3dp"
app:layout_constraintBottom_toBottomOf="#id/webview_toolbar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.473"
app:layout_constraintStart_toStartOf="parent" />
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#id/view3">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:fitsSystemWindows="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/view3" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Any help would be appreciated. Thanks.

Add SwipeRefreshLayoutListener i.e. setOnRefreshListener like below:
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshLayout.setRefreshing(true);
loadWebView();
}
});
Whole Class with SwipeRefreshLayout Layout :
public class WebViewActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
private WebSettings webSettings;
private View view3;
private ProgressBar loadingBar;
private SwipeRefreshLayout refreshLayout;
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
view3 = findViewById(R.id.view3);
loadingBar = findViewById(R.id.loadingBar);
refreshLayout = findViewById(R.id.swipeContainer);
webview = findViewById(R.id.webview);
webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setDomStorageEnabled(true);
webSettings.setSaveFormData(true);
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
loadWebView();
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshLayout.setRefreshing(true);
loadWebView();
}
});
}
private void loadWebView(){
String urlLink="https://stackoverflow.com/questions/57478675/android-webview-refreshing-when-scrolling-down";
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
refreshLayout.setRefreshing(false);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
});
webview.setWebChromeClient(new WebChromeClient());
webview.clearCache(true);
webview.loadUrl(urlLink);
}
}
I hope its work for you.

Related

Android videoView not showing inside fragment

Hey all I am having a little bit of an issue with trying to call a fragment that has the videoview within it into my current fragment page.
When I click on the test button I set up it goes through the code without error but never shows the video fragment - I even gave it a background color of red so I could see it load into my current view.
My goal here is just to send a parameter of the video path to the video fragment videoview player and start playing it.
videoPlay.java
public class videoPlay extends Fragment {
public videoPlay(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragvideoplay, container, false);
MediaController mc= new MediaController(getActivity());
VideoView view = (VideoView)rootView.findViewById(R.id.videoView);
String path = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/sddir/Bubble Guppies.mp4";
view.setVideoURI(Uri.parse(path));
view.setMediaController(mc);
view.start();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
}
}
_fragvideoplayer.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<VideoView
android:id="#+id/videoView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
FragMovies.java:
public class FragMovies extends Fragment {
public FragMovies(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragmovies, container, false);
WebView view = (WebView) rootView.findViewById(R.id.webView);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
container.findViewById(R.id.webView).setVisibility(View.GONE);
container.findViewById(R.id.pBar1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
container.findViewById(R.id.pBar1).setVisibility(View.GONE);
container.findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
});
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setAllowContentAccess(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setLoadsImagesAutomatically(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setBuiltInZoomControls(false);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setDisplayZoomControls(false);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.getSettings().setSupportZoom(false);
view.setHorizontalScrollBarEnabled(false);
view.setVerticalScrollBarEnabled(false);
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("https://www.bing.com/");
return rootView ;
}
}
_fragmovies.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainLayout">
<ProgressBar
android:id="#+id/pBar1"
android:layout_width="93dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="true"
android:layout_marginStart="950px"
android:layout_marginLeft="950px" />
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</LinearLayout>
Main_activity.java:
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
PagerAdapter pagerAdapter;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getViews();
//adapter setup
pagerAdapter = new com.example.telluridetainment.PagerAdapter(getSupportFragmentManager());
//attaching fragments to adapter
pagerAdapter.addFragment(new FragMovies(),"Movies");
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
//setting icons
tabLayout.getTabAt(0).setIcon(R.drawable.ic_movie_white_24dp);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new MyClass());
}
public class MyClass implements View.OnClickListener {
#Override
public void onClick(View v) {
videoPlay myfragment = new videoPlay();
//pass data
Bundle bundle = new Bundle();
bundle.putString("KEY","DATA");
myfragment.setArguments(bundle);
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentManager.addToBackStack(null);
fragmentManager.replace(R.id.viewPager, myfragment).commit();
}
}
private void getViews() {
tabLayout = findViewById(R.id.mTabLayout);
viewPager = findViewById(R.id.viewPager);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="2000px"
android:layout_height="1200px"
tools:context=".MainActivity">
<Button
android:id="#+id/button0"
android:layout_width="200dp"
android:layout_height="152dp"
android:text="Button"
android:textColor="#B71C1C" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/appbarLayout"
tools:ignore="SpeakableTextPresentCheck">
</android.support.v4.view.ViewPager>
</RelativeLayout>
The path to the movie is correct. And the movie is there in the "external" SD card path. Clicking around on the new fragment (videoPlay) yields no video menu (play, remind, pause...) so its not there.
Any help would be great!

Show toast error and prevent display of webview when no connection is available

When there is no connection available it displays the deafult browser error page, What is want is simply not to display any browser error page instead a toast message and a blank screen.
My code:
public class EarnFragment extends Fragment {
WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_earn, container, false);
mWebView = (WebView) v.findViewById(R.id.webview);
mWebView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
return v;
}
}
if you want to display black screen instead of webview, first you need to change your layout file.
then you check internet connection before load the url.
check if internet connection not available taht time hide your webview and display your Toast message and relative layout.
Othervise hide Relativelayout noConnection.
Step 1 : create layout like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webViewData"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<RelativeLayout
android:id="#+id/noConnection"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent"/>
</RelativeLayout>
</LinearLayout>
Step 2 : Check your internet connection using this function.
public static boolean checkInternetConnection(Context context) {
if (context != null) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isConnectedOrConnecting();
} else {
return false;
}
} else {
return false;
}
}
At the end do this in your code, before load you url,
public class EarnFragment extends Fragment {
WebView mWebView;
RelativeLayout noConnection;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_earn, container, false);
mWebView = (WebView) v.findViewById(R.id.webview);
noConnection = (RelativeLayout)v.findViewById(R.id.noConnection);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
if(checkInternetConnection(getActivity())){
noConnection.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
mWebView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");
}else{
noConnection.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.GONE);
}
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
return v;
}
Step 1: Make include_error_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ebebeb"
android:gravity="center"
android:orientation="vertical">
<!--android:background="#ebebeb"-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/labelError"
android:layout_centerHorizontal="true"
android:src="#drawable/img_icon_error_list" />
<TextView
android:id="#+id/labelError"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:padding="10dp"
android:text="#string/err_error_list"
android:textColor="#color/color_app_font_primary" />
<ProgressBar
android:id="#+id/errorProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/labelError"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:visibility="gone"/>
</RelativeLayout>
</LinearLayout>
Step 2: Make fragment layout fragment_abc.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:id="#+id/errorView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<include layout="#layout/include_error_list_view" />
</RelativeLayout>
</RelativeLayout>
Step 3: Bind Layout with JAVA.
public class AbcFragment extends Fragment {
private final String TAG = "AbcFragment";
private WebView webView;
private ProgressDialog progress;
private RelativeLayout errorView;
private boolean isShowErrorWiew = false;
private ProgressDialog progress;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_abc, container, false);
webView = (WebView) view.findViewById(R.id.webview);
errorView = (RelativeLayout) view.findViewById(R.id.errorView);
TextView labelError = (TextView) view.findViewById(R.id.labelError);
labelError.setText("Application unable to connect with internet.");
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
showProgressBarWithoutHide();
errorView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isShowErrorWiew = false;
showProgressBarWithoutHide();
webView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");
}
});
try {
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " + url);
if (!isShowErrorWiew) {
errorView.setVisibility(View.GONE);
}
hideProgressBar();
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
isShowErrorWiew = true;
errorView.setVisibility(View.VISIBLE);
// Snackbar.make(webView, getString(R.string.err_process_webView), Snackbar.LENGTH_LONG).show();
}
});
webView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");
} catch (Throwable th) {
th.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
webView.onResume();
}
#Override
public void onPause() {
super.onPause();
/*Todo Always Pause WebView Because Background video play is violating google policy*/
webView.onPause();
}
public void hideProgressBar() {
if (progress != null) {
progress.dismiss();
}
}
public void showProgressBarWithoutHide() {
if (progress == null) {
progress = new ProgressDialog(getActivity());
progress.setMessage(getString(R.string.please_wait));
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
} else if (!progress.isShowing()) {
progress.show();
}
}
}

WebView scroll up automatically when scrolling it down little

In web view when I scroll the page little bit down then it scroll up automatically on some pages not all pages but on some pages.Why this happen and what is it solution
Here is xml code
<android.support.design.widget.CoordinatorLayout android:id="#+id/nonVideoLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<WebView
android:id="#+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.design.widget.CoordinatorLayout>
Here is my code you can check this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
bindLayout();
mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
CookieManager.getInstance().setCookie(url, cookie);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
ProgressDialogHelper.showProgress(WebViewActivity.this);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
mySwipeRefreshLayout.setRefreshing(false);
}
});
webView.loadUrl(url);
}
Here is my java code I set the cookie also to web view and I set also layer type. I search that everyone says to set layer type then this problem solved but it does not solved.
try this
final WebSettings settings = mWebView.getSettings();
settings.setDomStorageEnabled(true);
settings.setJavaScriptEnabled(true);
mWebView.setVerticalScrollBarEnabled(false);
Just remove
webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
all others are OK
try this in AndroidManifest.xml
set android:hardwareAccelerated="true" in the application and activity tag.

How to add Toolbar to PreferenceActivity

I am creating an app which have a setting PreferenceActivity with actionbar and that's working fine. I want to use another custom PreferenceActivity with actionbar which is using a layout (activity_about.xml) and preference layout (about_preferences.xml). But when i run the app it's causing my app to crash on calling that activity. Probably the actionbar is returning the Null, i can't figure it out where is the problem. Please help.
My ActivityAbout.java
public class ActivityAbout extends PreferenceActivity {
private AppCompatDelegate mDelegate;
private ActionBar actionBar;
private SharedPref sharedPref;
private View parent_view;
private TextView ver;
Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.about_preferences);
setContentView(R.layout.activity_about);
View lv = findViewById(android.R.id.list);
if (lv != null) lv.setPadding(0, 0, 0, 0);
final Preference prefPrivacy = (Preference) findPreference(getString(R.string.pref_title_privacy));
final Preference prefTerm = (Preference) findPreference(getString(R.string.pref_title_term));
final Preference prefBuild = (Preference) findPreference(getString(R.string.pref_title_build));
final Preference prefCopyright = (Preference) findPreference(getString(R.string.pref_title_copyright));
String versionName = BuildConfig.VERSION_NAME;
ver = (TextView) findViewById(R.id.version);
ver.setText("Version "+versionName);
prefBuild.setSummary("Version "+versionName);
int y = Calendar.getInstance().get(Calendar.YEAR);
prefCopyright.setSummary("Copyright © "+y+" Get Rid Remedy.\nAll Right Reserved.");
prefPrivacy.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
dialogPrivacy(ActivityAbout.this);
return false;
}
});
prefTerm.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
dialogTerm(ActivityAbout.this);
return false;
}
});
initToolbar();
}
public void dialogPrivacy(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(activity.getString(R.string.pref_title_privacy));
builder.setMessage(activity.getString(R.string.content_privacy));
builder.setPositiveButton("OK", null);
builder.show();
}
public void dialogTerm(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(activity.getString(R.string.pref_title_term));
builder.setMessage(activity.getString(R.string.content_term));
builder.setPositiveButton("OK", null);
builder.show();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
private void initToolbar() {
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(R.string.activity_title_settings);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
Here is the about_preferences layout.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="#string/pref_title_dev_email"
android:summary="#string/developer_email"
android:title="#string/pref_title_dev_email"/>
<Preference
android:key="#string/pref_title_copyright"
android:summary="#string/copyright"
android:title="#string/pref_title_copyright"/>
<Preference
android:key="#string/pref_title_build"
android:summary="#string/app_version"
android:title="#string/pref_title_build"/>
<Preference
android:key="#string/pref_title_privacy"
android:title="#string/pref_title_privacy"
android:widgetLayout="#layout/ic_about"/>
<Preference
android:key="#string/pref_title_term"
android:title="#string/pref_title_term"
android:widgetLayout="#layout/ic_about"/>
Here is activity_about.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_about"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.overridecode.getridremedy.ActivityAbout">
<android.support.design.widget.AppBarLayout
android:id="#+id/tool"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/toolbar" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_below="#+id/tool"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_vertical_margin">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
app:srcCompat="#mipmap/ic_launcher"
android:id="#+id/imageView" />
<TextView
android:text="#string/app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:textSize="30dp"
android:textStyle="bold"
android:textColor="#73000000"
android:id="#+id/app_title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="#+id/version" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentBottom="true">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
The error i am getting:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.overridecode.getridremedy/
com.overridecode.getridremedy.ActivityAbout}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
Add an ID to your Toolbar:
<include
android:id="#+id/toolbar_prefs"
layout="#layout/toolbar" />
And call setSupportActionBar() (passing your Toolbar instance) before calling getSupportActionBar():
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_prefs);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(R.string.activity_title_settings);
}
Otherwise getSupportActionBar() will return null.
As per my experience, I found there is no ActionBar in preference activity. So,
There are following steps to add toolbar in your activity
Add in xml
<include layout="#layout/toolbar" />
Set Toolbar in java class using following code.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarId);
setSupportActionBar(toolbar);
NOTE: here you need to use this code in starting of intitToolbar() method.
Import proper class/package for your toolbar. From your comments seems you need to import
import android.support.v7.widget.Toolbar;
Hope this may help you. If helps, please approve it as right answer.

WebView not working in Android when used with OnClickListener

I am working on a simple Android App which uses WebView.
The code is:
activity_main.xml
<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"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linear1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editUrl"
android:layout_weight="3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/url_hint"/>
<Button
android:id="#+id/buttonGo"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/url_go"/>
</LinearLayout>
<WebView
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear1"
tools:context=".MainActivity" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
WebView mWebView;
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.buttonGo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText = (EditText)findViewById(R.id.editUrl);
String url = editText.getText().toString();
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl(url);
}
});
}
}
However, this code doesn't seem to work. I don't know why. It was working perfectly when I did not add any EditText or Button, and the code in the MainActivity.java was:
public class MainActivity extends ActionBarActivity {
WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://google.com";
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl(url);
}
});
}
}
I have no idea why this is happening because the app seemed to work fine before.
When I changed the layout, the app doesn't work.
Please help me in detail as I am new to Android.
Thanks.
PLEASE FEEL FREE TO SUGGEST ME A BETTER METHOD TO IMPLEMENT THIS ALSO
Create java object of all other view objects like web view before it and then try.
I just tried your code as is, and it worked. One thing to note though, you have to type in the full url, for example: http://www.example.com.
One improvement would be to make it so you just have to type in example.com by doing something like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText = (EditText)findViewById(R.id.editUrl);
String url = editText.getText().toString();
if (!url.contains("www")){
url = "www." + url;
}
if (!url.contains("http")){
url = "http://" + url;
}
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl(url);
}
});

Categories

Resources