当用户未连接到互联网时如何显示自定义错误布局?

时间:2018-06-28 05:59:08

标签: android android-layout android-studio

我想在没有互联网可用时显示类似Google Playstore的布局,它显示没有互联网。我为此创建了一个布局,并使用代码检查了网络

private boolean isNetworkAvailable(){
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

我用过

 if (isNetworkAvailable()){

    }else {
        setContentView(R.layout.no_internet);
    }

显示布局。但我说

时出错
  

试图在空对象引用上调用虚拟方法'void android.support.v4.widget.DrawerLayout.addDrawerListener(android.support.v4.widget.DrawerLayout $ DrawerListener)'

如何显示布局?

这是我的主要活动代码

public class MainActivity extends BaseActivity
    implements UpdateHelper.OnUpdateCheckListener, NavigationView.OnNavigationItemSelectedListener {

private CircleImageView mDisplayImageView;
private TextView mNameTextView;
private TextView mEmailTextView;


String token = "";
List<Item> items = new ArrayList<>();
WebView webView;
PostAdapter adapter;
SpinKitView progress;
RecyclerView recyclerView;
LinearLayoutManager manager;
Boolean isScrolling = false;
int currentItems, totalItems, scrollOutItems;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    recyclerView = (RecyclerView) findViewById(R.id.postList);
    manager = new LinearLayoutManager(this);
    adapter = new PostAdapter(this, items);
    recyclerView.setLayoutManager(manager);
    recyclerView.setAdapter(adapter);
    progress = (SpinKitView) findViewById(R.id.spin_kit);

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL)
            {
                isScrolling = true;
            }
        }
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            currentItems = manager.getChildCount();
            totalItems = manager.getItemCount();
            scrollOutItems = manager.findFirstVisibleItemPosition();

            if(isScrolling && (currentItems + scrollOutItems == totalItems))
            {
                isScrolling = false;
                getData();
            }
        }
    });
    getData();


    if (isNetworkAvailable()){

    }else {
        setContentView(R.layout.no_internet);
    }


    if (isFirstTime()) {
        new MaterialStyledDialog.Builder(MainActivity.this)
                .setTitle("Psst!")
                .setDescription(R.string.alerttext)
                .setIcon(R.drawable.hello)
                .withIconAnimation(true)
                .withDialogAnimation(true)
                .setHeaderColor(R.color.white)
                .setPositiveText("Ok!")
                .show();
    }




    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.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setItemIconTintList(null);
    navigationView.setNavigationItemSelectedListener(this);

    UpdateHelper.with(this)
            .onUpdateCheck(this)
            .check();




    View navHeaderView = navigationView.getHeaderView(0);
    mDisplayImageView = (CircleImageView) navHeaderView.findViewById(R.id.imageView_display);
    mNameTextView = (TextView) navHeaderView.findViewById(R.id.textView_name);
    mEmailTextView = (TextView) navHeaderView.findViewById(R.id.textView_email);
    mEmailTextView.setText(R.string.verified);
    loadUserInfo();
    if (mFirebaseUser == null) {
        String email = mFirebaseUser.getEmail();
        FirebaseDatabase.getInstance().getReference(Constants.USER_KEY).child(mFirebaseUser.getEmail().replace(".", ","))
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
    }



}

private void getData()
{
    String url = BloggerAPI.url + "?key=" + BloggerAPI.key;
    if(token != ""){
        url = url+ "&pageToken="+ token;
    }
    if(token == null){
        return;
    }
    progress.setVisibility(View.VISIBLE);
    final Call<PostList> postList = BloggerAPI.getService().getPostList(url);
    postList.enqueue(new Callback<PostList>() {
        @Override
        public void onResponse(Call<PostList> call, Response<PostList> response) {
            PostList list = response.body();
            token = list.getNextPageToken();
            items.addAll(list.getItems());
            adapter.notifyDataSetChanged();
            Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
            progress.setVisibility(View.GONE);
        }

        @Override
        public void onFailure(Call<PostList> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
        }
    });
}

private void loadUserInfo()
{
    FirebaseUser user = mAuth.getCurrentUser();
    if (user != null) {
        if (user.getPhotoUrl() != null) {
            Glide.with(this)
                    .load(user.getPhotoUrl().toString())
                    .into(mDisplayImageView);
        }
        if (user.getDisplayName() != null) {
            mNameTextView.setText(user.getDisplayName());
        }
        if (user.getEmail() != null) {
            mEmailTextView.setText(user.getEmail());
        }
    }

}


private boolean isNetworkAvailable(){
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
        AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
        mBuilder.setCancelable(false);
        mBuilder.setTitle("Are you sure you want to exit?");
        mBuilder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mBuilder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finishAffinity();
                System.exit(0);
            }
        });

        AlertDialog alertDialog = mBuilder.create();
        alertDialog.show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        FirebaseAuth.getInstance().signOut();
        Intent logout = new Intent(MainActivity.this, WelcomeActivity.class);
        startActivity(logout);
        finish();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.about) {

        Intent intent = new Intent(MainActivity.this, AboutActivity.class);
        startActivity(intent);





        // Handle the camera action
    } else if (id == R.id.bookstore) {
        startActivity(new Intent(this, BooksActivity.class));

    }else if (id == R.id.feedback) {
        new EasyFeedback.Builder(this)
                .withEmail(R.string.emailid)
                .withSystemInfo()
                .build()
                .start();


    } 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
private boolean isFirstTime() {
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    boolean ranBefore = preferences.getBoolean("RanBefore", false);
    if (!ranBefore) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("RanBefore", true);
        editor.commit();
    }
    return !ranBefore;
}

4 个答案:

答案 0 :(得分:1)

您可以使用全屏的“自定义对话框”检查互联网。 所以,你可以写,

    if(isNetworkAvailable()){
            //Your Logic for Internet Connection
     }else {
        val noInternetDialog = Dialog(this, android.R.style.Theme)
        noInternetDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        noInternetDialog.setContentView(R.layout.no_internet_layout)
        val window = noInternetDialog.window
        window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        // What ever you have widget, can use them here.
        //for example
        val button_try_again = noInternetDialog.findViewById(R.id.buttonId)
        // listeners for Button

        noInternetDialog.show
     }

答案 1 :(得分:1)

尝试此代码。 将以下权限添加到android清单文件中。.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>

完成此方法后。

 public boolean isNetConnected() throws Throwable {
    boolean netConnected = false;
    ConnectivityManager connectivity = (ConnectivityManager)getSystemService("connectivity");
    if (connectivity == null) {
        netConnected = false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for(int i = 0; i < info.length; ++i) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    netConnected = true;
                }
            }
        }
    }
    return netConnected;
}

在那之后做这件事。

        try {
        if (isNetConnected()){
            setContentView();
        }
        else{
            setContentView();

        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }

答案 2 :(得分:0)

您可以使用:

public boolean testConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

            if(!testConnection()){


            setContentView();

            }
            else{
            //or another contentview 
            setContentView();

            }

答案 3 :(得分:0)

 call **isNetworkAvailable()** if Network not Available then **SHOW** ErrorView Otherwise **HIDE** ErrorView.


  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/r`enter code here`es-auto"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@drawable/app_gradient_square"
            android:orientation="horizontal"
            android:padding="@dimen/dim_5">

            <ImageView
                android:id="@+id/btnCancel"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_centerVertical="true"
                android:padding="@dimen/dim_5"
                ads:srcCompat="@drawable/ic_editor_back_white" />

            <TextView
                android:id="@+id/txtAppTitle"
                android:layout_width="wrap_content"
                android:layout_height="@dimen/img_btn_height"
                android:layout_centerInParent="true"
                android:gravity="center"
                android:text="@string/screen_sticker"
                android:textColor="@color/color_app_font_secondary"
                android:textSize="@dimen/font_size_large"
                android:visibility="visible" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.design.widget.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/app_gradient_square"
                app:tabBackground="@drawable/tab_bg_selector_transperant_2"
                app:tabGravity="fill"
                app:tabIndicatorColor="@color/color_trans"
                app:tabMode="scrollable"
                app:tabSelectedTextColor="@color/selectedTabTextColor"
                app:tabTextAppearance="@style/TAB_TextAppearance_Regular"
                app:tabTextColor="@color/defaultTabTextColor" />
            <!-- app:tabBackground="@drawable/tab_bg_selector_transperant"-->

            <View
                android:id="@+id/toolbar_shadow"
                android:layout_width="match_parent"
                android:layout_height="3dp"
                android:layout_below="@+id/tabLayout"
                android:background="@drawable/toolbar_dropshadow" />

            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/adView"
                android:layout_below="@+id/toolbar_shadow" />

            <RelativeLayout
                android:id="@+id/emptyView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="gone">

                <include layout="@layout/include_empty_list_view" />

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/errorView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="gone">

                <include layout="@layout/include_error_list_view" />

            </RelativeLayout>

        </RelativeLayout>

    </LinearLayout>