I have a file, where the variables are "static" in java sense, and I want to access them by the file name. I am giving an example.
private var user:User?= null// this is put directly inside the file
fun saveMe(user: User?){
saveObject(user, USER_FILE)
FileStorage.user = user// this method is not allowed. How to access the top level user variable from here?
}
I don't know if this has been asked before, I guess the question is clear, about accessing the top level variable from a function that has same name argument. I don't want to rename either of the variables.
Option 1: Wrap your file into object:
object FileStorage {
// all your previous file content
}
Then FileStorage.user means exactly what you want.
Option 2 (if your file has a package declaration):
fun saveMe(user: User?){
saveObject(user, USER_FILE)
your.package.user = user
}
Option 3: add indirection:
private var user:User?= null
fun setTopLeverUser(_user: User?) { user = _user; }
fun saveMe(user: User?){
saveObject(user, USER_FILE)
setTopLevelUser(user)
}
Related
I recently switched to Java 11 for a rather big project, and would like to switch to using var class = new Class() instead of Class class = new CLass().
I tried using Intellij Structural Search (and replace) for this, but its turning out to be more complex than expected.
My first attempt was $Type$ $Inst$ = new $Constructor$($Argument$);, which also matches global variables (which don't allow var).
My second attempt is:
class $Class$ {
$ReturnType$ $Method$ ($ParameterType$ $Parameter$) throws $ExceptionType$ {
$Statements$;
final $Type$ $Inst$ = new $Constructor$($Argument$);
$Statements2$;
}
}
Which misses all calls inside e.g. try blocks (since they get matched by the expressions)
Any help would be greatly appreciated!
Use your first template
$Type$ $Inst$ = new $Constructor$($Argument$);
But add a Script modifier on the $Inst$ variable with the following text:
Inst instanceof com.intellij.psi.PsiLocalVariable
Alternatively you may want to try the Local variable type can be omitted inspection that is available in IntelliJ IDEA.
I'm trying to add a method (PsiMethod) to a class (PsiClass) so that IDEA shows this method when typing. I did this, but I ran into a problem: when I add PsiMethod to PsiClass, the text of this method appears in the file, and I don't need it. I need to add a method so that it is highlighted by IDEA, but it is not displayed in the file as text.
How can this be done?
Here is my code how I add PsiMethod to PsiClass:
val module = ModuleManager.getInstance(project).modules.first()
val file = FilenameIndex
.getFilesByName(
project,
"TestPsiFile.java",
module.moduleContentScope)
.first()
val newMethod = PsiElementFactory.getInstance(project).createMethod("testMethod", PsiType.VOID)
WriteCommandAction.runWriteCommandAction(project) {
file.children
.filter { it.elementType == JavaElementType.CLASS }
.map { it.add(newMethod) }
}
Link to this question in the Jetbrains Community: link
How to populate the value of this variable:
private val _urlList = MutableLiveData<List<Url>>()
of type Url:
data class Url(
val imgSrcUrl: String
)
with the incoming list of url strings from a firebase call?
Here is where the magic happens:
private fun getData(){
viewModelScope.launch {
try {
getImagesUrl {
"Here where I need to set the value of the variable to a listOf(it) with it being strings
of urls retrieved from firebase storage"
}
}catch (e: Exception){
"Handling the error"
}
}
}
Edit
The map function #dominicoder provided solved my problem, answer accepted.
Thank you all for your help
Your question is unclear because you're showing a live data of a single Url object but asking to stuff it with a list of strings. So first, your live data object needs to change to a list of Urls:
private val _urlList = MutableLiveData<List<Url>>()
Then, assuming getImagesUrl yields a list of strings, if I understood you correctly, then you would map that to a list of Urls:
getImagesUrl { listOfImageUrlStrings ->
_urlList.value = listOfImageUrlStrings.map { imageUrlString -> Url(imageUrlString) }
}
If that does not answer your question, you really need to review it and clarify.
You can set values on the MutableLiveDataObject in two ways (depends on what you're doing).
Setting the value as normal from the UI thread can be done with:
myLiveData.value = myobject
If you're setting it from a background thread like you might in a coroutine with a suspended function or async task etc then use:
myLiveData.postValue(myObject)
It's not clear from your question whether the LiveData is meant to hold a list as you mention both lists and single values. But your LiveData holds a set the values as a collection like a list, set or map. It's can be treated as a whole object so adding a value later needs to have the whole collection set again like:
myLiveData.value = mutableListOf<Url>()
//Response received and object created
myLiveData.value = myLiveData.value.apply {
add(myObject)
}
Or if the value is mutable updating the existing value (preferred as it's cleaner):
myLiveData.value.add(myObject)
The problem with that approach is you're exposing the map as a mutable/writeable object. Allowing accessors to change the values which you might not want.
Having problems with my code, So I am currently trying to create a new directory and also store a text file within that folder I have created, I looked at a couple of examples but it seems like they only focus on a specific thing like how to create a file or a folder but never how to utilise both. How can I achieve this? I keep hitting exception errors when I try doing different methods, thanks!
val newFile : Int = 1
val fileString = "nameData"
//so we are creating variable to store the directory information
val folderDir = File("G:\\Random Projects\\JVM\\database\\Collection 1")
//we use that variable to create a File class which will create a folder called nameData
//this will also be stored in another variable called f
val f = File(folderDir, "nameData")
//this will create the actual folder based on the variable information
f.mkdir()
//creating file
try {
val fo = FileWriter(fileString, true)
fo.write(a)
fo.close()
} catch (ex:Exception) {
println("Something Went Wrong When Creating File!!")
}
The problem is that you probably don't have the whole folder structure created, that's why you usually use the mkdirs (note the s at the end) function. You can then use the writeBytes function to write the content:
val fileString = "nameData"
val folderDir = File("myfolder")
val f = File(folderDir, "nameData")
f.parentFile.mkdirs()
f.writeBytes(fileString.toByteArray())
I'd like to be able to use Micronaut's declarative client to hit an a different endpoint based on whether I'm in a local development environment vs a production environment.
I'm setting my client's base uri in application.dev.yml:
myserviceclient:
baseUri: http://localhost:1080/endpoint
Reading the docs from Micronaut, they have the developer jumping through quite a few hoops to get a dynamic value piped into the actual client. They're actually quite confusing. So I've created a configuration like this:
#ConfigurationProperties(PREFIX)
class MyServiceClientConfig {
companion object {
const val PREFIX = "myserviceclient"
const val BASE_URL = "http://localhost:1080/endpoint"
}
var baseUri: String? = null
fun toMap(): MutableMap<String, Any> {
val m = HashMap<String, Any>()
if (baseUri != null) {
m["baseUri"] = baseUri!!
}
return m
}
}
But as you can see, that's not actually reading any values from application.yml, it's simply setting a const value as a static on the class. I'd like that BASE_URL value to be dynamic based on which environment I'm in.
To use this class, I've created a declarative client like this:
#Client(MyServiceClientConfig.BASE_URL)
interface MyServiceClient {
#Post("/user/kfc")
#Produces("application/json")
fun sendUserKfc(transactionDto: TransactionDto)
}
The docs show an example where they're interpolating values from the config map that's built like this:
#Get("/api/\${bintray.apiversion}/repos/\${bintray.organization}/\${bintray.repository}/packages")
But how would I make this work in the #Client() annotation?
Nowhere in that example do they show how bintray is getting defined/injected/etc. This appears to be the same syntax that's used with the #Value() annotation. I've tried using that as well, but every value I try to use ends up being null.
This is very frustrating, but I'm sure I'm missing a key piece that will make this all work.
I'm setting my client's base uri in application.dev.yml
You probably want application-dev.yml.
But how would I make this work in the #Client() annotation?
You can put a config key in the #Client value using something like #Client("${myserviceclient.baseUri}").
If you want the url somewhere in your code use this:
#Value("${micronaut.http.services.occupancy.urls}")
private String occupancyUrl;