I just created an android app for fetching data from a website. I want to check if the device has an internet connection or not. If the device has internet connection, run my code and fetch the data and display it, otherwise if the device has no internet, then display the no internet connection message. I have tried this code to check the internet connection. How can I call the code when there is an internet connection?
My Java code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
new FetchWebsiteData().execute();
}
});
}
private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
ProgressDialog progress;
private Context context;
//check Internet connection.
private void checkInternetConnection(){
ConnectivityManager check = (ConnectivityManager) this.context.
getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null)
{
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i <info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
Toast.makeText(context, "Internet is connected",
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(context, "not conencted to internet",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//some code here
}
@Override
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
//some code
}
//parsing first URL
String [] resultArray=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
//parsing second URL
String [] resultArray1=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
try{
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
ListView list=(ListView)findViewById(R.id.listShow);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
list.setAdapter(arrayAdapter);
mProgressDialog.dismiss();
}
}
}
How can I run the code when the connection is open and how to display message when app has no internet connection?