-2

i designed an app that checks for internet connection before making http requests and it works fine, but the problem is that when there is an internet connection and i switch of mobile data or forcefully lose internet connection within that period its searching for data, the app crashes. is there a way i can make the app report no internet connection if internet connection is lost whilst fetching the data, i checked and tried to use Broadcast receivers but in the android manifest where we are to declare intent filters,i couldn't find these i am also using loaders instead of async tasks to do the network requests in other words

i just need a way to handle Response validation

The app checks whether the device is connected to the internet and responds appropriately. The result of the request is validated to account for a bad server response or lack of server response maybe due to loss of internet connection during fetching the data

enter code here   

// this is the code to fetch the data

public class Fesh {

public static ArrayList<word> fesh (){


    // Create an empty ArrayList that we can start adding earthquakes to
    ArrayList<word> words = new ArrayList<>();

    // Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
    // is formatted, a JSONException exception object will be thrown.
    // Catch the exception so the app doesn't crash, and print the error message to the logs.

    final String RESPONSE = feshjson();
    try {

        // TODO: Parse the response given by the SAMPLE_JSON_RESPONSE string and
        // build up a list of Earthquake objects with the corresponding data.

        JSONObject rootobject = new JSONObject(RESPONSE);

        JSONArray rootarray = rootobject.getJSONArray("features");
        for(int i = 0;i<rootarray.length();i++){

            JSONObject current = rootarray.getJSONObject(i);
            JSONObject properties = current.getJSONObject("properties");
            double magnitude = properties.getDouble("mag");
            String place = properties.getString("place");
            long date = properties.getLong("time");
            String url = properties.getString("url");

            word earthquake = new word(magnitude,place,date,url);
            words.add(earthquake);

        }



    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
    }

    // Return the list of earthquakes
    // getword(words);
    return words;


}




public static String feshjson(){

    HttpURLConnection connection = null;
    InputStream stream = null;
    BufferedReader reader = null;

    try {
        URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2012-12-01&minmagnitude=6");
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        String line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return  buffer.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        new MainActivity().Nonetwork();
    }
    catch (ConnectException ex)
    {
        ex.printStackTrace();
         new MainActivity().Nonetwork();
    }

    catch (SocketException ex)
    {
        ex.printStackTrace();
        new MainActivity().Nonetwork();
    }
    catch (SocketTimeoutException ex)
    {
        ex.printStackTrace();
        new MainActivity().Nonetwork();
    }
    catch(NullPointerException ex)
    {
        ex.printStackTrace();
        new MainActivity().Nonetwork();
    }
    catch (Exception e)
    {

        e.printStackTrace();

        new MainActivity().Nonetwork();
    }

     finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            new MainActivity().Nonetwork();
        }
    }
    return null;



}

}

//this is the method to display no network 
public void Nonetwork(){
TextView text = (TextView) findViewById(R.id.texto);
text.setText("no internet");
text.setVisibility(View.VISIBLE);

}``

//this is what my Log looks like
05-25 23:50:46.029 22283-22308/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                               Process: com.example.android.myquake, PID: 22283
                                               java.lang.RuntimeException: An error occured while executing doInBackground()
                                                   at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                   at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                   at java.lang.Thread.run(Thread.java:818)
                                                Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                                                   at android.os.Handler.<init>(Handler.java:200)
                                                   at android.os.Handler.<init>(Handler.java:114)
                                                   at android.app.Activity.<init>(Activity.java:793)
                                                   at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:34)
                                                   at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
                                                   at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:29)
                                                   at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:77)
                                                   at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:64)
                                                   at com.example.android.myquake.MainActivity.<init>(MainActivity.java:0)
                                                   at com.example.android.myquake.Fesh.feshjson(Fesh.java:129)
                                                   at com.example.android.myquake.Fesh.fesh(Fesh.java:39)
                                                   at com.example.android.myquake.Arrayloader.loadInBackground(Arrayloader.java:28)
                                                   at com.example.android.myquake.Arrayloader.loadInBackground(Arrayloader.java:18)
                                                   at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                   at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                   at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:57)
                                                   at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                   at java.lang.Thread.run(Thread.java:818) 
awesome_cos
  • 15
  • 1
  • 5

1 Answers1

0

You can declare the action for the broadcast as:

   <receiver android:name=".Receiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

inside the broadcast receiver whose onReceive will be called wheneverthe connection changes.

Based on the change you can either show the error or continue fetching the data.

Anmol
  • 448
  • 2
  • 6