user user - 1 day ago 3
Android Question

How to check internet connection in Fragement Tabs

I am developing an app in which i want to check if internet connection is there then it will execute the task otherwise it will show error message like no internet connection is there.In this application i am using 2 tabs. I wrote one code for checking internet connection,but every time when no connection is there my app crashes.

Code for Main Activity:

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 code:

@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)

Answer

Create new class Application_utlity (according to u) and put this code in your class like that

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;
}}

if u want to check your internet connection in fragment then use method check connection in fragment like :

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

if(!checkConnection) {

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

}

else{

// your code here

}

Comments