How to open WebView when click on Card View - android

I trying to open WebView when I click on Card View. The WebView is implemented in Main Activity. It is not working. I am new in coding. This is the Dashboard Activity 👇. Please tell me how can I solve the problem.
public class DashBoardActivity extends MainActivity implements View.OnClickListener {
public CardView card1, card2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( activity_dashboard );
card1 = findViewById( R.id.c1 );
card2 = findViewById( R.id.c2 );
card1.setOnClickListener( this );
card2.setOnClickListener( this );
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.nav_home1) {
web_view( "example1.com" );
} else if (id == R.id.nav_home2) {
web_view( "example2.com");
}
}
}

You don't need to extend your Main Activity.
Just pass the URL in Intent Extras to your Main Activity and start it there.
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MainActivity.class);
String example1 = "example1.com";
String example2="example2.com";
int id = v.getId();
if (id == R.id.nav_home1) {
intent.putExtra("URL", example1);
} else if (id == R.id.nav_home2) {
intent.putExtra("URL", example2);
}
startActivity(intent);
}
Then retrieve these extras in your onCreate MainActivity
private WebView wv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
url= null;
} else {
url= extras.getString("URL");
}
} else {
url= (String) savedInstanceState.getSerializable("URL");
}
wv1=(WebView)findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}

Related

How to move from activity to fragment

I wrote this code for login and for chatting;
login is an activity where is chatting is a fragment; here is my activity :
public class Consultant extends AppCompatActivity {
private FirebaseAuth auth;
private Button loginbtn;
private EditText email;
private EditText pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consultant);
auth = FirebaseAuth.getInstance();
loginbtn = (Button) findViewById(R.id.loginbtn);
email = (EditText) findViewById(R.id.email);
pass = (EditText) findViewById(R.id.pass);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkEmailandpassword();
}
});
}
public boolean checkEmailandpassword() {
if (validate()) {
String CEmail = email.getText().toString().trim();
String CPass = pass.getText().toString().trim();
auth.signInWithEmailAndPassword(CEmail, CPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Consultant.this, "welcome", Toast.LENGTH_LONG).show();
Intent i = new Intent(Consultant.this,Consultant_Home_Chatting.class);
startActivity(i);
} else {
Toast.makeText(Consultant.this, "wrong ", Toast.LENGTH_LONG).show();
}
}
});
}
return false;
}
private boolean validate() {
boolean result = false;
String CPass = pass.getText().toString();
String CEmail = email.getText().toString();
if (CPass.isEmpty() || CEmail.isEmpty()) {
Toast.makeText(Consultant.this, "all fields required", Toast.LENGTH_LONG).show();
} else {
result = true;
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_nav, menu);
return true;
}
}
and here my fragment :
public class Consultant_Home_Chatting extends Fragment {
private ViewPager mViewP ;
private FirebaseAuth mAuth ;
private TabLayout mTab ;
private TabsPagerAdapter mAdapter ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_consultant__home__chatting, container, false);
}
public Consultant_Home_Chatting() {
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
mViewP = (ViewPager) getView().findViewById(R.id.main_tabs_pager);
mAdapter = new TabsPagerAdapter(getFragmentManager());
mViewP.setAdapter(mAdapter);
mTab = (TabLayout) getView().findViewById(R.id.main_tabs);
mTab.setupWithViewPager(mViewP);
}
I tried to add a new class holding these liens then make a constructor in my fragment and onCreatOptions method in my activity but it does not work!
I think the solution is to use the Bundle but I don't know how to use it or can I use it and what can I send inside put extra, can you please help?
if (savedInstanceState == null){
getFragmentManager().beginTransaction()
.add(android.R.id.content, new Consultant_Home_Chatting ()).commit();}
to use bundle simple create the instance of your fragment and then create bundle add all data you want and add this bundle to the fragment.
Here is example:
In activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestFragment testFragment = new TestFragment();
Bundle bundle = new Bundle();
bundle.putString("name", "John");
bundle.putInt("age", 24);
testFragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, testFragment).commit();
}
In your fragment:
public class TestFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if(bundle != null){
String name = bundle.getString("name");
int age =`enter code here` bundle.getInt("age");
}
}
}

How to open url in webview activity

How to open Url in Webview activity
Hi,
i want to open link in WebView activity right now my code is scan barcode & open link directly to browser but
i want to change it and open in Webview
how can i do this please help me to fix this issue
thanks
here is code of BarcodeScannerActivity
public class BarcodeScannerActivity extends AppCompatActivity {
String scanContent;
String scanFormat;
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode_scanner);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(BarcodeScannerActivity.this);
scanIntegrator.setPrompt("Scan");
scanIntegrator.setBeepEnabled(true);
//enable the following line if you want QR code
//scanIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
scanIntegrator.setCaptureActivity(CaptureActivityAnyOrientation.class);
scanIntegrator.setOrientationLocked(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null) {
if (scanningResult.getContents() != null) {
scanContent = scanningResult.getContents().toString();
scanFormat = scanningResult.getFormatName().toString();
}
Toast.makeText(this, scanContent + " type:" + scanFormat, Toast.LENGTH_SHORT).show();
textView.setText(scanContent + " type:" + scanFormat);
Intent browseintent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com/index.php?iduser="+ scanContent));
startActivity(browseintent);
} else {
Toast.makeText(this, "Nothing scanned", Toast.LENGTH_SHORT).show();
}
}
}
Webview Activity Code
public class SecondActivity extends AppCompatActivity {
Button b1;
EditText ed1;
private WebView wv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);
wv1=(WebView)findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = ed1.getText().toString();
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Replace the following code
Intent browseintent=new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com/index.php?iduser="+ scanContent));
startActivity(browseintent);
with below code
Intent browseintent=new Intent(this, SecondActivity.class);
browseintent.putExtra("url","http://www.example.com/index.php?iduser="+ scanContent);
startActivity(browseintent);
This will open the secondactivity with url in intent extras. You can set it to your edittext or you can use it directly to your webview.
You can receive the url in the second activity using the following code
String url = getIntent().getExtras().getString("url");
You can use it in your button click as follows
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = getIntent().getExtras().getString("url");
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
You try this, it should open link with webview:
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowContentAccess(true);
settings.setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://vk.com/zabroshkiborika");

Cannot click on interstitial ad in WebView fragment

I have made an AdvanceWebView Application.
In that I have made a function to show interstitialAd in "fragmentActivity", that means whenever I download something from that webview that Ad will show up but it isn't clickable.
I think my ad is showing behind that fragment or something like that or maybe some other issue.
And when Vedio Ads are showen, the countdown of that ad also doesn't woprking.
I can see the Ad but it isn't clickable and if I click on any part of Ad, Logcat
is showing this => "I/HwSecImmHelper: mSecurityInputMethodService is null"
Here it is some part of my code:
WebfragmentActivy:
public class WebFragment extends Fragment implements AdvancedWebView.Listener, SwipeRefreshLayout.OnRefreshListener{
//Layouts
public FrameLayout rl;
public AdvancedWebView browser;
public SwipeRefreshLayout swipeLayout;
public ProgressBar progressBar;
//WebView Clients
public WebToAppChromeClient chromeClient;
public WebToAppWebClient webClient;
//WebView Session
public String mainUrl = null;
static String URL = "url";
public int firstLoad = 0;
//Keep track of the interstitials we show
private int interstitialCount = -1;
public WebFragment() {
// Required empty public constructor
}
public static WebFragment newInstance(String url) {
WebFragment fragment = new WebFragment();
Bundle args = new Bundle();
args.putString(URL, url);
fragment.setArguments(args);
return fragment;
}
public void setBaseUrl(String url){
this.mainUrl = url;
browser.loadUrl(mainUrl);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null && mainUrl == null) {
mainUrl = getArguments().getString(URL);
firstLoad = 0;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rl = (FrameLayout) inflater.inflate(R.layout.fragment_observable_web_view, container,
false);
progressBar = (ProgressBar) rl.findViewById(R.id.progressbar);
browser = (AdvancedWebView) rl.findViewById(R.id.scrollable);
swipeLayout = (SwipeRefreshLayout) rl.findViewById(R.id.swipe_container);
return rl;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Config.PULL_TO_REFRESH)
swipeLayout.setOnRefreshListener(this);
else
swipeLayout.setEnabled(false);
// Setting the webview listeners
browser.setListener(this, this);
// set javascript and zoom and some other settings
browser.requestFocus();
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setBuiltInZoomControls(false);
browser.getSettings().setAppCacheEnabled(true);
browser.getSettings().setDatabaseEnabled(true);
browser.getSettings().setDomStorageEnabled(true);
// Below required for geolocation
browser.setGeolocationEnabled(true);
// 3RD party plugins (on older devices)
browser.getSettings().setPluginState(PluginState.ON);
if (Config.MULTI_WINDOWS) {
browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
browser.getSettings().setSupportMultipleWindows(true);
}
webClient = new WebToAppWebClient(getActivity(), browser);
browser.setWebViewClient(webClient);
chromeClient = new WebToAppChromeClient(getActivity(), rl, browser, swipeLayout, progressBar);
browser.setWebChromeClient(chromeClient);
// load url (if connection available
if (webClient.hasConnectivity(mainUrl, true)) {
String pushurl = ((App) getActivity().getApplication()).getPushUrl();
if (pushurl != null){
browser.loadUrl(pushurl);
} else {
browser.loadUrl(mainUrl);
}
}
}
#Override
public void onRefresh() {
browser.reload();
}
#SuppressLint("NewApi")
#Override
public void onPause() {
super.onPause();
browser.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
browser.onDestroy();
}
#SuppressLint("NewApi")
#Override
public void onResume() {
super.onResume();
browser.onResume();
}
#SuppressLint("NewApi")
#Override
public void onDownloadRequested(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if (!hasPermissionToDownload(getActivity())) return;
String filename = null;
try {
filename = new GetFileInfo().execute(url).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (filename == null) {
String fileExtenstion = MimeTypeMap.getFileExtensionFromUrl(url);
filename = URLUtil.guessFileName(url, null, fileExtenstion);
}
if (AdvancedWebView.handleDownload(getActivity(), url, filename)) {
Toast.makeText(getActivity(), getResources().getString(R.string.download_done), Toast.LENGTH_SHORT).show();
onDownloadInterstitialAd();
}
else {
Toast.makeText(getActivity(), getResources().getString(R.string.download_fail), Toast.LENGTH_SHORT).show();
}
}
private static boolean hasPermissionToDownload(final Activity context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED )
return true;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.download_permission_explaination);
builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
context.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
});
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
if (firstLoad == 0 && MainActivity.getCollapsingActionBar()){
((MainActivity) getActivity()).showToolbar(this);
firstLoad = 1;
} else if (firstLoad == 0){
firstLoad = 1;
}
}
/**
* Show an interstitial ad
*/
private void onDownloadInterstitialAd(){
final InterstitialAd mInterstitialAd = new InterstitialAd(getActivity());
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ad_interstitial_id));
AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mInterstitialAd.show();
}
});
mInterstitialAd.loadAd(adRequestInter);
}
#Override
public void onPageFinished(String url) {
//showInterstitial();
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
// TODO Auto-generated method stub
}
#Override
public void onExternalPageRequest(String url) {
// TODO Auto-generated method stub
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
browser.onActivityResult(requestCode, resultCode, data);
}
}
And this is my Main Activity:
public class MainActivity extends AppCompatActivity implements DrawerFragment.DrawerFragmentListener{
//Views
public Toolbar mToolbar;
public View mHeaderView;
public TabLayout mSlidingTabLayout;
public SwipeableViewPager mViewPager;
//App Navigation Structure
private NavigationAdapter mAdapter;
private DrawerFragment drawerFragment;
private WebFragment CurrentAnimatingFragment = null;
private int CurrentAnimation = 0;
//Identify toolbar state
private static int NO = 0;
private static int HIDING = 1;
private static int SHOWING = 2;
//Keep track of the interstitials we show
private int interstitialCount = 0;
SharedPreferences prefs;
public FirebaseAuth authtt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
authtt = FirebaseAuth.getInstance();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mHeaderView = (View) findViewById(R.id.header_container);
mSlidingTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (SwipeableViewPager) findViewById(R.id.pager);
setSupportActionBar(mToolbar);
mAdapter = new NavigationAdapter(getSupportFragmentManager(), this);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
String data = intent.getDataString();
((App) getApplication()).setPushUrl(data);
}
hasPermissionToDo(this, Config.PERMISSIONS_REQUIRED);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
if ((Config.HIDE_ACTIONBAR && getHideTabs()) || ((Config.HIDE_ACTIONBAR || getHideTabs()) && getCollapsingActionBar())){
lp.topMargin = 0;
} else if ((Config.HIDE_ACTIONBAR || getHideTabs()) || (!Config.HIDE_ACTIONBAR && !getHideTabs() && getCollapsingActionBar())){
lp.topMargin = getActionBarHeight();
} else if (!Config.HIDE_ACTIONBAR && !getHideTabs()){
lp.topMargin = getActionBarHeight() * 2;
}
if (Config.USE_DRAWER) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
drawerFragment = (DrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
} else {
((DrawerLayout) findViewById(R.id.drawer_layout)).setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
mViewPager.setLayoutParams(lp);
mViewPager.setAdapter(mAdapter);
mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount() - 1);
mSlidingTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.accent));
mSlidingTabLayout.setupWithViewPager(mViewPager);
mSlidingTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (getCollapsingActionBar()) {
showToolbar(getFragment());
}
mViewPager.setCurrentItem(tab.getPosition());
showInterstitial();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
for (int i = 0; i < mSlidingTabLayout.getTabCount(); i++) {
if (Config.ICONS.length > i && Config.ICONS[i] != 0) {
mSlidingTabLayout.getTabAt(i).setIcon(Config.ICONS[i]);
}
}
// admob
if (!getResources().getString(R.string.ad_banner_id).equals("")) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
} else {
AdView adView = (AdView) findViewById(R.id.adView);
adView.setVisibility(View.GONE);
}
// application rating
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.rate_title))
.setMessage(String.format(getString(R.string.rate_message), getString(R.string.app_name)))
.setPositiveButton(getString(R.string.rate_yes), null)
.setNegativeButton(getString(R.string.rate_never), null)
.setNeutralButton(getString(R.string.rate_later), null);
new AppRate(this)
.setShowIfAppHasCrashed(false)
.setMinDaysUntilPrompt(2)
.setMinLaunchesUntilPrompt(2)
.setCustomDialog(builder)
.init();
// showing the splash screen
if (Config.SPLASH) {
findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE);
//getFragment().browser.setVisibility(View.GONE);
}
}
// using the back button of the device
#Override
public void onBackPressed() {
View customView = null;
WebChromeClient.CustomViewCallback customViewCallback = null;
if (getFragment().chromeClient != null) {
customView = getFragment().chromeClient.getCustomView();
customViewCallback = getFragment().chromeClient.getCustomViewCallback();
}
if ((customView == null)
&& getFragment().browser.canGoBack()) {
getFragment().browser.goBack();
} else if (customView != null
&& customViewCallback != null) {
customViewCallback.onCustomViewHidden();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setTitle(String title) {
if (mAdapter != null && mAdapter.getCount() == 1 && !Config.USE_DRAWER && !Config.STATIC_TOOLBAR_TITLE)
getSupportActionBar().setTitle(title);
}
public WebFragment getFragment(){
return (WebFragment) mAdapter.getCurrentFragment();
}
boolean getHideTabs(){
if (mAdapter.getCount() == 1 || Config.USE_DRAWER){
return true;
} else {
return Config.HIDE_TABS;
}
}
#Override
public boolean onDrawerItemSelected(View view, int position) {
String url = Config.URLS[position];
if (WebToAppWebClient.urlShouldOpenExternally(url)){
try {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch(ActivityNotFoundException e) {
if (url.startsWith("intent://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url.replace("intent://", "http://"))));
} else {
Toast.makeText(this, getResources().getString(R.string.no_app_message), Toast.LENGTH_LONG).show();
}
}
return false;
} else {
getFragment().browser.loadUrl("about:blank");
getFragment().setBaseUrl(Config.URLS[position]);
showInterstitial();
return true;
}
}
private static boolean hasPermissionToDo(final Activity context, final String[] permissions) {
boolean oneDenied = false;
for (String permission : permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ContextCompat.checkSelfPermission(context, permission)
!= PackageManager.PERMISSION_GRANTED)
oneDenied = true;
}
if (!oneDenied) return true;
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
builder.setMessage(R.string.common_permission_explaination);
builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
context.requestPermissions(permissions,1);
}
});
android.support.v7.app.AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
return false;
}
}

How do I display ProgressDialog using Fragment

I have a Fragment activity that has a ListFragment on the left and a Fragment on the right that has a WebView. The functionality works fine but I would like to display a progress dialog showing "Loading..." while the web page finishes loading. How can I accomplish this seemingly trivial task?
Below is my code:
public class ArticleListActivity extends FragmentActivity implements
ArticleListFragment.OnArticleSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articlelist_fragment);
}
public void onArticleSelected(String contentLink) {
ArticleViewerFragment viewer = (ArticleViewerFragment) getSupportFragmentManager()
.findFragmentById(R.id.articleview_fragment);
if (viewer == null || !viewer.isInLayout()) {
Intent showContent = new Intent(getApplicationContext(),
ArticleViewerActivity.class);
showContent.setData(Uri.parse(contentLink));
startActivity(showContent);
} else {
viewer.updateUrl(contentLink);
}
}
}
Here is my FragmentActivity
public class ArticleViewerActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articleview_fragment);
Intent launchingIntent = getIntent();
String content = launchingIntent.getData().toString();
ArticleViewerFragment viewer = (ArticleViewerFragment) getSupportFragmentManager()
.findFragmentById(R.id.articleview_fragment);
viewer.updateUrl(content);
}
}
and here is my Fragment
public class ArticleViewerFragment extends Fragment {
private ProgressDialog progressBar;
private WebView viewer = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
viewer = (WebView) inflater.inflate(R.layout.webview_layout, container, false);
viewer.loadUrl("file:///android_asset/default.html");
return viewer;
}
public void updateUrl(String newUrl) {
if (viewer != null) {
viewer.loadUrl(newUrl);
}
}
}
Use this code:
final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);
pd.setCancelable(false);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
}
});
webview.loadUrl("file:///android_asset/default.html");

Need help in debugging NullPointerException in Android

I have a about class in my app to show some button and when the user click on the button it jump to a webview activity to view some webpage so I defined urls in the about class, then set onlick method to deliver them to the same webview activity to open the web page, but I keep getting a curious NullPointerException when running this activity and my logcat print nothing but
12-02 09:03:11.815: WARN/ActivityManager(51): Activity idle timeout
for HistoryRecord{44d68ea0 com.appkon.hdtvs/.About} 12-02
09:03:17.026: WARN/ActivityManager(51): Activity destroy timeout for
HistoryRecord{44e37518 com.appkon.hdtvs/.HDtvs}
Here are my code.Any help would be appreciated, thank you
About.java
public class About extends Activity{
private Button backbutton;
private Button likebutton;
private ImageView versionlogo;
private ImageButton faq;
private ImageButton forum;
private ImageButton feedback;
private ImageButton rate;
private String likepath ="http://appkon.com/hdtvs/share.html";
private String likename = "分享";
private String lpath="" ;
private String lname="" ;
private String faqpath ="http://appkon.com/hdtvs/faq.html";
private String faqname ="常见问题";
private String forumpath= "http://appkon.com/forum/" ;
private String forumname = "APP论坛";
private String fqpath="";
private String fqname="";
private String frpath="";
private String frname="";
private String ratepath ="http://appkon.com/hdtvs/";
private String ratename="评价";
private String rpath="";
private String rname="";
private String feedbackpath ="http://appkon.com/hdtvs/feedback.html";
private String feedbackname="反馈问题";
private String fdname="";
private String fdpath="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
backbutton=(Button) findViewById(R.id.back);
likebutton=(Button) findViewById(R.id.share);
faq =(ImageButton)findViewById(R.id.faqbutton);
forum =(ImageButton)findViewById(R.id.forumbutton);
feedback =(ImageButton)findViewById(R.id.feedbackbutton);
rate =(ImageButton)findViewById(R.id.ratebutton);
backbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(About.this, HDtvs.class);
startActivity(intent);
About.this.finish();
}
});
likebutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(About.this, Renrenframe.class);
startActivity(intent);
About.this.finish();
}
});
faq.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(About.this, Aboutframe.class);
Bundle bundle = new Bundle();
bundle.putString("fqpath",faqpath);
bundle.putString("fqname",faqname);
intent.putExtras(bundle);
startActivity(intent);
About.this.finish();
}
});
feedback.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(About.this, Aboutframe.class);
Bundle bundle = new Bundle();
bundle.putString("fdpath",feedbackpath);
bundle.putString("fdname",feedbackname);
intent.putExtras(bundle);
startActivity(intent);
About.this.finish();
}
});
rate.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(About.this, Aboutframe.class);
Bundle bundle = new Bundle();
bundle.putString("rpath",ratepath);
bundle.putString("rname",ratename);
intent.putExtras(bundle);
startActivity(intent);
About.this.finish();
}
});
forum.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(About.this, Aboutframe.class);
Bundle bundle = new Bundle();
bundle.putString("frpath",forumpath);
bundle.putString("frname",forumname);
intent.putExtras(bundle);
startActivity(intent);
About.this.finish();
}
});
}
}
Aboutframe.java
public class Aboutframe extends Activity{
private TextView namebar;
private ImageButton likebutton;
private ImageButton backbutton;
private WebView aboutframe;
private String lpath ;
private String lname ;
private String fqpath;
private String fqname;
private String frpath;
private String frname;
private String rpath;
private String rname;
private String fdname;
private String fdpath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutframe);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar
backbutton=(ImageButton) findViewById(R.id.back);
likebutton=(ImageButton) findViewById(R.id.share);
aboutframe =(WebView)findViewById(R.id.aboutframe);
Intent intent=this.getIntent();
Bundle bunde = intent.getExtras();
lname = bunde.getString("lname");
lpath = bunde.getString("lpath");
fqname = bunde.getString("fqname");
fqpath = bunde.getString("fqpath");
frname = bunde.getString("frname");
frpath = bunde.getString("frpath");
rname = bunde.getString("rname");
rpath = bunde.getString("rpath");
fdname = bunde.getString("fdname");
fdpath = bunde.getString("fdpath");
if(lname != null&lpath!= null){
namebar.setText(lname);
aboutframe.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(lpath);
return true;
}
});
}
if(fqname != null&fqpath!= null){
namebar.setText(fqname);
aboutframe.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(fqpath);
return true;
}
});
}
if(frname != null&frpath!= null){
namebar.setText(frname);
aboutframe.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(frpath);
return true;
}
});
}
if(rname != null&rpath!= null){
namebar.setText(rname);
aboutframe.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(rpath);
return true;
}
});
}
if(fdname != null&fdpath!= null){
namebar.setText(fdname);
aboutframe.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(fdpath);
return true;
}
});
backbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(Aboutframe.this, About.class);
startActivity(intent);
Aboutframe.this.finish();
}
});
likebutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(Aboutframe.this, Renrenframe.class);
startActivity(intent);
Aboutframe.this.finish();
}
});
}
}
}
That error means your activity timed out.
I don't understand why you call:
aboutframe.setWebViewClient
multiple times. You can try to replace if's with if else's:
/*...*/
else if(frname != null&frpath!= null){
/*...*/
else if(rname != null&rpath!= null){
/*...*/
put all your code between
try
{
your Code here...
}
catch(NullPointerException e)
{
e.printStackTrace();
}
You better use && instead of &. The latter is "binary and", you want to use "logical and".

Categories

Resources