如何检查Fragement选项卡中的Internet连接

时间:2016-12-01 10:04:38

标签: android android-recyclerview

我正在开发一个应用程序,其中我想检查互联网连接是否存在然后它将执行任务否则它将显示错误消息,如没有互联网连接那里。在这个应用程序中我使用2个选项卡。我写了一个用于检查互联网连接的代码,但每当没有连接时我的应用程序崩溃。

主要活动代码:

     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    if (!isNetworkAvailable()) {
        Toast.makeText(getApplicationContext(),
                "Internet Connection is Not Available", Toast.LENGTH_LONG).show();
        finish();
    } else {


        if (getIntent().getExtras() != null) {

            for (String key : getIntent().getExtras().keySet()) {
                String value = getIntent().getExtras().getString(key);

                if (key.equals("Tab_Notification") && value.equals("True")) {
                    Intent intent = new Intent(this, Tab_Notification.class);
                    intent.putExtra("value", value);
                    startActivity(intent);
                    finish();
                }

            }
        }

        subscribeToPushService();



   final Handler mHandler = new Handler();


   final Runnable mUpdateResults = new Runnable() {
            public void run() {

                AnimateandSlideShow();

            }
        };

        int delay = 1000; // delay for 1 sec.

        int period = 15000; // repeat every 4 sec.

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {

                mHandler.post(mUpdateResults);

            }

        }, delay, period);


        SharedPreferences sharedpreferences = getSharedPreferences(SignIn.MyPREFERENCES, Context.MODE_PRIVATE);

      final String e = sharedpreferences.getString(SignIn.email, "");

        toolbar = (Toolbar) findViewById(R.id.toolbar1);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout1);

        viewPager = (ViewPager) findViewById(R.id.pager1);
        i = (ImageView) findViewById(R.id.pinButton);
        i.setOnClickListener(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        tabLayout.addTab(tabLayout.newTab().setText("Super Market"));
        tabLayout.addTab(tabLayout.newTab().setText("Shopping"));
        tabLayout.addTab(tabLayout.newTab().setText("FOOD"));
        tabLayout.addTab(tabLayout.newTab().setText("Cosmetics"));
        tabLayout.addTab(tabLayout.newTab().setText("Medical"));
        tabLayout.addTab(tabLayout.newTab().setText("Hotels"));
        tabLayout.addTab(tabLayout.newTab().setText("Jewellery"));

        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        fragmentAdapter = new FragmentAdapterClass(getSupportFragmentManager(), tabLayout.getTabCount());

        viewPager.setAdapter(fragmentAdapter);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab LayoutTab) {

                viewPager.setCurrentItem(LayoutTab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab LayoutTab) {

            }


            @Override
            public void onTabReselected(TabLayout.Tab LayoutTab) {

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

Tab1代码:

   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.activity_tab_1, container, false);
    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(getActivity());

    recyclerView.setLayoutManager(layoutManager);
    mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swifeRefresh);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {


                getData();

                upcomingJobs.clear();
                upcomingJobs.addAll(upcomingJobs);
                // fire the event
                adapter.notifyDataSetChanged();


                // uAdapter.notifyDataSetChanged();
            }


    });
    //Make call to AsyncTask
    getData();

    return v;
}


private void getData() {
    class GetData extends AsyncTask<Void, Void, String> {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            // progressDialog = ProgressDialog.show(getContext(), "Fetching Data", "Please wait...",false,false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            // progressDialog.dismiss();
            parseJSON(s);


            mSwipeRefreshLayout.setRefreshing(false);
        }

        @Override
        protected String doInBackground(Void... params) {



            BufferedReader bufferedReader = null;
            try {
                URL url = new URL(Config.GET_URL);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();

                bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }

                return sb.toString().trim();

            } catch (Exception e) {
                return null;
            }
        }


    }
    GetData gd = new GetData();
    gd.execute();
}

public void showData() {
    adapter = new CardAdapter(Config.offer, Config.offerprice, Config.bitmaps, Config.price, Config.urls);

    recyclerView.setAdapter(adapter);
    recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Toast.makeText(getContext(), "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
        }
    }));
}


private void parseJSON(String json) {
    try {
        JSONObject jsonObject = new JSONObject(json);
        JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);

        config = new Config(array.length());

        for (int i = 0; i < array.length(); i++) {
            JSONObject j = array.getJSONObject(i);
            Config.offer[i] = getoffer(j);
            Config.urls[i] = geturl(j);
            Config.offerprice[i] = getofferprice(j);
            Config.price[i] = getprice(j);
            Config.urls[i] = geturl(j);

        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    GetBitmap gb = new GetBitmap(getContext(), this, Config.urls);
    gb.execute();
}

private String getoffer(JSONObject j) {
    String name = null;
    try {
        name = j.getString(Config.TAG_Offer);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return name;
}

private String getofferprice(JSONObject j) {
    String name = null;
    try {
        name = j.getString(Config.TAG_Offerprice);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return name;
}

private String getprice(JSONObject j) {
    String name = null;
    try {
        name = j.getString(Config.TAG_price);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return name;
}


private String geturl(JSONObject j) {
    String url = null;
    try {
        url = j.getString(Config.TAG_IMAGE_URL);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return url;
}

logcat的:

FATAL EXCEPTION: main
                                                                   java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                                    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                                    at org.json.JSONObject.<init>(JSONObject.java:156)
                                                                    at org.json.JSONObject.<init>(JSONObject.java:173)
                                                                    at com.zaps.myrewards.Tab_1_Activity.parseJSON(Tab_1_Activity.java:144)
                                                                    at com.zaps.myrewards.Tab_1_Activity.access$300(Tab_1_Activity.java:31)
                                                                    at com.zaps.myrewards.Tab_1_Activity$1GetData.onPostExecute(Tab_1_Activity.java:92)
                                                                    at com.zaps.myrewards.Tab_1_Activity$1GetData.onPostExecute(Tab_1_Activity.java:78)
                                                                    at android.os.AsyncTask.finish(AsyncTask.java:632)
                                                                    at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                                    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:145)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

2 个答案:

答案 0 :(得分:0)

创建新类Application_utlity(根据你)并将此代码放在你的类中

public class Application_utility {

ConnectivityManager connectivityManager;
NetworkInfo info;

public boolean checkConnection(Context context) {
    boolean flag = false;
    try {

        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        info = connectivityManager.getActiveNetworkInfo();

        if (info.getType() == ConnectivityManager.TYPE_WIFI) {

            System.out.println(info.getTypeName());
            flag = true;
        }

        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            System.out.println(info.getTypeName());
            flag = true;
        }

    } catch (Exception exception) {

        System.out.println("Exception at network connection....."
                + exception);
    }

   return flag;
}}

如果你想在片段中检查你的互联网连接,那么在片段中使用方法检查连接:

final boolean checkConnection=new Application_utility().checkConnection(getActivity());

if(!checkConnection)
{

   Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_LONG).show();

}

else{

// your code here

}

答案 1 :(得分:0)

通过传递片段上下文或父活动来尝试此操作。

 /**
 * Check Connection
 *
 * @param ctx
 * @return
 */
public static boolean isConnectedToInternet(Context ctx) {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
    return ni != null && ni.isAvailable() && ni.isConnected();
}