Verify Internet App Android Studio

2

I need my application to check if there is internet and if there is not show a set.text saying that there is not.

I think it has something to do with this class:

public class HTTPDataHandler {
static String stream = null;

public HTTPDataHandler() {


}

public String GetHTTPData(String urlString) {
    try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader r = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null)
                sb.append(line);
            stream = sb.toString();
            urlConnection.disconnect();
        }


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
        return stream;

}

}

MAIN CLASS

    public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    RecyclerView recyclerView;
    RssObject rssObject;

    // Posem el link que volem.

    private final String RSS_link="http://estaticos.marca.com/rss/portada.xml";
    private final String RSS_to_Json_API = "https://api.rss2json.com/v1/api.json?rss_url=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//Crreguem activity main, desorés la barra toolbar
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle("EAC2-2017S1");
        setSupportActionBar(toolbar);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);

        loadRss();  // Carreguem la clase loadRSS
    }

    //Utilitzem AsyncTask per carregar dades i convertirles
    private void loadRss() {

        AsyncTask<String,String,String> loadRSSAsync = new AsyncTask<String, String, String>() {
           // SpotsDialog mDialog = new SpotsDialog(MainActivity.this);
// No he trobat forma que SpotsDialog em funciones.. :( Així que he optat per mDialog.
           ProgressDialog mDialog = new ProgressDialog(MainActivity.this);

            // He possat el mDialog encara que sé que està decapated.
            @Override
            protected void onPreExecute() {
                mDialog.setMessage("Un moment siusplau..."); // He fet un missatje cuan carregui la app.
                mDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
            String result;
                HTTPDataHandler http = new HTTPDataHandler();
                result = http.GetHTTPData(params[0]);
                return result;

            }

            @Override
            protected void onPostExecute(String s) {
                mDialog.dismiss();
                rssObject = new Gson().fromJson(s,RssObject.class);
                FeedAdapter adapter = new FeedAdapter(rssObject,getBaseContext());
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }
        };

        StringBuilder url_get_data = new StringBuilder(RSS_to_Json_API);
        url_get_data.append(RSS_link);
        loadRSSAsync.execute(url_get_data.toString());

    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu){
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if (item.getItemId() ==R.id.menu_refresh)
            loadRss(); // ACTUALITZEM RSS
        return true;
    }

}

But the truth is that I have no idea how to do it .. I'm super lost .. if you can help me: (

thanks

    
asked by Montse Mkd 24.10.2017 в 18:04
source

1 answer

2

Using the following method you can determine if there is an internet connection and evaluate if you try to download the data or just show a message indicating that you do not have internet:

private static ConnectivityManager manager;

public static boolean isOnline(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}

The implementation would be done within your onCreate (),

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//Crreguem activity main, desorés la barra toolbar
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle("EAC2-2017S1");
        setSupportActionBar(toolbar);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);


        if (isOnline(getApplicationContext())) { 
             loadRss();   //Si hay conexión descarga datos!
        } else {
           Toast.makeText(getApplicationContext(),"NO hay conexión!",Toast.LENGTH_SHORT).show(); 
        }


    }

Do not forget to define the permissions:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
    
answered by 24.10.2017 / 18:46
source