In the following Kotlin code
editTextUsername = EditText findViewById(R.id.email_edittext)
and the error is :
Error:(70, 35) Unexpected tokens (use ';' to separate expressions on the same line)
but i can not understand what did i do wrong.
If you're trying to specify the type of a variable, you can do it like this:
val editTextUsername: EditText = findViewById(R.id.email_edittext)
If you're below API level 26, and need a cast:
editTextUsername = findViewById(R.id.email_edittext) as EditText
If you already have the generic findViewById method because you're on a newer API level:
editTextUsername = findViewById<EditText>(R.id.email_edittext)
if you are finding and casting view inside activity
editTextUserName = findViewById<EditText>(R.id.<id>) as EditText
or inside fragment use the ff
View view = inflater.inflate(R.layout.article_view, container, false);
editTextUserName = view.findViewById<EditText>(R.id.<id>) as EditText
Related
Trying to pass a data class User from one Activity to another using Intent.
My putExtra looks like this using my observe fun:
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("userData",userData)
startActivity(intent)
My get routine looks like this:
userData = intent.getParcelableExtra<User>("userData") as User
or
userData = intent.getParcelableExtra("userData")
My problem is that Android Studio strikes out the function. My User data class is marked #Parcelize. It all ends up getParcelableExtra.
I've add to my gradle build:
id 'kotlin-parcelize'
I've read several posts about Parcelable being more modern than Serialable, so that's the technique I'm using. All the posts are from 2018 or prior and many of them in Java.
How does one send an data class from one Activity to another using Intent?
Since getParcelableExtra (String name) is deprecated from api level 33 you can use getParcelableExtra (String name, Class<T> clazz) from api level 33
In Your case use :
val userData =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra("userData", userData::class.java)
}
else{
intent.getParcelableExtra("userData") as userData?
}
where TIRAMISU is constant value 33
To get more info:Read this:
https://developer.android.com/reference/android/content/Intent#getParcelableExtra(java.lang.String,%20java.lang.Class%3CT%3E)
SOLUTION:
Given the need for compiler version 33 for the most modern solution, I went with a more backward compatible solution. This code translates the data object into a string, then back into the object.
SETUP: (PUT)
private var _userData = MutableLiveData<User>() // does the username and pw validate?
val userData : LiveData<User>
get() = _userData
SETUP: (GET)
private lateinit var userData: User
PUT CODE:
val intent = Intent(this, MainActivity::class.java)
val jsonUserData = Gson().toJson(userData)
intent.putExtra("userData",jsonUserData)
GET CODE:
val jsonUserData = intent.getStringExtra("userData")
userData = Gson().fromJson(jsonUserData, User::class.java)
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.
Can anyone please suggest me good server side validation library for kotlin.
Which can perform basic validation like below
Checking for spaces and new line in a string
Checking the minimum and maximum of character in a string
Checking empty string
As I need to use a validation library instead of below code
val data.name = "test test"
val nameMaxLimit: Int = 256
if (data.name.contains(" ") || data.name.isNullOrEmpty() || data.name.length > nameMaxLimit) {
return true
}
My project is a Gradle Project, So gradle supported validation library will be blessed
You can use beans validation. I think it is the best way.
You would need to annotate each field with the rules you want.
Then you would tell the validations to run.
It would return to you an array of violations.
Here an example:
import javax.validation.Validator
val violations = validator.validate(data)
if (violations.isEmpty()) {
successAction()
}
I have a TabLayout with a fragment in each tab. The first tab is a fragment instance, and the next has an instance of the same fragment:
adapter.addFragment(fragmentoFichaSerie.newInstance(ficha, cookie), "Ficha");
for (HTMLParser.temporada objTemporada : ficha.temporadas)
{
adapter.addFragment(fragmentoCapitulos.newInstance(objTemporada.capitulos, cookie), objTemporada.nombre);
}
"ficha.temporadas" contains "n" "capitulos" arrays. Each fragment receive one "capitulos" array.
fragmentoCapitulos contains a RecyclerView that i populate with an ArrayList of objects (each item get its data from one array's position).
In the fragment, i receive the array in the "newInstance" method and put it in a bundle with putParcelableArrayList.
public static fragmentoCapitulos newInstance(List<HTMLParser.capitulo> capitulos, String Cookie) {
fragmentoCapitulos fragment = new fragmentoCapitulos();
Bundle args = new Bundle();
args.putParcelableArrayList("capitulos", (ArrayList<HTMLParser.capitulo>) capitulos);
fragment.setArguments(args);
cookie = Cookie;
return fragment;
}
In onCreateView i get the content of the bundle:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.capitulos, container, false);
RecyclerView recycler = (RecyclerView) view.findViewById(R.id.recCapitulos);
TextView empty = (TextView) view.findViewById(R.id.empty);
ImageView imgEmpty = (ImageView) view.findViewById(R.id.imgEmpty);
ArrayList<HTMLParser.capitulo> capitulos;
capitulos = getArguments().getParcelableArrayList("capitulos");
My problem is if i'm in tab 2, i should receive the first array of "ficha.temporadas", but i receive the second array (the first tab contains another fragment that doesn't need any array).
I try to pass a void array to the first tab but doesn't work. What can i do to pass the correct array to each fragment?
Finally i found a solution. I was wrong with the problem, not a parcelable error.
When viewpager creates pages dynamically always generates pages at both sides of current page. This was doing incorrectly. After debuging much time and reading a lot of articles, i changed FragmentPagerAdapter by FragmentStatePagerAdapter and all works fine.
I hope this could be helpful for someone with same problem.
For example, when I type ArrayList<String> data =, how can I auto-complete this so that it shows ArrayList<String> data = new ArrayList<>();?
PS: I do remember there is a way to do so in eclipse, but I don't know how to do it in android studio.
Type Object obj = new and then
Ctrl+Shift+Space bar
Example:
String str = new (ctrl+shift+space)
will give you
String str = new String();
For Objects that have paramters it will show suggestion as in while creating Collection objects like List<E> and ArrayList<E> like,
Reference: Here is a full list of Key map for Windows
Assuming you have the default keymap, it's Ctrl + Shift + A
Reference:
https://developer.android.com/sdk/installing/studio-tips.html
http://www.jetbrains.com/idea/documentation/index.jsp