Search code examples
androidtimber-android

Timber duplicate logs after calling finish() and restarting app


I have an onTouchListener on my TextView. On touch, I log with Timber.i() and then I call finish(). If after finish(), I launch my app again, and click again on the TextView, It will log twice, then 3 times, etc...

(If I replace Timber.i() by the normal Log.i(), there is no problem)

// first time
Clicked

// second time
Clicked
Clicked

// etc...
Clicked
Clicked
Clicked

Timber version :

compile 'com.jakewharton.timber:timber:4.5.1'

Working code :

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Timber.plant(new Timber.DebugTree());

    TextView tv = (TextView) findViewById(R.id.mytextview);
    tv.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Timber.i("Clicked");
            finish();
            return false;
        }
    });
}

Layout :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.caca.test.MainActivity">

    <TextView
        android:id="@+id/mytextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

Solution

  • The problem is that you are 'planting' trees in the Activities onCreate method. Instead, use a custom Applications subclass and plant the trees there.

    
    class MyApp : Application() {
    
        override fun onCreate() {
            super.onCreate()
    
            if (BuildConfig.DEBUG) {
                 Timber.plant(DebugTree())
            }
        }
    }
    

    And update your AndroidManifest accordingly:

    <application android:name="com.foo.MyApp" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"/>