Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambda expression in android

Tags:

android

lambda

When I Use Lambda like this it report that

Cannot resolve method getAction()

Code

BroadcastReceiver refreshDataReceiver = (context,intent)-> {
        if (AppConstants.REFRESH_DATA_ACTION.equals(intent.getAction())) {
            taskInfos.clear();
            taskInfos.addAll(mTaskDao.queryMyTasks());
            mAdapter.notifyDataSetChanged();
        }
};

While I write this code in normal way, it works well ,why?

 BroadcastReceiver refreshDataReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (AppConstants.REFRESH_DATA_ACTION.equals(intent
                .getAction())) {
            taskInfos.clear();
            taskInfos.addAll(mTaskDao.queryMyTasks());
            mAdapter.notifyDataSetChanged();
        }
    }
};
like image 627
Ryan Avatar asked May 17 '26 20:05

Ryan


2 Answers

BroadcastReceiver is not a valid candidate for lambda replacement. Lambdas can only replace single method interfaces. From the Java Lambda Quickstart docs --

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression.

BroadcastReceiver is neither an interface nor does it have just a single method.

like image 181
iagreen Avatar answered May 20 '26 09:05

iagreen


Add Retrolambda to your Gradle build configuration

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.4.0'
    classpath 'me.tatarka:gradle-retrolambda:3.2.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

Add the source and target compatibility to Java 8 and apply the new plug-in in your app/build.gradle file.

apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'

android {
compileSdkVersion 22
buildToolsVersion "23.0.0 rc2"

defaultConfig {
    applicationId "com.vogella.android.retrolambda"
    minSdkVersion 22
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}



dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
} 

then use lambda expressions. link

like image 37
Vishal Raj Avatar answered May 20 '26 10:05

Vishal Raj