0

iam begineer in android development , i would like to diplay my custom/own error message instead of web page not avaialble message when my device is not connected to internet .

Here is my Main activity.java Source:

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ShareActionProvider;


public class MainActivity extends Activity {

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.loadUrl("http://tech2dsk.blogspot.in/");
        mWebView.setWebViewClient(new com.example.tech2dsk.tech2dsk.MyAppWebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                //hide loading image
                findViewById(R.id.progressBar1).setVisibility(View.GONE);
                //show webview
                findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
            }});


    }

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }


    private ShareActionProvider mShareActionProvider;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        /** Inflating the current activity's menu with res/menu/items.xml */
        getMenuInflater().inflate(R.menu.menu_main, menu);

        /** Getting the actionprovider associated with the menu item whose id is share */
        mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();

        /** Setting a share intent */
        mShareActionProvider.setShareIntent(getDefaultShareIntent());

        return super.onCreateOptionsMenu(menu);

    }

    /** Returns a share intent */
    private Intent getDefaultShareIntent(){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
        intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
        return intent;

    }


}

and here is myappwebviewclient.java source :

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Created by Karthik's on 3/5/2015.
 */
public class MyAppWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(Uri.parse(url).getHost().endsWith("tech2dsk.blogspot.in")) {
            return false;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }
}

Plz help me in Fixing this.

Rohith
  • 43
  • 2
  • 11

2 Answers2

1
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf = cm.getActiveNetworkInfo();
    if (nf != null && nf.isConnected()){
       // do your stuff here
    } else {
        Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
    }
}
Chaudhary Amar
  • 836
  • 8
  • 20
1

Check this link on stackoverflow. They talk about to check and customize.

or if want to check if it was internet connection, you can use:

public static boolean checkAppConnectionStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    }else{
        return false;
    }
}

So you can call anywhere:

 if (!Utils.checkAppConnectionStatus(ActivityClass.this)){
    Toast.makeText(ActivityClass.this,"No internet connection", Toast.LENGTH_SHORT).show();

Edit Answer

To create a layout to show when doesn't have internet you can do:

One way, is create a layout and set visible or invisible. Other way is Inflate a new Layout.

Here I'll show to you how to create a layout and make visible or invisible.

First of all, create your basic layout to show when doesn't have internet:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/no_internet_connection"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="gone"> 

    <TextView
        android:id="@+id/no_internet_connection_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center_horizontal"
        android:text="Error: No internet connection!"
        android:textSize="25sp"/>
</RelativeLayout>

note android:visibility="gone" set your layout invisible and it doesn't fill any space in your main layout.

Now include in your main activity <include layout="@layout/name_of_your_activity"/>

Create two methods in a class that you can access easily(I recommend to put together with your checkAppConnectionStatus(Context context)

    public static void setLayoutInvisible(View viewName) {
        if (viewName.getVisibility() == View.VISIBLE) {
            viewName.setVisibility(View.GONE);
        }
    }
    public static void setLayoutVisible(View viewName) {
        if (viewName.getVisibility() == View.GONE ) {
            viewName.setVisibility(View.VISIBLE);
        }
    }

So now just work with these methods in your main activiy, like:

private View mNoInternetConnection;
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);
            // Get layout that you had included in you main_activiy.xml
            mNoInternetConnection = findViewById(R.id.no_internet_connection);
    .
    .
    .
    .
    ..
    ...
    ....
    // Check the internet connect
       if (!Utils.checkAppConnectionStatus(ActivityClass.this)){
            // If do not have internet connection, set layout visible
            Utils.setLayoutVisible(mNoInternetConnection);
       }else{
            // If have internet connection, set layout invisible
            Utils.setLayoutInvisible(mNoInternetConnection);
Community
  • 1
  • 1
Adley
  • 511
  • 1
  • 6
  • 19
  • can u plz tell me where to implement this in my code – Rohith Apr 29 '16 at 11:28
  • Anywhere, you can put in your activity or create a utils class. so you call passing parameters. – Adley Apr 29 '16 at 11:33
  • Thanx for the help – Rohith Apr 29 '16 at 11:36
  • You are welcome. If you still have some doubt, just ask. – Adley Apr 29 '16 at 11:39
  • Ok. I suggest you to write in a utils file, because if you need check in other acitivty, you just need call the method again. Also you can customize your View depending the recived result. To add some message or add a popout or just do what you want. – Adley Apr 29 '16 at 11:43
  • @adely i have callled it in main activity.java but what should i use instead of activityclass – Rohith Apr 30 '16 at 09:10
  • You tag my name wrong hahaha. Well The checkAppConnectionStatus method needs a Context to verify if was connected or not. In your case, you need to pass MainActivity context. To do so, you need to pass nameYourClasse.this, like MainActivity.this – Adley Apr 30 '16 at 18:38
  • sorry for that , and i would like to replace toast and pt some error message using activity – Rohith May 01 '16 at 04:50
  • You can put any code instead Toast, it's just an example. But you still need to pass the context, so with context the method checkAppConnectionStatus() can validate status – Adley May 01 '16 at 06:19
  • can u post me how to call the a error activity page instead of toast plz – Rohith May 01 '16 at 10:28
  • First, create a layout or a view to show( you called as Activity error page) and set visibility="gone" http://pastie.org/10820481 – Adley May 02 '16 at 00:57
  • Include in your mainActivity xml, like – Adley May 02 '16 at 00:58