0

I am trying to stop an app crash if a network call is not available.

If the network call is available then I want to button click to continue into the next Activity. The catch should display a toast.

However the app is still crashing instead of displaying the toast

Here is my code:-

public void GoToStation(View v)
{

        try {

            Intent myIntent = new Intent(
                             MainActivity.this, CustomizedListViewStation.class);
            startActivityForResult(myIntent, 0);
        } catch (Exception myIntent) {
            // TODO Auto-generated catch block
            Context context = getApplicationContext();
            CharSequence text = "There is no data for this Community";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

LOGCAT:-

08-01 12:36:56.944: E/AndroidRuntime(32556): FATAL EXCEPTION: main
08-01 12:36:56.944: E/AndroidRuntime(32556): java.lang.RuntimeException: Unable to start     activity     ComponentInfo{police.uk.greatermanchesterpoliceandroid/police.uk.greatermanchesterpoliceandroid.CustomizedListViewStation}: android.os.NetworkOnMainThreadException
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.os.Looper.loop(Looper.java:137)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.main(ActivityThread.java:4898)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.lang.reflect.Method.invokeNative(Native Method)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.lang.reflect.Method.invoke(Method.java:511)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at dalvik.system.NativeStart.main(Native Method)
08-01 12:36:56.944: E/AndroidRuntime(32556): Caused by: android.os.NetworkOnMainThreadException
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at police.uk.greatermanchesterpoliceandroid.XMLParser.getXmlFromUrl(XMLParser.java:45)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at police.uk.greatermanchesterpoliceandroid.CustomizedListViewStation.onCreate(CustomizedListViewStation.java:108)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.Activity.performCreate(Activity.java:5206)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
08-01 12:36:56.944: E/AndroidRuntime(32556):    ... 11 more
08-01 12:37:05.694: I/Process(32556): Sending signal. PID: 32556 SIG: 9

3 Answers3

1

instead of it check the internet connection first. Remove try-catch block and call isOnline function in if code -> if(isOnline()){} :

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

replace your try-catch with this:

if (isOnline()){
    Intent myIntent = new Intent(MainActivity.this, CustomizedListViewStation.class);
    startActivityForResult(myIntent, 0);
} 

else {            
    Context context = getApplicationContext();
    CharSequence text = "There is no data for this Community";
    int duration = Toast.LENGTH_LONG;
    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}
canova
  • 3,965
  • 2
  • 22
  • 39
1

Use this if you are 200% sure that you need to have your networking activity in the main thread, use:

if (android.os.Build.VERSION.SDK_INT > 9) {
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
}

Otherwise, have a look at Threads and AsyncTasks.

FD_
  • 12,947
  • 4
  • 35
  • 62
  • FD_ That looks like what I need. Where would this be placed? – Rob Birkett Aug 01 '13 at 12:08
  • In the onCreate of your Activity. But, please note that this is bad practice and you should consider moving your networking code into a background thread in the long run. – FD_ Aug 01 '13 at 12:55
  • Would this possibly affect my app being approved in the Play Store? – Rob Birkett Aug 01 '13 at 13:55
  • There is no Play Store review team as there is for Apple's App Store. They really don't bother about your used techniques etc – FD_ Aug 01 '13 at 13:57
  • Although this would fix your problem, it is a really bad idea. It would be very likely that your users would receive app not responding (ANR) messages which would result in them force closing the app and likely receive negative comments in the play store. Although doing this wouldn't result in the app being pulled from the play store, but Google will never promote your app as they expect apps to be developed according to the development guidelines – Boardy Aug 01 '13 at 16:18
0

Its because you are running the code on the main thread so it is throwing a NetworkOnMainThreadException. This isn't in your code so you can't catch it, nor should you attempt to catch it because your app will never work because it will never attempt to make a network connection due to this error.

You need to perform your network activity in a separate thread such as an ASyncTask and this exception will no longer be thrown.

The reason for this exception is network activity usually causes a delay in the app as network calls tend to block until they are complete. If network activity is performed on the main thread the users of your app will likely then receive an ANR (Application Not Responding) message which will mean the user can force close your app as it looks as if your app is no longer responding to anything as in the background it is doing the network activity.

Boardy
  • 35,417
  • 104
  • 256
  • 447