1

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

1
  • you need to create Kotlin and Java code in separate files. Kotlin code goes in *.kt files, Java code - in *.java files. Commented Jan 14, 2019 at 19:43

1 Answer 1

1
//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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.