0

I'm trying to access my application without internet and I want the application to inform that there is no connection instead of closing alone giving an error. When my internet is disabled, I cannot access the application. It simply closes by itself returning the error:

    D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.myapp.test, PID: 20245
    java.lang.NullPointerException
        at java.util.Objects.requireNonNull(Objects.java:203)
        at java.util.Arrays$ArrayList.<init>(Arrays.java:3741)
        at java.util.Arrays.asList(Arrays.java:3728)
        at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:164)
        at com.myapp.test.utils.adapters.CustomGridView.<init>(CustomGridView.java:35)
        at com.myapp.test.fragment.FragmentHome.onCreateView(FragmentHome.java:193)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1392)
        at android.app.Activity.performStart(Activity.java:7260)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3009)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1840)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6872)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
E/MQSEventManagerDelegate: failed to get MQSService.

As I understand it, I need to return a null value, but I can't implement it in my code. Can someone help me?

Here is the code for my GridView:

    package com.myapp.test.utils.adapters;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.myapp.test.R;
import com.myapp.test.utils.image.RoundedSquareImageView;
import com.myapp.test.utils.text.DinTextView;

import java.io.InputStream;

/**
 * Created by jaiso on 13-02-2018.
 */

public class CustomGridView extends ArrayAdapter<String>{

    private String[] profilename;
    private String[] imagepath;
    private String[] ImgUserStatus;
    private Activity context;
    Bitmap bitmap;

    public CustomGridView(Activity context, String[] profilename, String[] imagepath, String[] ImgUserStatus) {
        super(context, R.layout.item_home_grid_users,profilename);
        this.context=context;
        this.profilename=profilename;
        this.imagepath=imagepath;
        this.ImgUserStatus=ImgUserStatus;

    }

    @NonNull
    @Override

    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent){
        View r=convertView;
        ViewHolder viewHolder=null;
        if(r==null){
            LayoutInflater layoutInflater=context.getLayoutInflater();
            r=layoutInflater.inflate(R.layout.item_home_grid_users,null,true);
            viewHolder=new ViewHolder(r);
            r.setTag(viewHolder);
        }
        else {
            viewHolder=(ViewHolder)r.getTag();

        }

        viewHolder.tvw1.setText(profilename[position]);
        new GetImageFromURL(viewHolder.ivw).execute(imagepath[position]);
        new GetImageFromURLStatus(viewHolder.ImgStatusOnlineOffline).execute(ImgUserStatus[position]);
        return r;
    }

    class ViewHolder{

        DinTextView tvw1;
        RoundedSquareImageView ivw;
        ImageView ImgStatusOnlineOffline;
        LinearLayout LinearFavIconHidden;

        ViewHolder(View v){
            tvw1=(DinTextView)v.findViewById(R.id.fragm_feed_txt_name);
            ivw=(RoundedSquareImageView)v.findViewById(R.id.fragm_feed_profile_image);
            ImgStatusOnlineOffline=(ImageView)v.findViewById(R.id.fragm_home_user_img_status_online_offline);
        }

    }

    public class GetImageFromURL extends AsyncTask<String,Void,Bitmap>
    {
        RoundedSquareImageView imgView;
        public GetImageFromURL(RoundedSquareImageView imgv)
        {
            this.imgView=imgv;
        }
        @Override
        protected Bitmap doInBackground(String... url) {
            String urldisplay=url[0];
            bitmap=null;

            try{

                InputStream ist=new java.net.URL(urldisplay).openStream();
                bitmap= BitmapFactory.decodeStream(ist);
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap){

            super.onPostExecute(bitmap);
            imgView.setImageBitmap(bitmap);
        }
    }

    public class GetImageFromURLStatus extends AsyncTask<String,Void,Bitmap>
    {
        ImageView imgViewStatus;
        public GetImageFromURLStatus(ImageView imgvStatus)
        {
            this.imgViewStatus=imgvStatus;
        }
        @Override
        protected Bitmap doInBackground(String... url) {
            String urldisplay=url[0];
            bitmap=null;

            try{

                InputStream ist=new java.net.URL(urldisplay).openStream();
                bitmap= BitmapFactory.decodeStream(ist);
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap){

            super.onPostExecute(bitmap);
            imgViewStatus.setImageBitmap(bitmap);
        }
    }
}
Teemu
  • 22,918
  • 7
  • 53
  • 106
  • Now your code works if there is no internet, but you need to stop this exception and make the app work without a crash is this right? – Zain Apr 20 '20 at 18:33
  • @Zain Yes, I need the app to work when opened without an internet connection :) – Micahel Keller Apr 20 '20 at 20:10

1 Answers1

0

Now, your app works whenever the device is connected to the internet, but it crashes when the internet is not available.

So, you want to check if you're connected to the internet, and if not, then you want to prevent any code that tries to parse any URL.

In order to check whether your device is connected to the internet or not use the below method which return true if your device is connected to the internet.

public boolean isOnline(Context context) {

    boolean isConnected = false;
    ConnectivityManager   mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
        // Checking internet connectivity
        NetworkInfo activeNetwork = null;
        if (mConnectivityMgr != null) {
            activeNetwork = mConnectivityMgr.getActiveNetworkInfo(); // Deprecated in API 29
        }
        isConnected = activeNetwork != null;

    } else {
        Network[] allNetworks = mConnectivityMgr.getAllNetworks(); // added in API 21 (Lollipop)

        for (Network network : allNetworks) {
            NetworkCapabilities networkCapabilities = mConnectivityMgr.getNetworkCapabilities(network);
            if (networkCapabilities != null) {
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
                        || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
                        || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
                    isConnected = true;
            }
        }
    }

    return isConnected;

}

Add isOnline() method in your custom adapter class which is called CustomGridView.

In your code you tries to access the internet in your adapter, specifically within getView() method using the your custom AsyncTask class. So change this method to check if your are online or not.

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View r = convertView;
        ViewHolder viewHolder = null;
        if (r == null) {
            LayoutInflater layoutInflater = context.getLayoutInflater();
            r = layoutInflater.inflate(R.layout.item_home_grid_users, null, true);
            viewHolder = new ViewHolder(r);
            r.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) r.getTag();

        }

        viewHolder.tvw1.setText(profilename[position]);

        if (isOnline(parent.getContext())) {
            new GetImageFromURL(viewHolder.ivw).execute(imagepath[position]);
            new GetImageFromURLStatus(viewHolder.ImgStatusOnlineOffline).execute(ImgUserStatus[position]);
        }

        return r;
    }

check this answer if you want to do more about internet functionality.

Zain
  • 37,492
  • 7
  • 60
  • 84
  • I implemented this code in mine, but whenever I turn off the Internet and start the application, it remains closed on its own. – Micahel Keller Apr 23 '20 at 09:49