Im using udacity to learn android development and I have ran into a problem. there are a few errors that have come up:
error: package android.v7.app does not exist
error: cannot find symbol class AppCompatActivity
error: method does not override or implement a method from a supertype
error: cannot find symbol variable super
error: cannot find symbol method setContentView(int)
error: cannot find symbol class openNumbersList
error: cannot find symbol method startActivity(Intent)
Everything was working fine but I was following a tutorial and noticed that my imports in my Main Activity didn't match with what was on the tutorial so I changed:
import...
to
import android.v7.app.AppCompatActivity;
import android.os.Bundle;
also even before this, AppCompatActivity was in red:
Main Activity:
package com.example.android.miwok;
import android.content.Intent;
import android.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_main);
}
public void openNumbersList(View view){
Intent i = new Intent(this, openNumbersList.class);
startActivity(i);
}
}
gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "com.example.android.miwok"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:23.3.0'
implementation 'com.android.support:support-v4:23.3.0'
implementation 'com.android.support:design:23.3.0'
}
hope this helps.
I assume, that you forget to add the dependency to the appcompat support library. Add this to your build.gradle in the app folder:
dependencies {
...
// Add this line
implementation 'artifact com.android.support:appcompat-v7:28.0.0-alpha1'
}
However, you should read other tutorials as well because you will proably face more issues, when you don't know how dependencies work in Android. If you create a fresh project in Android Studio, it will create a runnable app for you which is a good point to start off.
EDIT
I re-read your code and the import is incorrect. It must be
android.support.v7.app.AppCompatActivity
instead of
android.v7.app.AppCompatActivity
Related
i am trying to reference a kotlin class in a fragment class in java and it results to error saying that it cannot find the symbol of the kotlin class.
fragment class
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_flashcards, container, false);
go = (ImageButton) rootview.findViewById(R.id.goBtn);
//Instructions audio
instruct = (ImageButton) rootview.findViewById(R.id.soundBtn);
MediaPlayer.create(getActivity(), R.raw.instructions);
//Click go button to explore flashcards
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), Flashcards1.class));
}
});
return rootview;
}
}
this is where the error is
startActivity(new Intent(getActivity(), Flashcards1.class));
build.gradle app
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
compileSdk 33
defaultConfig {
applicationId "com.example.salitongue_updated"
minSdk 27
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
viewBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.0'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.0.5'
implementation 'com.google.firebase:firebase-firestore:24.2.2'
implementation 'com.google.firebase:firebase-auth:21.0.7'
implementation 'androidx.navigation:navigation-fragment:2.5.1'
implementation 'androidx.navigation:navigation-ui:2.5.1'
implementation "androidx.fragment:fragment-ktx:1.6.0-alpha02"
//testImplementation 'junit:junit:4.13.2'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
build.gradle
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.13'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10"
}
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.2.2' apply false
id 'com.android.library' version '7.2.2' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
I think your problem is that you don't have Kotlin set up for your app module. You have the plugin dependency added to your main build.gradle, but you're not applying the plugin in the app module build.gradle. You also don't have the kotlin-stdlib dependency added to that module. Have a look at the example setup here (you have to scroll down a bit to the code snippets).
I don't know a lot about Gradle and the ways to configure your build files, so it's possible you've got it set up a different way and it's fine - but you should be able to see Kotlin class files from Java without doing anything special:
Kotlin code can be easily called from Java. For example, instances of a Kotlin class can be seamlessly created and operated in Java methods.
So it seems like maybe it's just not set up, and that's why it's not working for you. If Kotlin's working in the IDE (like popping up in code completion) but not when you try to build it, that sounds like the IDE plugin is set up fine, but not the stuff in your project. I don't know for sure, but hopefully it'll help!
Problem:
I'm trying to recreate this codelab tutorial project https://developer.android.com/codelabs/android-proto-datastore, but Android Studio can't import androidx.datastore.dataStore
Steps:
create new Kotlin project with an empty Acivity
modify gradle file
Switch to Android Studio's Project view
create a folder named proto inside of app/src/main
create and modify file user_prefs.proto inside of app/src/main/proto
Build -> Clean Project -> rebuild project
Create a serializer class called UserPreferencesSerializer
Trying to add the following Code to the empty MainActivity.kt
private const val DATA_STORE_FILE_NAME = "user_prefs.pb"
private val Context.userPreferencesStore: DataStore
by dataStore(
fileName = DATA_STORE_FILE_NAME,
serializer = UserPreferencesSerializer )
After this step Android Studio marks dataStore and shows the warning "Unresolved reference: dataStore" I'm also unable to import androidx.datastore.dataStore, but I can't find a missing import in my gradle file. Please, can someone tell me how I can resolve this problem?
Code:
build.gradle
plugins {
id 'com.android.application'
id 'kotlin-android'
id "com.google.protobuf" version "0.8.12"
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.test"
minSdkVersion 28
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "androidx.datastore:datastore-core:1.0.0-alpha08"
implementation "com.google.protobuf:protobuf-javalite:3.11.0"
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.10.0"
}
// Generates the java Protobuf-lite code for the Protobufs in this project. See
// https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
// for more information.
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option 'lite'
}
}
}
}
}
user_prefs.proto
syntax = "proto3";
option java_package = "com.example.test";
option java_multiple_files = true;
message UserPreferences {
// filter for showing / hiding completed tasks
bool show_completed = 1;
}
UserPreferencesSerializer
package com.example.test
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import com.google.protobuf.InvalidProtocolBufferException
import java.io.InputStream
import java.io.OutputStream
object UserPreferencesSerializer : Serializer<UserPreferences> {
override val defaultValue: UserPreferences = UserPreferences.getDefaultInstance()
override suspend fun readFrom(input: InputStream): UserPreferences {
try {
return UserPreferences.parseFrom(input)
} catch (exception: InvalidProtocolBufferException) {
throw CorruptionException("Cannot read proto.", exception)
}
}
override suspend fun writeTo(t: UserPreferences, output: OutputStream) = t.writeTo(output)
}
MainActivity.kt
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.datastore.core.DataStore
private const val DATA_STORE_FILE_NAME = "user_prefs.pb"
private val Context.userPreferencesStore: DataStore<UserPreferences> by dataStore(
fileName = DATA_STORE_FILE_NAME,
serializer = UserPreferencesSerializer
)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
I also had this problem while working on a project.
I found that I was using datastore-core and needed datastore-preferences. So I changed my dependency declaration from:
implementation 'androidx.datastore:datastore-core:1.0.0-alpha08'
to:
implementation 'androidx.datastore:datastore-preferences:1.0.0'
Possibly there was a breaking change between alpha08 and the 1.0.0 release.
The dataStore delegate is part of the androidx.datastore:datastore library.
Add the dependency to your modudle's build.gradle file. Replace $dataStoreVersion with the version of data store which you use, e.g. 1.0.0:
implementation "androidx.datastore:datastore:$dataStoreVersion"
You can find the available versions here in Google's Maven repository.
After adding this dependency, you can use by dataStore by adding the following import to your class:
import androidx.datastore.dataStore
In Android documentation:
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
This line should be at the top of your code.
See DataStore documenation
After a lot of searching, The problem is simple. Make sure Gradle is not in offline mode.
Also, ensure that you use this dependency.
implementation "androidx.datastore:datastore-preferences:$dataStoreVersion"
I am following a tutorial where the instructor is using the Android support library v7. In my app I am using the androidx version (as suggested on the Android Developer website). When I type the lines of code as instructed, Android Studio puts a strikethrough over part of the code where I try to obtain a FragmentManager and says: "getter for fragmentManager: FragmentManager! is deprecated. Deprecated in Java." I have searched so many posts where people were having similar issues but the solutions provided don't apply to my case. Some users were having mismatched support library versions and others didn't have the proper dependencies in the gradle file. As far as I can tell those issues don't apply here.
According to the androidx documentation for FragmentManager, it states, "Your activity must derive from FragmentActivity to use this. From such an activity, you can acquire the FragmentManager by calling FragmentActivity#getSupportFragmentManager." However, I am not using an Activity, the code is inside an inner class that extends the RecylcerView.ViewHolder class which is nested inside a class extending RecyclerView.Adapter. Is my only choice to use the android support library v7?
RecyclerView Adapter Class:
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.e_product_row.view.*
import androidx.fragment.app.DialogFragment // greyed out as "unused import directive"
import androidx.fragment.app.FragmentManager // greyed out as "unused import directive"
class EProductAdapter(var context: Context, var arrayList : ArrayList<EProduct>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val productView = LayoutInflater.from(context).inflate(R.layout.e_product_row, parent, false)
return ProductViewHolder(productView)
}
override fun getItemCount(): Int {
return arrayList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
// downcast holder to ProductViewHolder
(holder as ProductViewHolder).initializeRowComponents(arrayList.get(position).id,
arrayList[position].name,
arrayList[position].price,
arrayList[position].picture)
}
inner class ProductViewHolder(productView: View) : RecyclerView.ViewHolder(productView) {
fun initializeRowComponents(id: Int, name: String, price: Int, pictureName: String) {
itemView.txt_id.text = id.toString()
itemView.txt_name.text = name
itemView.txt_price.text = price.toString()
var pictureUrl = "http://192.168.0.21/OnlineStoreApp/osimages/$pictureName"
pictureUrl = pictureUrl.replace(" ", "%20")
Picasso.get().load(pictureUrl).into(itemView.img_product)
// initialize add item imageView
itemView.img_add_item.setOnClickListener {
var amountFragment = AmountFragment()
var fragmentManager = (itemView.context as Activity).fragmentManager // fragmentManager strikethrough text
amountFragment.show(fragmentManager, "TAG") // show function cannot be called with arguments supplied and won't compile
}
}
}
}
DialogFragment class:
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
class AmountFragment : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle? ): View? {
return inflater.inflate(R.layout.fragment_amount, container, false)
}
}
build.gradle(Module: app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.bryontaylor.onlinestoreapp"
minSdkVersion 24
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.android.volley:volley:1.1.1'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.fragment:fragment:1.2.4'
implementation 'androidx.fragment:fragment-ktx:1.2.4'
}
According to the androidx documentation for FragmentManager, it
states, "Your activity must derive from FragmentActivity to use this.
From such an activity, you can acquire the FragmentManager by calling
FragmentActivity#getSupportFragmentManager." However, I am not using
an Activity
Yes you are:
var fragmentManager = (itemView.context as Activity).fragmentManager
The only problem is that you're casting to the root Activity type and using the deprecated getFragmentManager(). You need to do exactly as the docs state: use FragmentActivity and getSupportFragmentManager():
var fragmentManager = (itemView.context as FragmentActivity).supportFragmentManager
Your show() call will then work because you're passing in the correct fragment manager type.
Hope that helps!
Recently I've been trying to make a annotation processor through Kotlin but I can't seem to get it to work. Everything compiles and I don't get any errors but when I check the contents of my jar file I don't see the resource I'm trying to create.
I've tried everything for hours and I'm really stuck so just looking for help :/ I do have one random class annotated to see if it would work but no luck.
The annotation class
#Retention(AnnotationRetention.RUNTIME)
#Target(AnnotationTarget.CLASS)
annotation class TestAnnotation
The processor class
#AutoService(TestAnnotation::class)
class TestAnnotationProcessor : AbstractProcessor() {
override fun process(annotations: MutableSet<out TypeElement>, environment: RoundEnvironment): Boolean {
this.processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", "test.txt")
return true
}
override fun getSupportedSourceVersion() = SourceVersion.RELEASE_8
override fun getSupportedAnnotationTypes() = setOf(TestAnnotation::class.java.canonicalName)
}
My build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
java
kotlin("jvm") version "1.3.50"
kotlin("kapt") version "1.3.50"
id("com.github.johnrengelman.shadow") version "5.1.0"
}
group = "com.example.test"
version = "1.0"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.1")
implementation("com.google.auto.service:auto-service:1.0-rc6")
kapt("com.google.auto.service:auto-service:1.0-rc6")
}
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.withType<ShadowJar> {
dependencies {
exclude(dependency("com.google.auto.service:auto-service:1.0-rc6"))
}
}
In order for your custom annotation processor to work, you will have to use it in your build script dependencies
dependencies {
kapt project(':processor-module') // or what ever your processor's module is named.
//OR
kapt 'gourp:artifact:version' // if your processor is published into a maven repository.
}
Android Studio 3.4.2
build.gradle:
buildscript {
ext.kotlin_version = '1.3.41'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
in app/build.gradle:
def AAVersion = '4.6.0'
def KOTLIN_COROUTINE_VERSION = '1.2.1'
dependencies {
annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation('com.crashlytics.sdk.android:crashlytics:2.7.0#aar') { transitive = true; }
implementation 'com.google.android.material:material:1.1.0-alpha07'
implementation 'com.google.code.gson:gson:2.8.5'
implementation "org.androidannotations:androidannotations-api:$AAVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$KOTLIN_COROUTINE_VERSION"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINE_VERSION"
}
I has activity (java class) annotate by org.androidannotations.annotations.EActivity
Here snippet:
import android.app.Activity;
import android.os.Bundle;
import org.androidannotations.annotations.EActivity
#EActivity
public class LoginActivity extends Activity {
}
And another java activity (SplashActivity.java) that call this LoginActivity like this:
import android.app.Activity;
import android.os.Bundle;
import org.androidannotations.annotations.EActivity
#EActivity
public class SplashActivity extends Activity {
Intent intent = new Intent(thisActivity, LoginActivity_.class);
startActivity(intent);
Nice it's work fine.
Now I migrate only LoginActivity to Kotlin class (LoginActivity.kt)
like this:
import org.androidannotations.annotations.Background
import org.androidannotations.annotations.EActivity
#EActivity
open class LoginActivity : Activity() {
}
and now SplashActivity.java has compile error in this line:
Intent intent = new Intent(thisActivity, LoginActivity_.class);
error message:
Cannot resolve symbol 'LoginActivity_'
P.S. If I remove "_" than compile success:
Intent intent = new Intent(thisActivity, LoginActivity.class);
But I need to use LoginActivity_
You have to use kapt instead of annotationProcessor to handle Kotlin files. Any annotation processor may or may not correctly handle them; for androidannotations in particular there is documentation on Kotlin support.