Reputation: 593
I want to show a layout like google playstore when no internet is available it shows No Internet. I have created a layout for this and I used the code to check network
private boolean isNetworkAvailable(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
and I used
if (isNetworkAvailable()){
}else {
setContentView(R.layout.no_internet);
}
to show the layout. But I get an error saying
Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.addDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
How can I show the layout?
Here is my main activity code
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;
}
Upvotes: 0
Views: 847
Reputation: 12678
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>
Upvotes: 0
Reputation: 77
you can use :
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;
}
and
if(!testConnection()){
setContentView();
}
else{
//or another contentview
setContentView();
}
Upvotes: 0
Reputation:
Try this code.. add below permission into android manifest file..
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
after make this method..
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;
}
after that make this things..
try {
if (isNetConnected()){
setContentView();
}
else{
setContentView();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
Upvotes: 1
Reputation: 91
You can use Custom Dialog of full Screen to check for internet. So, you can write,
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
}
Upvotes: 0