This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.
Below is my activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:id="#+id/webView"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
And this is my MainActivity.java file
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
#Override
public boolean onCreateOptionsMenu (Menu manu){
getMenuInflater().inflate(R.menu.main, manu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
int id=item.getItemId();
if(id==R.id.id_about){
Intent intentabout=new Intent(MainActivity.this, About.class);
startActivity(intentabout);
return true;
}
if(id==R.id.id_terms){
return true;
}
if(id==R.id.id_privacy){
return true;
}
return true;
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webView.loadUrl("https://google.com");
swipe.setRefreshing(true);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error.html");
}
public void onPagefinished(WebView view, String url){
swipe.setRefreshing(false);
}
});
}
}
You gotta put your WebView inside SwipeRefreshLayout:
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipeRefreshLayout;
String currentUrl = "https://www.google.co.in/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
webView.loadUrl(currentUrl);
webView.setWebViewClient(new MyWebViewClient());
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.loadUrl(currentUrl);
}
});
}
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
}
swipeRefreshLayout.setRefreshing(false) stops the animation.
you can put your Webview inside a NestedScrollView to make this work.
Example:
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.widget.NestedScrollView
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" />
</android.support.v4.widget.NestedScrollView>
You should add
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
swipe.setRefreshing(true); //add
LoadWeb();
}
LoadWeb();
Related
I have done everything, I can see the navigation drawer but my app is crashing. Can anyone explain whats the problem in the below code. Now whenever I try to open ForumActivty it is crashing.
public class ForumActivity extends AppCompatActivity implements AdvancedWebView.Listener{
public AdvancedWebView webView;
private ProgressBar mPbar = null;
private static final String url = "https://discuss.flarum.org/";
String webURL, webTitle ;
private DrawerLayout mDrawerLayout;
private Fragment fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CustomApplication)getApplication()).checkUserLogin();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_forum);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
Bundle bundle = getIntent().getExtras();
if(bundle != null){
fragment = new ProfileFragment();
}else{
fragment = new TopicFragment();
}
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_content, fragment).commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_topic) {
fragment = new TopicFragment();
}
else if(id == R.id.nav_profile){
fragment = new ProfileFragment();
}
else if(id == R.id.nav_scores){
fragment = new ScoreFragment();
}
else if(id == R.id.nav_share){
fragment = new ScoreFragment();
}
else if(id == R.id.nav_contact){
startActivity(new Intent(ForumActivity.this, ContactActivity.class));
}
else if(id == R.id.nav_settings){
fragment = new SettingsFragment();
}
else if(id == R.id.nav_logout){
((CustomApplication)getApplication()).getShared().setUserData("");
Intent logoutIntent = new Intent(ForumActivity.this, LoginActivity.class);
logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(logoutIntent);
finish();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_content, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
mPbar = (ProgressBar) findViewById(R.id.loader);
webView = (AdvancedWebView) findViewById(R.id.newWeb);
webView.loadUrl(url);
webView.setListener(this, this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAllowFileAccess(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
AdvancedWebView newWebView = new AdvancedWebView(ForumActivity.this);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setAllowUniversalAccessFromFileURLs(true);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
});
webView.setOnKeyListener( new View.OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
webView.setThirdPartyCookiesEnabled(true);
webView.setCookiesEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
webView.onResume();
}
#Override
protected void onPause() {
webView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
webView.onDestroy();
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
webView.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onBackPressed() {
if (!webView.onBackPressed()) { return; }
super.onBackPressed();
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
}
#Override
public void onPageFinished(String url) {
webURL = webView.getUrl();
webTitle = webView.getTitle();
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
}
#Override
public void onExternalPageRequest(String url) {
}
}
I know I am doing something wrong above but I have included everything in layout. It would be really nice if someone can help
You should have also shared the code of layout&activity which already has a Navigation Drawer. Anyway, you can follow this guide.
For you layout file, you will need to put your CoordinatorLayout inside DrawerLayout like this and add a NavigationView (check the xml layout of other Activity which already has a navigation drawer and copy <android.support.design.widget.NavigationView> and replace with the one in below example):
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<im.delight.android.webview.AdvancedWebView
android:id="#+id/newWeb"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
></im.delight.android.webview.AdvancedWebView>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loader"
android:layout_weight="1"
android:layout_gravity="center_vertical|center_horizontal|center"/>
</android.support.design.widget.CoordinatorLayout>
<!-- Replace this with the one in other activity layout -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
After that there will be some code that you will need to add in your Activity class. You can check the link I put above and after reading it you can understand which code you need to copy from other Activity which already has a navigation drawer.
I need to display splash screen until web page is loaded in webview.
I use following code. Is it possible to do?
public class SplashScreen extends Activity {
protected Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
intent = new Intent(getApplicationContext(), MainActivity.class);
// MainActivity.class contains WebView
Thread myThread = new Thread() {
#Override
public void run() {
try {
sleep(5000);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
And
public class MainActivity extends Activity {
private WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
String url = "http://google.com";
view = (WebView)this.findViewById(R.id.webView1);
view.clearCache(true);
WebSettings s = view.getSettings();
s.setJavaScriptEnabled(true);
s.setCacheMode(WebSettings.LOAD_DEFAULT);
s.setDomStorageEnabled(true);
view.loadUrl(url);
}
Don't make a separate activity for splash screen, in MainActivity.java itself create a splash screen layout and webview layout and set visibility of webview to GONE.
On open of MainActivity initialize webView and set custom WebViewClient. Override onPageFinished() in your custom webViewClient and in this method make webview visible and splash screen layout to Gone.
Same here : Loading a WebView URL before splashscreen finishes
My solution is here
private WebView view;
private ImageView splashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
splashScreen = (ImageView) this.findViewById(R.id.spscreen);
String url = "http://google.com";
view = (WebView)this.findViewById(R.id.webView1);
view.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
splashScreen.setVisibility(View.INVISIBLE);
view.setVisibility(View.VISIBLE);
}
});
WebSettings s = view.getSettings();
s.setJavaScriptEnabled(true);
s.setCacheMode(WebSettings.LOAD_DEFAULT);
s.setDomStorageEnabled(true);
view.loadUrl(url);
}
And layout
<ImageView
android:id="#+id/spscreen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/splashscreen"
android:visibility="visible"
android:scaleType="fitXY"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView1"
android:visibility="invisible" />
I am new to android development and I am confused about how to add admob banner to a fragment activity(I think its calling fragment). I am modifying a source code.
I have a layout file called fragment_ftp.xml and its as below
<?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"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=""
android:id="#+id/statusText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="99dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/ftpAddressText"
android:layout_below="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_ftp"
android:id="#+id/startStopButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/primary_red"
android:text=""
android:id="#+id/warningText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ftp_image"
android:layout_above="#+id/warningText"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer" />
</RelativeLayout>
</RelativeLayout>
I had added the admob banner and in the preview, I can see that. Please check the below screenshot.
But the issues is that, Where should I write the java code for this admob banner. I don't have a corresponding activity for this fragment_ftp.xml.
Searching for fragment_ftp, I could see only a java file as follows.
FTPServerFragment.java
package com.filename.fragments;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I this the java page where I shall write the admob call?
try and use this code solve the issue
http://www.androidhive.info/2016/02/android-how-to-integrate-google-admob-in-your-app/
your code java has to be added inside onCreateView function in FTPServerFragement like this :
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
//your ads
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = rootView.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
Inside my SettingsActivity extends AppCompatActivity I have SettingsFragment extends PreferenceFragment. When I try press home-buttion in toolbar it is not working. Here is my code
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/settingsToolbar"
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="?android:actionBarSize"
android:background="#color/colorPrimary" />
SettingsActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupToolBar();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
private void setupToolBar() {
getLayoutInflater().inflate(R.layout.toolbar, (ViewGroup) findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar) findViewById(R.id.settingsToolbar);
setSupportActionBar(toolbar);
setTitle(getResources().getString(R.string.settings));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setFocusable(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
I tried to solve it in such way: remove setNavigationOnClickListener and add this:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return (super.onOptionsItemSelected(menuItem));
}
It does not help. How can I fix this?
add this line to config your getSupportActionBar:
getSupportActionBar().setHomeButtonEnabled(true);
use both code in your activity like below:
in your setupToolbar method:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Log.d("cek", "home selected");
finish();
}
});
and in your onOptionsItemSelected method:
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
This is my splashscreen activity.
public class Splash extends Activity {
private static int SPLASH_TIME_OUT=10000;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Timer r=new Timer();
new Handler().postDelayed(r,SPLASH_TIME_OUT);
}
class Timer implements Runnable{
#Override
public void run() {
// TODO Auto-generated method stub
Intent i=new Intent(Splash.this,MainActivity.class);
startActivity(i);
finish();
}
}
}
This is my MainActivity. This activity Should be performed in background while splashscreen is on the front. Is it advisable to use AsyncTask. How to do that?
If not AsyncActivity, What can I use?
public class MainActivity extends Activity {
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.output);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAppCacheEnabled(false);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
}
);
webview.loadUrl("http://www.example.com");
}
//this is to go back to previous pages if exists
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack()){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
If possible can I set the time for the splashscreen to view as long as the url is loaded without giving time?
The second attempt
public class MainActivity extends Activity {
WebView webview;
private boolean isSplashOn = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
webview = (WebView)findViewById(R.id.output);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAppCacheEnabled(false);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
public void onPageFinished(WebView view, String url) {
if(isSplashOn) {
webview.setBackgroundDrawable(null);
webview.setBackgroundColor(0);
isSplashOn = false;
}
super.onPageFinished(view, url);
}
}
);
webview.loadUrl("http://www.example.com");
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack()){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
Guys. Still the problem is't solved. Need some help
You can use the simple trick -
I was showing a loading spinner till the page was being loaded in background.
Thus I had used two web views.
In your case, you can use ImageView or any other view.
XML file will like this -
<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"
tools:context="${relativePackage}.${activityClass}" >
//Actual webview
<WebView
android:id="#+id/actual_webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
//Any view you want to show while webpage is loading
<WebView
android:id="#+id/spinner_webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
...
</RelativeLayout>
Now, in your JAVA file-
//initially, make actual_webview invisible
actual_webview.setVisibility(View.INVISIBLE);
Also, in
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// make spinner_webview invisible
spinner_webview.setVisibility(View.INVISIBLE);
// make actual_webview visible
actual_webview.setVisibility(View.VISIBLE);
}
Also,
shouldOverrideUrlLoading(...)
onPageStarted(...)
onPageFinished(...)
In all these methods, you get the URL and can check which URL is being loaded or finished loading.
According to the URL you can decide whether to show / hide the splash screen.
You can do it without AsyncTask and you can hide the splash screen when the page loaded without a timer.
WebViewClient class has a method onPageFinished() which will be called once the page has been loaded. You can make use of it.
In you project folder, place your splash screen images with name 'splash_screen.png' (or whatever name you want. If you want to use a different name then change this line webView.setBackgroundResource(R.drawable.splash_screen); to map to your splash screen image file) under res/drawable-xxx with corresponding resolutions.
For Eg:
I followed these resolutions for my app's splash screen.
hdpi - 400x800
ldpi - 240x320
mdpi - 320x480
xdpi - 640x960
And try this code:
public class MainActivity extends Activity {
final Activity activity = this;
private WebView webView;
private boolean isSplashOn = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setBackgroundColor(0);
webView.setBackgroundResource(R.drawable.splash_screen);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.setWebViewClient(new MyWebClient());
webView.loadUrl("http://www.google.com");
}
public class MyWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
if(!isSplashOn) {
webView.setBackgroundDrawable(null);
webView.setBackgroundColor(0);
isSplashOn = true;
}
super.onPageFinished(view, url);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
if(webView.canGoBack()) {
webView.goBack();
return true;
}else {
activity.finish();
}
}
return super.onKeyDown(keyCode, event);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
</LinearLayout>
EDIT:
By the way i found the issue with your code. You are trying to set the splash screen to the webview before instantiating it.
Change your code from this:
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
webview = (WebView)findViewById(R.id.output);
to this:
webview = (WebView)findViewById(R.id.output);
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
Why does the splash has to be an activity?
You can make it a full screen ImageView in the bottom of your layout and hide it using a handler:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isDestroyed())
return;
mSplashView.setVisibility(View.GONE);
}
},2000);