Null pointer exception when retrieving textView in onCreate using shared preference - nullpointerexception

Here is my code in onCreate method
SharedPreferences sp = getSharedPreferences("key", Context.MODE_PRIVATE);
String tValue = sp.getString("textvalue","");
coins.setText(tValue);
This is where iam saving text value
count++;
coins.setText(String.valueOf(count));
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", coins.getText().toString());
sedt.commit();

The problem will be resolved by this line..Try it
TextView coins = (TextView) findViewById(R.id.yourcoinsid);
coins.setText(""+tValue);
Reason
The instance variable coins was null , so we find it using findViewById and then it will work.

Related

Kotlin Cancels getParceableExtra call when passing data class using Intent

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)

Jetpack compose and Kotlin, dynamic UI losing values on recomp

I am making a dynamic UI using kotlin and Jetpack compose and storing the information in an object box database.
The aim is that i will have a composable that starts off with 1 initial item that is empty and when the contents of the textbox have been filled in would allow the red "+" button to be clicked and then another textfield would appear. These values will need to be able to be edited constantly all the way until the final composable value is stored. The button changes colour currently and the states are fine with the button so i can add and remove rows
The data comes in as a string and is converted into a Hashmap<Int, String>. The int is used to store the position in the map being edited and the string would be the text value.
Using log messages i see that the information is updated in the list and for recomp sake i instantly store the value of the edited list in a converted json string.
At the moment:
When i scroll past the composable it resets and looks like the initial state (even if i have added multiple rows)
Log messages show that my hashmap has the values from before e.g. {"0":"asdfdsa"} but the previous positions are ignored and as the previous information would still be present but not shown on the UI when i enter it into the first field again (the others are not visible at the time) {"0":"asdfdsa","0":"hello"}. This would later cause an error when trying to save new data to the list because of the duplicate key
In the composables my hashmap is called textFields and is defined like this. Number is used to determine how many textfields to draw on the screen
val textFields = remember { getDataStringToMap(data.dataItem.dataValue) }
val number = remember { mutableStateOf(textFields.size) }
the method to getDataStringToMap is created like this
private fun getDataMapToString(textFieldsMap: HashMap<Int, String>): String {
val gson = Gson()
val newMap = hashMapOf<Int, String>()
for (value in textFieldsMap){
if (value.value .isNotBlank()){
newMap[value.key] = value.value
}
}
return gson.toJson(newMap)
}
and the method to getDataStringToMap is created like this (I explicitly define the empty hashmap type because its more readable for me if i can see it)
private fun getDataStringToMap(textsFieldsString: String): HashMap<Int, String> {
val gson = Gson()
return if (textsFieldsString.isBlank()) {
hashMapOf<Int, String>(0 to "")
} else {
val mapType = HashMap<Int, String>().javaClass
gson.fromJson(textsFieldsString, mapType)
}
the composables for the textfields are called like this
items(number.value) { index ->
listItem(
itemValue = textFields[index].orEmpty(),
changeValue = {
textFields[index] = it
setDataValue(getDataMapToString(textFields))
},
addItem = {
columnHeight.value += itemHeight
scope.launch {
scrollState.animateScrollBy(itemHeight)
}
},
deleteItem = {
columnHeight.value -= itemHeight
scope.launch {
scrollState.animateScrollBy(-itemHeight)
}
},
lastItem = index == number.value - 1,
index = index
)
}
Edited 30/12/2022
Answer from #Arthur Kasparian solved issues. Change to rememberSaveable retains the UiState even on scroll and recomp.
Now just to sort out which specific elements are removed and shown after :D
The problem is that remember alone does not save values on configuration changes, whereas rememberSaveable does.
You can read more about this here.

How to copy values from a recyclerview to clipboard in kotlin?

I'm trying to copy text in recyclerview to clipboard. can anyone help me.
val myClipboard = rvItemsList.getContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val myClip = ClipData.newPlainText("label", rvItemsList.toString())
myClipboard.setPrimaryClip(myClip)
this is the code i used. when trying to print i'm getting result
I/System.out: ClipData { text/plain "label" {T:androidx.recyclerview.widget.RecyclerView{1d0e7d4 VFED..... ........ 55,809-1025,1768 #7f08015b app:id/rvItemsList}} }
values in the recycler view is productname and rate
image of app with recyclerview
The issue here that when you call rvItemsList.toString it will return default toString() method on the object.The output is, class name, then ‘at’ sign, and at the end hashCode of object.
If want to copy value just add click listener on your textview. e.g.:
textView.setText("your_value")
textView.setOnClickListener {
val myClipboard = rvItemsList.getContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val myClip = ClipData.newPlainText("label", your_value) myClipboard.setPrimaryClip(myClip)
}

InputStream getResource() return NULL

I need to get inputStream from ./resources but I got all the time NULL. Let me show you, what I did.
This is my simple code:
private const val CREDENTIALS_FILE_PATH = "/credentials.json"
val inputStream = javaClass.getResource(CREDENTIALS_FILE_PATH)
When I set debugger on inputStream, I got null all the time.
I tried write input in different way, but it also do not work.
val inputStream = this::class.java.classLoader.getResource(CREDENTIALS_FILE_PATH)
val inputStream = javaClass.classLoader.getResource(CREDENTIALS_FILE_PATH)
So I did something like that:
val inputStream = javaClass.getResource(".")
and I think there is problem, because this path refer to ./out/test/classes not to ./out/test/resources
Can I ask for some advice so that I can point to the file from ./resources?

Kotlin complains about this (Unexpected Tokens)

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