简体   繁体   中英

Calling kotlin function from java class creates error

I am trying to call kotlin class function from Java class but getting error instead. I have added both kotlin and java code inside the java class. Below is the code and I am getting error while using context.

KotlinClass:

class TestDatabaseHandler(var context: Context?) :
    SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION)

{
    fun insertSerialNo(serialno: String)
    {
        val db=this.writableDatabase
        var cv=ContentValues()
    }
}

JavaClass:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String serialno =123456;
        Intent intent = new Intent(MainActivity.this, Test.class);
        intent.putExtra("serialno", serialno);

        //Below Four lines of Code Error in JavaClass
        var db= TestDatabaseHandler(this.applicationContext)
        db.insertSerialNo(serialno)
        //Java Conversion
        String db= new TestDatabaseHandler(this.context);
        db.insertSerialNo(serialno);

        startActivity(intent);

    }
}

Error:

1) Can't find symbol context

2) Can't resolve method insertSerialNo

//Below Four lines of Code Error in JavaClass
var db= TestDatabaseHandler(this.applicationContext)
db.insertSerialNo(serialno)
//Java Conversion
String db= new TestDatabaseHandler(this.context);
db.insertSerialNo(serialno);

Not counting comments:

The first two lines are in Kotlin. Java has no var syntax, and creating new instances requires the new keyword. Remove these lines.

The second two lines are the proper Java syntax for the Kotlin lines above. However, there is no such thing as Activity.context . Activity is already a Context. Just pass this , not this.context .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM