Check for internet connection - android

I guess I should start off by saying that I'm completely new to eclipse and java. I'm trying to create a android app using eclipse that launches my web page. I have an example of my code that works just fine, but it's pretty much copied and pasted from examples that I've found online so please excuse my sloppy code. I would like to know how to check if an internet or wifi connection is available.. If there is no connection show an alert (No Internet Connection).. I found some similar questions but, I'm just not sure where to place the code? Can someone please show me?
package com.mysite.news;
import com.mysite.news.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class WebActivity extends Activity {
private WebView wv;
private String LASTURL = "";
Menu myMenu = null;
private static final String PREFS_NAME = "MyPrefs";
private Boolean imgOn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
this.getWindow().requestFeature( Window.FEATURE_PROGRESS );
setContentView( R.layout.web_view );
wv = ( WebView ) findViewById( R.id.web_view );
WebSettings webSettings = wv.getSettings();
webSettings.setSavePassword( true );
webSettings.setSaveFormData( true );
webSettings.setJavaScriptEnabled( true );
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(false);
SharedPreferences settings = getSharedPreferences( PREFS_NAME, 0 );
imgOn = settings.getBoolean( "IMGMODE", false );
webSettings.setLoadsImagesAutomatically( imgOn );
final Activity activity = this;
// start ProgressDialog with "Page loading..."
final ProgressDialog dialog = new ProgressDialog( activity );
dialog.setMessage( "Page loading..." );
dialog.setIndeterminate( true );
dialog.setCancelable( true );
dialog.show();
wv.setWebChromeClient( new WebChromeClient() {
public void onProgressChanged( WebView view, int progress ) {
// set address bar and progress
// activity.setTitle( " " + LASTURL );
// activity.setProgress( progress * 100 );
if( progress == 100 ) {
// stop ProgressDialog after loading
dialog.dismiss();
// activity.setTitle( " " + LASTURL );
}
}
} );
wv.setWebViewClient( new WebViewClient() {
public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
Toast.makeText( getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG ).show();
}
#Override
public boolean shouldOverrideUrlLoading( WebView view, String url ) {
if( url.indexOf( "mysite" ) <= 0 ) {
// the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
startActivity( intent );
return true;
}
return false;
}
public void onPageStarted( WebView view, String url, Bitmap favicon ) {
LASTURL = url;
view.getSettings().setLoadsImagesAutomatically( true );
view.getSettings().setBuiltInZoomControls( true );
}
public void onPageFinished( WebView view, String url ) {
view.loadUrl( "javascript:(function() { " +
"hide('sidebar');" +
//"var parent = document.getElementsByClassName('page-navigation')[0];"+
//"var panel = document.getElementsByClassName('panel-tools')[0];"+
//"var div = document.createElement('div');"+
//"div.innerHTML = panel.innerHTML;"+
//"parent.appendChild(div);"+
//"panel.innerHTML = '';"+
//"div.style['margin-left'] = '31px';"+
"var panel = document.getElementById('search');" +
"panel.style['width'] = '55px';" +
//"var imgs=document.getElementsByTagName('IMG');for(var i=0;i<imgs.length;i++){if (imgs[i].height=60) {imgs[i].src='';imgs[i].width=0;} }"+
//"var urls=document.getElementsByTagName('li');for(var i=0;i<urls.length;i++){if (urls[i].style='margin: -14px 0pt 0pt;'){urls[i].style['display'] = 'none';}}"+
//"hideByClass('panel-tools');"+
"function hide(id){if (document.getElementById(id)){document.getElementById(id).style['display'] = 'none';}}" +
//"function hideByClass(c){var e=document.getElementsByClassName(c);for(var i=0;i<e.length;i++){e[i].style['display'] = 'none';}}"+
"})()" );
if( imgOn ) {
view.getSettings().setLoadsImagesAutomatically( true );
view.getSettings().setSupportZoom(false);
}
}
} );
wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wv.setScrollbarFadingEnabled(false);
wv.loadUrl( "http://www.mysite.com" );
}
#Override
public boolean onKeyDown( int keyCode, KeyEvent event ) {
if( ( keyCode == KeyEvent.KEYCODE_BACK ) && wv.canGoBack() ) {
wv.goBack();
return true;
}
return super.onKeyDown( keyCode, event );
}
#Override
public boolean onCreateOptionsMenu( Menu menu ) {
super.onCreateOptionsMenu( menu );
this.myMenu = menu;
MenuItem item = menu.add( 0, 1, 0, "MAIN PAGE" );
item.setIcon( R.drawable.home );
MenuItem item2 = menu.add( 0, 2, 0, "BACK" );
item2.setIcon( R.drawable.arrowleft );
MenuItem item3 = menu.add( 0, 3, 0, "Reload" );
item3.setIcon( R.drawable.s );
MenuItem item4 = menu.add( 0, 4, 0, "CLEAR CACHE" );
item4.setIcon( R.drawable.trash );
MenuItem item5 = menu.add( 0, 5, 0, "Rate" );
item5.setIcon( R.drawable.vote );
MenuItem item6 = menu.add( 0, 6, 0, "Exit" );
item6.setIcon( R.drawable.close );
return true;
}
#Override
public boolean onOptionsItemSelected( MenuItem item ) {
switch( item.getItemId() ) {
case 1:
wv.loadUrl( "http://mysite.com" );
break;
case 2:
if( wv.canGoBack() ) {
wv.goBack();
}
break;
case 3:
wv.loadUrl( LASTURL );
break;
case 4:
wv.clearCache( true );
break;
case 5:
Intent marketIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(
"https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(marketIntent2);
break;
case 6:
finish();
break;
}
return true;
}
private void saveSettings( Boolean val ) {
SharedPreferences settings = getSharedPreferences( PREFS_NAME, 0 );
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean( "IMGMODE", val );
editor.commit();
}
}

private boolean checkNetwork() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
Toast.makeText(getApplicationContext(),
"Sorry, Network Unavailable! :(", Toast.LENGTH_LONG).show();
}
return false;
}
This snippet helped me out, hope it helps you too. Your usage might look like this.
if (!checkNetwork()) {
//TODO Network Not Available
} else {
//TODO Network Available
}
You might want to put the Toast notification NOT in the function().

check this link
How do you check the internet connection in android?
Use the same solution before you load the url. Show an error dialog if internet is not available else load the url

Here's a helper class I use for Network Connectivity:
public class NetworkUtils
{
public static boolean isOnline( Service service )
{
ConnectivityManager cm = (ConnectivityManager) service.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if ( netInfo != null && netInfo.isConnected() )
{
return true;
}
return false;
}
}
And don't forget to add the permissions to AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

Related

youtubeExtractor for Android

I want to use youtubeExtractor for android app and I found library like
compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'
There is a sample code in github I copied it. After I open app, it closes at the same time. There isn't an error in phone and also Logcat. Only there is
W/System: ClassLoader referenced unknown path: /data/app/oz.videos-1/lib/arm64 on logcat. I am not sure this is a error or not. Any suggestion? Thanks in advance.
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import at.huber.youtubeExtractor.VideoMeta;
import at.huber.youtubeExtractor.YouTubeExtractor;
import at.huber.youtubeExtractor.YtFile;
public class MainActivity extends Activity
{
private static String youtubeLink;
private LinearLayout mainLayout;
private ProgressBar mainProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
mainProgressBar = (ProgressBar) findViewById(R.id.prgrBar);
// Check how it was started and if we can get the youtube link
if (savedInstanceState == null && Intent.ACTION_SEND.equals(getIntent().getAction())
&& getIntent().getType() != null && "text/plain".equals(getIntent().getType()))
{
String ytLink = getIntent().getStringExtra(Intent.EXTRA_TEXT);
if (ytLink != null
&& (ytLink.contains("://youtu.be/") || ytLink.contains("youtube.com/watch?v=")))
{
youtubeLink = ytLink;
// We have a valid link
getYoutubeDownloadUrl(youtubeLink);
}
else
{
Toast.makeText(this, R.string.error_no_yt_link, Toast.LENGTH_LONG).show();
finish();
}
} else if (savedInstanceState != null && youtubeLink != null) {
getYoutubeDownloadUrl(youtubeLink);
} else {
finish();
}
}
private void getYoutubeDownloadUrl(String youtubeLink)
{
new YouTubeExtractor(this)
{
#Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
mainProgressBar.setVisibility(View.GONE);
if (ytFiles == null) {
// Something went wrong we got no urls. Always check this.
finish();
return;
}
// Iterate over itags
for (int i = 0, itag; i < ytFiles.size(); i++) {
itag = ytFiles.keyAt(i);
// ytFile represents one file with its url and meta data
YtFile ytFile = ytFiles.get(itag);
// Just add videos in a decent format => height -1 = audio
if (ytFile.getFormat().getHeight() == -1 || ytFile.getFormat().getHeight() >= 360) {
addButtonToMainLayout(vMeta.getTitle(), ytFile);
}
}
}
}.extract(youtubeLink, true, false);
}
private void addButtonToMainLayout(final String videoTitle, final YtFile ytfile)
{
// Display some buttons and let the user choose the format
String btnText = (ytfile.getFormat().getHeight() == -1) ? "Audio " +
ytfile.getFormat().getAudioBitrate() + " kbit/s" :
ytfile.getFormat().getHeight() + "p";
btnText += (ytfile.getFormat().isDashContainer()) ? " dash" : "";
Button btn = new Button(this);
btn.setText(btnText);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String filename;
if (videoTitle.length() > 55) {
filename = videoTitle.substring(0, 55) + "." + ytfile.getFormat().getExt();
} else {
filename = videoTitle + "." + ytfile.getFormat().getExt();
}
filename = filename.replaceAll("\\\\|>|<|\"|\\||\\*|\\?|%|:|#|/", "");
downloadFromUrl(ytfile.getUrl(), videoTitle, filename);
finish();
}
});
mainLayout.addView(btn);
}
private void downloadFromUrl(String youtubeDlUrl, String downloadTitle, String fileName)
{
Uri uri = Uri.parse(youtubeDlUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(downloadTitle);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
}
Please try to implement the version 2.0.0 of the library:
implementation 'com.github.HaarigerHarald:android-youtubeExtractor:v2.0.0'
May be your savedInstanceState == null, and then finish() method called.
Try call getYoutubeDownloadUrl() with youtube link after mainProgressBar = (ProgressBar) findViewById(R.id.prgrBar);

Android problems opening downloads and urls with mailto and tel

So I am stuck on a issue with my webapp that runs inside a webview from android studio.
I want download like pdf file to be downloaded and opend in the native app on the phone. This work fine by using the download manager from android studio.
How ever I also have links that start with "mailto:" and "tel:" those links give me an error when I don't override the method "shouldOverrideUrlLoading" where I can check what kind of url it is. And then open the propper inten.
So when I combine the 2 the downloadmanager and the custom NavigationHandler that extends the WebViewClient, it doesn't work as expected.
For a better understanding of what is happening.
When I hit a button with a pdf file it downloads the file gives a toast message and opens the file with the native app on the phone. This is without overriding the "shouldOverrideURLLoading" and without my class that extends the WebViewClient.
When I also use my own NavigationHandler witch extends from WebViewClient,
my urls with "mailto:" and "tel:" open with native apps on the phone.
When I now hit a button with a pdf file it is opend in a browser to be downloaded. Witch I don't want. I have tried numerous things to solf the problem but until now without succes.
I run a website app inside of a WebViewClient.
P.S. sorry for the shitty code but it's new to me and haven't find my way jet in coding in Android Studio.
My NavigationHandler class
package nl.firejob.selector;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class NavigationHandler extends WebViewClient {
private static final String TEL_PREFIX = "tel:";
private static final String MAILTO_PREFIX = "mailto:";
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if ( url.startsWith( TEL_PREFIX ) ) {
// This is a tel link, which should be opened with the native thing.
Intent tel = new Intent( Intent.ACTION_DIAL, Uri.parse( url ) );
view.getContext().startActivity( tel );
return true;
} else if ( url.startsWith( MAILTO_PREFIX ) ) {
// This is a mail link, which should be opened with the other native thing.
Intent mail = new Intent(Intent.ACTION_SENDTO);
mail.setType("message/rfc822");
mail.setData(Uri.parse( url ));
view.getContext().startActivity( mail );
return true;
} else if ( Uri.parse(url).getHost().startsWith("myurl.com") ) {
// This is what we want to show in the app, so let the WebView handle it.
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse( url ) );
view.getContext().startActivity( intent );
return true;
}
}
My MainActivity Class
package nl.firejob.selector;
import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private DownloadManager dm;
private Long myDownloadReference;
private BroadcastReceiver receiveDownloadComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
// Allow webview to use javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Stop local links/redirects from opening in browser instead of WebView
mWebView.setWebViewClient(new NavigationHandler() {
#Override
public void onPageFinished(WebView view, String url) {
// Show the webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
// Hide splashscreen objects
findViewById(R.id.imageLogo).setVisibility(View.GONE);
findViewById(R.id.textLogo).setVisibility(View.GONE);
}
});
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if( haveStoragePermission()) {
Log.i("download url",url);
//for downloading directly through download manager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setVisibleInDownloadsUi(true);
request.setDescription("Doorvoerboek").setTitle("doorvoerboek.pdf");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "doorvoerboek.pdf");
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myDownloadReference = dm.enqueue(request);
IntentFilter intentFilter = new IntentFilter( dm.ACTION_DOWNLOAD_COMPLETE);
receiveDownloadComplete = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (myDownloadReference == reference) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(reference);
Cursor cursor = dm.query(query);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
int fileNameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TITLE);
String saveFilePath = cursor.getString(fileNameIndex);
Log.i("filename",saveFilePath);
int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
int reason = cursor.getInt(columnReason);
switch (status){
case DownloadManager.STATUS_SUCCESSFUL:
Toast.makeText(MainActivity.this, "Download Complete", Toast.LENGTH_LONG).show();
Log.i("dir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() );
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() +"/doorvoerboek.pdf");
Intent intentView = new Intent(Intent.ACTION_VIEW);
intentView.setDataAndType(Uri.fromFile(file),"application/pdf");
intentView.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intentView);
break;
}
}
}
};
registerReceiver(receiveDownloadComplete,intentFilter);
}
}
});
mWebView.loadUrl("http://myurl.com/");
}
public boolean haveStoragePermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.e("Permission error","You have permission");
return true;
} else {
Log.e("Permission error","You have asked for permission");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //you dont need to worry about these stuff below api level 23
Log.e("Permission error","You already have the permission");
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
//if Back key pressed and webview can navigate to previous page
mWebView.goBack();
// go back to previous page
return true;
}
else
{
finish();
// finish the activity
}
return super.onKeyDown(keyCode, event);
}
}
This code downloads any file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webView);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
webview.setWebViewClient(new CustomWebViewClient());
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("http://www.website.com");
//Download file code stackoverflow.com
webview.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "downloading",
Toast.LENGTH_LONG).show();
}
});
// Download section of code
} // Close of onCreate
// mailto code stackoverflow.com
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle it
else if (url.startsWith("tel:")) {
Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(tel);
return true;
}
else if (url.startsWith("mailto:")) {
String body = "Enter your Question, Enquiry or Feedback below:\n\n";
Intent mail = new Intent(Intent.ACTION_SEND);
Intent intent = mail.setType("application/octet-stream");
MailTo recipient = MailTo.parse(url);
mail.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient.getTo()});
mail.putExtra(Intent.EXTRA_SUBJECT, "Contact");
mail.putExtra(Intent.EXTRA_TEXT, body);
startActivity(mail);
return true;
}
return true;
}
}
// mailto section of code

How to load html in webview when no internet connected otherwise load website in android [duplicate]

This question already has answers here:
Save webview content for offline browsing?
(2 answers)
Closed 8 years ago.
How to show web page even if internet is not connected? And if internet is connected than website should be loaded on webview
..
I am new for android and i needed an app. i checked over internet and created app.
my dashboard code is :
public class Dashboard extends Activity {
public String BASE_URL = "http://mywebsite.com/";
public String DASHBOARD_URL = BASE_URL;
private JavascriptInterface jsInterface;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
WebView engine = (WebView) findViewById(R.id.web_engine);
// Progress bar.
// With full screen app, window progress bar (FEATURE_PROGRESS) doesn't seem to show,
// so we use an explicitly created one.
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
engine.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
progressBar.setProgress(progress);
}
});
engine.setWebViewClient(new FixedWebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
jsInterface.enablePreferencesMenu = false;
jsInterface.modalIsVisible = false;
jsInterface.urlForSharing = null;
progressBar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url)
{
progressBar.setVisibility(View.GONE);
}
});
engine.getSettings().setJavaScriptEnabled(true);
jsInterface = new JavascriptInterface();
try {
ComponentName comp = new ComponentName(this, Dashboard.class);
PackageInfo pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0);
jsInterface.versionCode = pinfo.versionCode;
} catch(android.content.pm.PackageManager.NameNotFoundException e) {
}
engine.addJavascriptInterface(jsInterface, "Title");
engine.loadUrl(BASE_URL);
}
private WebView getEngine() {
return (WebView) findViewById(R.id.web_engine);
}
public void onBackPressed() {
WebView engine = getEngine();
String url = engine.getUrl();
if (jsInterface.modalIsVisible) {
engine.loadUrl("javascript: android.hideModal();");
} else if (url != null && (
url.equals(BASE_URL) ||
url.equals(DASHBOARD_URL) ||
!engine.canGoBack())) {
// exit
super.onBackPressed();
} else {
// go back a page, like normal browser
engine.goBack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem prefs = menu.findItem(R.id.preferences_menuitem);
if (prefs != null) {
prefs.setVisible(jsInterface.enablePreferencesMenu);
}
super.onPrepareOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.dashboard_menuitem:
getEngine().loadUrl(DASHBOARD_URL);
return true;
case R.id.refresh_menuitem:
getEngine().reload();
return true;
case R.id.preferences_menuitem:
getEngine().loadUrl("javascript: android.showPreferences()");
return true;
case R.id.contact_menuitem:
AboutBox.Show(Dashboard.this);
return true;
case R.id.share_url_menuitem:
final String url = (jsInterface.urlForSharing != null
? jsInterface.urlForSharing
: getEngine().getUrl());
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Android URL");
i.putExtra(Intent.EXTRA_TEXT, url);
startActivity(Intent.createChooser(i, "Share"));
default:
return super.onOptionsItemSelected(item);
}
}
private class FixedWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(BASE_URL) || url.startsWith("javascript:")) {
// handle by the WebView
return false;
} else if (url.startsWith("mailto:")) {
MailTo mt = MailTo.parse(url);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
i.putExtra(Intent.EXTRA_SUBJECT, mt.getSubject());
i.putExtra(Intent.EXTRA_CC, mt.getCc());
i.putExtra(Intent.EXTRA_TEXT, mt.getBody());
view.getContext().startActivity(i);
view.reload();
return true;
} else {
// Use external browser for anything not on this site
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(i);
return true;
}
}
}
// The methods of JavascriptInterface are called from javascript.
// The attributes are accessed from the Dashboard class.
// This is deliberately a dumb container class to stop possible
// security issues of javascript controlling Java app.
final class JavascriptInterface {
public boolean enablePreferencesMenu = false;
public boolean modalIsVisible = false;
public int versionCode = 0;
public String urlForSharing = null;
public void setEnablePreferencesMenu() {
enablePreferencesMenu = true;
}
public void setModalIsVisible(boolean visible) {
modalIsVisible = visible;
}
// This is useful for allowing the web site to be able to detect
// old app versions and prompt the user to upgrade.
public int getVersionCode() {
return versionCode;
}
public void setUrlForSharing(String url) {
urlForSharing = url;
}
}
}
Where should i edit to show no network connected message if device is not connected to internet???
First you need to check whether or not internet is connected to your device, you can check internet connection with below method
public static boolean checkNetworkConnection(Context _context){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
This method will return either true[If internet is connected] or false[if not connected]
Based on that true or false value you can decide whether to display html page or web page
Now Question is if you want to display webpage from your local folder than you can do it like this
You can load local html file as below
WebView lWebView = (WebView)findViewById(R.id.webView);
File lFile = new File(Environment.getExternalStorageDirectory() + "<FOLDER_PATH_TO_FILE>/<FILE_NAME>");
lWebView.loadUrl("file:///" + lFile.getAbsolutePath());
And if you want to display cahed html page than you need to do some R & D task for that.
Now if internet is connected than you can use below method to display web page on webview
wbb = (WebView) findViewById(R.id.webView_tobe_loaded);
WebSettings wbset=wbb.getSettings();
wbset.setJavaScriptEnabled(true);
wbb.setWebViewClient(new MyWebViewClient());
String url="http://www.google.com";
System.out.println(getdeviceid());
wbb.getSettings().setJavaScriptEnabled(true);
wbb.loadUrl(url);
I hope you understood all the explanation
You can check for internet connection using this:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
more info here: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
And to show HTML without load it from the internet:
webview.loadData("<b>Connection not availeable</b>", "text/html", null);
more info: http://developer.android.com/reference/android/webkit/WebView.html#loadData(java.lang.String,java.lang.String, java.lang.String)

When going back through activities, application stalls

I have this code, that goes through steps, aquired from a webservice.
I implemented my own history, so that the user can go back through performed steps.
The problem is that the same step can be visited more than once and that seems to cause my history to fail.
It can go back just fine, but sometimes it takes more than one press on the back button to go to the previous step.
Here's the code for my class that manages history:
private ArrayList<String> idList;
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
if ( idList == null )
{
idList = new ArrayList<String>();
}
}
#Override
public void finishFromChild( Activity child )
{
LocalActivityManager manager = getLocalActivityManager();
int index = idList.size()-1;
if ( index < 1 )
{
finish();
return;
}
manager.destroyActivity( idList.get( index ), true );
idList.remove( index ); index--;
String lastId = idList.get( index );
Activity lastActivity = manager.getActivity( lastId );
Intent lastIntent = lastActivity.getIntent();
Window newWindow = manager.startActivity( lastId, lastIntent );
setContentView( newWindow.getDecorView() );
}
public void startChildActivity( String id, Intent intent )
{
id += System.currentTimeMillis();
if ( "restart".equalsIgnoreCase( id ) )
{
idList.clear();
}
Window window = getLocalActivityManager().startActivity( id, intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ) );
if ( window != null )
{
idList.add( id );
setContentView( window.getDecorView() );
}
}
public Activity getCurrentActivity()
{
int length = idList.size();
if ( idList.isEmpty() ) {
return null;
}
else
{
return getLocalActivityManager().getActivity( idList.get( length-1 ) );
}
}
#Override
public boolean onKeyDown( int keyCode, KeyEvent event )
{
if ( keyCode == KeyEvent.KEYCODE_BACK )
{
return true;
}
return super.onKeyDown( keyCode, event );
}
#Override
public boolean onKeyUp( int keyCode, KeyEvent event )
{
if ( keyCode == KeyEvent.KEYCODE_BACK )
{
onBackPressed();
return true;
}
return super.onKeyUp( keyCode, event );
}
#Override
public void onBackPressed()
{
int length = idList.size();
if ( length > 1 )
{
Activity current = getLocalActivityManager().getActivity( idList.get( length-1 ) );
current.finish();
}
}
Turns of that the FLAG_ACTIVITY_CLEAR_TOP flag
in my method
public void startChildActivity( String id, Intent intent )
{
id += System.currentTimeMillis();
if ( "restart".equalsIgnoreCase( id ) )
{
idList.clear();
}
Window window = getLocalActivityManager().startActivity( id, intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ) );
if ( window != null )
{
idList.add( id );
setContentView( window.getDecorView() );
}
}
Was messing things up, now everything is working perfectly.

My Intent script always showing an error

i'm creating a login application
the login script is ok it's returned true and false
if the response returns true or 1, i want to make it to go to another activity called inputBarcode, the eclipse showing an error on my Intent line and i don't know what to do
i didn't know the other variations of making Intents
this is my full code, the Intent that i want to call is on the bottom after if(res.equals("1")){ :
package com.nigmagrid.go;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
//import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
public class login extends Activity {
String lokasiTugas;
boolean status_npp;
boolean status_password;
boolean status_lokasi;
Button button;
EditText usernameEditText, passwordEditText;
TextView error;
Spinner lokasiSpinner;
final int minNPP = 3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.login);
final Button button = (Button) findViewById(R.id.login_button);
final EditText usernameEditText = (EditText) findViewById(R.id.login_npp);
final EditText passwordEditText = (EditText) findViewById(R.id.login_password);
final Spinner lokasiSpinner = (Spinner) findViewById(R.id.spinner1);
final TextView error = (TextView) findViewById(R.id.login_status);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.lokasi_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lokasiSpinner.setAdapter(adapter);
lokasiSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
//Toast.makeText(getApplicationContext(), adapter.getItemAtPosition(i).toString(), Toast.LENGTH_SHORT).show();
lokasiTugas = adapter.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView arg0) {
//do something else
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
error.setText("Menghubungkan ke server...");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", usernameEditText.getText().toString()));
postParameters.add(new BasicNameValuePair("password", passwordEditText.getText().toString()));
String response = null;
String sNPP = usernameEditText.getText().toString().replace(" ", "");
String sPassword = passwordEditText.getText().toString();
// validasi NPP
if(sNPP.length()<=minNPP){
usernameEditText.setError("NPP minimal "+minNPP+" angka");
status_npp = false;
}else{
status_npp = true;
//Toast.makeText(getApplicationContext(), "NPP Anda : "+sNPP, Toast.LENGTH_SHORT).show();
}
// validasi Password
if(sPassword.length()<1){
passwordEditText.setError("Kata sandi diperlukan");
status_password = false;
}else{
status_password = true;
}
//validasi lokasiTugas
if(lokasiTugas.equals("Pilih Lokasi")){
Toast.makeText(getApplicationContext(), "Lokasi Tugas diperlukan", Toast.LENGTH_SHORT).show();
status_lokasi = false;
}else{
status_lokasi = true;
}
// pengecekan akhir
if(status_npp == true && status_password == true && status_lokasi == true){
//Toast.makeText(getApplicationContext(), "NPP Anda : "+sNPP+"\nLokasi : "+lokasiTugas, Toast.LENGTH_SHORT).show();
//fungsi login disini :D
try{
// variabel cek-nya ganti
String cek = "http://almezuflash.zxq.net/kspt-android/ceklogin.php";
response = CustomHttpClient.excecuteHttpPost(cek, postParameters);
String res = response.toString();
res = res.replaceAll("\\s", "");
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();
if(res.equals("1")){
error.setText("Login sukses");
Toast.makeText(getApplicationContext(), "Login Sukses", Toast.LENGTH_SHORT).show();
// i want to make Intent but eclipse says error, and i don't know what to do
Intent doBarcode = new Intent(parent, inputBarcode.class);
startActivity(doBarcode);
}else{
error.setText("Login gagal");
//Toast.makeText(getApplicationContext(), "Login Gagal", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
//error.setText(e.toString());
error.setText("Terjadi kesalahan, silahkan periksa koneksi internet anda");
}
}else{
//Toast.makeText(getApplicationContext(), "Otorisasi Gagal", Toast.LENGTH_SHORT).show();
status_npp = false;
status_password = false;
status_lokasi = false;
error.setText("Login gagal, silahkan periksa kembali");
}
}
});
}
}
Sorry for my bad english, i'm from Indonesia fyi :D
Did you make sure to add the inputBarCode activity to your AndroidManifiest? If you did not, then that will give a runtime error. If thats no the problem, then possibly changing
Intent doBarcode = new Intent(parent, inputBarcode.class);
to
Intent doBarcode = new Intent(this, inputBarcode.class);
will solve your problem. I'm not familiar with the parent variable being used.
I hope that helps.
Try instead of
Intent doBarcode = new Intent(parent, inputBarcode.class);
use this code:
Intent doBarcode = new Intent(login.this, inputBarcode.class);

Categories

Resources