Android Short Codes

Android Handling App Crash

android app crash uncaugh execption
Written by Yasir Ameen

App crashing is very wrost thing. It is always frustating when we launch app and its crash. There are number of ways availble online you can use to handle it, but i will describe you very easy way to handle the app crash with the reason of crashing displaying in CrashReport Activity.

In this tutorial I will craete our custom exception handler which will be helpful to crash app.

Let’s see a video demo what we are going to create.

 

Understanding a Concept.

Sometimes Android apps crash suddenly and we dont realize the reason of app crashing. There are number of exception classes availble in java which is very useful for handling different types of exceptions. Caught and Uncaught aslo the concept of exception handling. let’s see what are these.

 

Caught Exceptions

When we write code , we also use try-catch block in our code to handle exception according to the funtionality and behaviour of code, these are caught exceptions because your app will manage it if something bad happened inside the try catch block. For example.

 


try {
    
    File file = new File("demo.txt");
    file.createNewFile();
    
} catch (IOException e) {
    Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}

Uncaught Exceptions

Crashing app suddenly and unexpectldy can be called due to uncaugh exceptions beacuase sometimes its unexpected having numbers of issues like Null Pointer, No Resource Found, Out Of Memory  and etc.

 

Handling Uncaught Exceptions

In order to handle Uncaught Exception, we will create a class and paste the following code snippet. I am calling it HandleAppCrash.java

public class HandleAppCrash implements Thread.UncaughtExceptionHandler {
    private final Context myContext;
    Class<?> intentClass;

    public HandleAppCrash(Context context, Class<?> intentClass) {
        this.myContext = context;
        this.intentClass = intentClass;
    }

    public static void deploy(Context context, Class<?> intentClass) {
        Thread.setDefaultUncaughtExceptionHandler(new HandleAppCrash(context, intentClass));
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        System.err.println(stackTrace);
        Intent intent = new Intent(this.myContext, this.intentClass);
        intent.putExtra("stackTrace", stackTrace.toString());
        this.myContext.startActivity(intent);
        Process.killProcess(Process.myPid());
        System.exit(10);
    }
}

 

IMPLEMENTING CODE IN ACTIVITY (App Crash)

Now in your Activity class, add the following line inside OnCreate() method

HandleAppCrash.deploy(this,CrashReportActivity.class);

 

CREATING CRASHREPORTACTIVITY

 

  1. Designing CrashReportActivity

Create empty activity in your project and name it CrashReportActivity.java and open its xml file, paste the following xml code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_crash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/colorPrimary">

   <ImageView
       android:layout_width="wrap_content"
       android:layout_height="90dp"
       android:tint="#fff"
       android:layout_marginTop="15dp"
       app:srcCompat="@drawable/maintenance"
       android:layout_alignParentTop="true"
       android:layout_alignParentLeft="true"
       android:layout_alignParentStart="true"
       android:id="@+id/imageView4" />

   <TextView
       android:text="Opps! Something Went Wrong."
       android:layout_width="match_parent"
       android:gravity="center"
       android:textSize="22sp"
       android:enabled="false"
       android:backgroundTint="@android:color/transparent"
       android:textColor="#fff"
       android:layout_height="wrap_content"
       android:layout_below="@+id/imageView4"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="22dp"
       android:id="@+id/textView"
       android:fontFamily="sans-serif" />

   <ScrollView
       android:layout_below="@id/textView"
       android:layout_marginTop="10dp"
       android:layout_marginBottom="10dp"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_above="@+id/btnclose">

      <TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:ems="10"
          android:textSize="16sp"
          android:gravity="top"
          android:layout_below="@+id/textView"
          android:layout_alignParentLeft="true"
          android:layout_alignParentStart="true"
          android:layout_marginTop="15dp"
          android:id="@+id/report"
          android:textColor="#fff"
          android:layout_marginBottom="10dp"
          android:layout_alignParentRight="true"
          android:layout_alignParentEnd="true"
          android:layout_above="@+id/btnclose" />

   </ScrollView>

   <Button
       android:layout_width="match_parent"
       android:layout_height="50dp"
       android:background="#fff"
       android:text="Close"
       android:textSize="24sp"
       android:textAllCaps="false"
       android:textColor="@color/colorPrimary"
       android:layout_alignParentBottom="true"
       android:layout_alignParentLeft="true"
       android:layout_alignParentStart="true"
       android:id="@+id/btnclose" />

</RelativeLayout>

This is how your result look like,

 

android exception

 

 2.Full Code of CrashReportActivity.java

public class CrashReportActivity extends AppCompatActivity {


    private TextView _report;
    private Button _btnclose;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crash_report);

        ActionBar ab = getSupportActionBar();
        ab.hide();
        Intent intent  = getIntent();
        _report = (TextView) findViewById(R.id.report);
        _report.setText(intent.getStringExtra("stackTrace"));
        _btnclose = (Button) findViewById(R.id.btnclose);

        _btnclose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                finish();
            }
        });
    }
}

Run the app and enjoye without app shutdown 🙂

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

6 Comments

Leave a Comment