I'm trying to launch a activity based on whats in my sharedpreference string, so that I can use 1 login page that redirects to the corresponding activity based on the button I click.
Here I put in the sharedpref what the activity is called, which is ConfigureActivity.
sharedSettingsData.edit()
.putString("settingsLogin", "ConfigureActivity")
.apply()
Then here I get whats inside the sharedpref and insert it into a variable:
val activityHandler = sharedSettingsData.getString("settingsLogin","").toString()
and here I try to launch it:
val intent = Intent(this, activityHandler::class.java)
startActivity(intent)
But when doing this I get this error:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.myapp/java.lang.String};
I fixed my problem using this:
try {
if(sharedSettingsData.getString("settingsLogin", "") == "ConfigureActivity"){
val i = Intent(this, ConfigureActivity::class.java)
startActivity(i)
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
}
if(sharedSettingsData.getString("settingsLogin", "") == "SettingsChangePin"){
val i = Intent(this, SettingsChangePin::class.java)
startActivity(i)
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
}
if(sharedSettingsData.getString("settingsLogin", "") == "ConnectionsActivity"){
val i = Intent(this, ConnectionsActivity::class.java)
startActivity(i)
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
}
if(sharedSettingsData.getString("settingsLogin", "") == "InfoActivity"){
val i = Intent(this, InfoActivity::class.java)
startActivity(i)
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
}
}
catch (e: Exception){
Log.d("[ACTIVITY EXCEPTION]", "Unable to find correct activity to intent to. Code: $e")
}
Related
I'm trying to use registerForActivityResult but the result of it is 0, which mean that it doesn't get the result from the activity. The code was working perfectly last month when i did it, but i don't know why it made the error today, i tried to check for error in the code, but i dont think there is one.
Here is the function to use the camera :
private fun UseCamera() {
val takePictureIntent = Intent (MediaStore.ACTION_IMAGE_CAPTURE)
val imagePath = File(Environment.getExternalStorageDirectory(), "Pictures")
val photoFile = File(imagePath, "my_picture.jpg")
FilePath = FileProvider.getUriForFile(this, FILE_AUTHORITY, photoFile )
Log.w("FilePath",FilePath.toString())
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FilePath)
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
getPreviewImage.launch(takePictureIntent)
Log.w("UseCamera","Successful")
}
and here is the registerForResultActivity :
getPreviewImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result -> Log.e("Preview Image", result.resultCode.toString())
if (result.resultCode == RESULT_OK) {
if (!forfood){
Log.i("File Path", FilePath.toString())
val SelectedImage = FilePath
val PicRef = StorageRef.child(preferences.getValue("username").toString())
.child("kiosk_pic/" + ImageID)
PicRef.putFile(SelectedImage).addOnSuccessListener {
Toast.makeText(this, "Uploaded", Toast.LENGTH_SHORT).show()
PicRef.downloadUrl.addOnSuccessListener {
preferences.setValue("kiosk_pic", it.toString())
ref.child(preferences.getValue("username").toString()).child("kiosk_picture").setValue(it.toString())
setKioskImage(preferences.getValue("kiosk_pic").toString(),ImageID)
}
}
.addOnFailureListener {
Toast.makeText(this, "Upload Fail", Toast.LENGTH_SHORT).show()
}
.addOnProgressListener {
Toast.makeText(this, "Uploading", Toast.LENGTH_SHORT).show()
}
} else {
Log.i("File Path",FilePath.toString())
val SelectedImage = FilePath
if (add){
iv_addimage.setImageURI(SelectedImage)
}else{
iv_changeimage.setImageURI(SelectedImage)
}
}
}
}
i added the log and the result was this everytime i use the camera :
W/UseCamera: Successfull
D/OpenGLRenderer: endAllActiveAnimators on 0xea49f7f0 (AlertController$RecycleListView) with handle 0xc1acc9b0
E/Preview Image: 0
what did i do wrong here? since it worked perfectly before
EDIT
and also the log says this :
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
I have fix the problem by changing the UseCamera function code. im not really sure, but i think the problem was this part :
val imagePath = File(Environment.getExternalStorageDirectory(), "Pictures")
val photoFile = File(imagePath, "my_picture.jpg")
since im not really sure, my guess is that the temporary file that was created was missing right after the picture was taken so then make the resultcode return RESULT_CANCELED
i change my code to this:
private fun UseCamera() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val imageFile = getExternalFilesDir (Environment.DIRECTORY_PICTURES)
val tempFile = File.createTempFile("my_picture",".jpg",imageFile)
FilePath = FileProvider.getUriForFile(this, FILE_AUTHORITY,tempFile)
Log.e("File Path", FilePath.toString())
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FilePath)
getPreviewImage.launch(takePictureIntent)
}
and change the provider path to this
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="picture" path="Android/data/com.example.njajal/files/Pictures"/>
</paths>
i hope my answer, help some people with the same problem
if any one using java so use it
define first it to oncreate method :
ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
Log.d("Capture_img", ": "+result.getData());
if (result.getResultCode()==Activity.RESULT_OK){
Intent intent = result.getData();
Uri uri = Objects.requireNonNull(intent).getData();
String path = uri.getPath();
File ff = new File("" +path);
String pffImage = ff.getName();
String path111 = GloabalMethods.imageCompressor(getContext(), path,pffImage);
File user_img = new File(""+path111);
Bitmap myBitmap = BitmapFactory.decodeFile(user_img.getAbsolutePath());
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG,80,bytes);
binaryImage = Base64.encodeToString(bytes.toByteArray(),Base64.DEFAULT);
Log.d("RRRRRRRRRRRRRRRR", "onActivityResult: "+uri);
capture_image.setImageBitmap(myBitmap);
capture_image.setTag("yes");
} after that call
ImagePicker.with(requireActivity()) .crop() //Crop image(Optional), Check Customization for more option .compress(1024)
//Final image size will be less thanMB(Optional)
.maxResultSize(1080, 1080).createIntent(intent -> { mStartForResult.launch(intent); return null; } );
Though I controlled it with an if statement I'm getting ''Given string empty or null'' error and my app is closing.
fun kayitOl ( view : View) {
val email =findViewById<EditText>(R.id.emailText).text
val password = findViewById<EditText>(R.id.passwordText).text
if (email != null && password != null ) {
auth.createUserWithEmailAndPassword(email.toString(), password.toString())
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val intent = Intent(this, haber_akisi::class.java)
startActivity(intent)
finish()
}
}.addOnFailureListener { exception ->
Toast.makeText(this, exception.localizedMessage, Toast.LENGTH_LONG).show()
}
}else {
Toast.makeText(this,"Lütfen E-mail ve Password alanlarını doldurunuz",Toast.LENGTH_LONG).show()
}
}
You check just for null, but not for empty string ""
You can change your checking with email.isEmpty() or better email.isBlank() for checking strings like " "
I have been trying to code a step tracker app. When I build the app, it doesn't show any errors but when I run it, it crashes and throws this:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
at com.example.fitnesstracker.MainActivity.loadData(MainActivity.kt:159)
at com.example.fitnesstracker.MainActivity.onCreate(MainActivity.kt:48)
I have implemented everything that I need but it won't start.
Here is the code for the saveData() and loadData() where I have the error:
private fun saveData() {
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putFloat("key1", previoustotalSteps)
editor.apply()
}
private fun loadData(){
val sharedPreferences= getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val savedNumber = sharedPreferences.getFloat("key1", 0f)
Log.d("MainActivity", "$savedNumber")
previoustotalSteps = savedNumber
}
These lines are after the setContentView in the onCreate method:
loadData()
resetSteps()
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
And these are the other functions that I use:
override fun onSensorChanged(event: SensorEvent?) {
if(running){
val stepstaken = findViewById<TextView>(R.id.steps_taken_id)
val progressBar = findViewById<CircularProgressBar>(R.id.circularProgressBar)
totalSteps = event!!.values[0]
val currentSteps = totalSteps.toInt() - previoustotalSteps.toInt()
stepstaken.text = currentSteps.toString()
progressBar.apply {
setProgressWithAnimation(currentSteps.toFloat())
}
}
}
private fun resetSteps(){
val stepstaken = findViewById<TextView>(R.id.steps_taken_id)
stepstaken.setOnClickListener {
Toast.makeText(this, "Long tap for step reset.", Toast.LENGTH_SHORT).show()
}
stepstaken.setOnLongClickListener {
previoustotalSteps = totalSteps
stepstaken.text = 0.toString()
saveData()
true
}
}
Also the step counter doesn't work. It stays at 0 no matter how much I move my phone.
Making basic reminder app. Can't figure out how to pass the actually reminder text so the notification actually displays the reminder instead of just having a blank notification.
In MainActivity, where alarm created
private fun startAlarm (cal : Calendar) {
val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent :Intent = Intent(this, AlertReceiver().javaClass)
val pendingIntent : PendingIntent = PendingIntent.getBroadcast(this, reqCode, intent, 0)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.timeInMillis, pendingIntent)
}
AlertReceiver
class AlertReceiver(): BroadcastReceiver() {
#RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context?, intent: Intent?) {
val notificationObj : Notification = Notification(context)
val notif : NotificationCompat.Builder = notificationObj.createNotification("")
notificationObj.getManager().notify(1, notif.build())
}
}
Notification, createNotification
fun createNotification(reminder: String): NotificationCompat.Builder{
//to load main screen when click notification
val main: Intent = Intent (this, MainActivity().javaClass).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingMain: PendingIntent = PendingIntent.getActivity(this, 0, main, 0)
val notif : NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, channelID)
.setSmallIcon(R.drawable.ic_android_black_24dp)
.setContentTitle("Reminder:")
.setContentText(reminder)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingMain)
.setAutoCancel((true))
return notif
}
I wrote a simple temperature converter app, everything is working fine except when user leaves EditText blank/null but selects one of the radio buttons, The App crashes.
Here is the Kotlin Code:
class MainActivity : AppCompatActivity() {
lateinit var etTemp: EditText
lateinit var radioGroup: RadioGroup
lateinit var btnConverter :Button
lateinit var tempConverted: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Zeeshan's Temperature Converter"
etTemp = findViewById(R.id.etTemp)
radioGroup = findViewById(R.id.radioGroup)
btnConverter = findViewById(R.id.btnConverter)
tempConverted = findViewById(R.id.tempConverted)
btnConverter.setOnClickListener {
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this#MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}
}
}
}
You should check if etTemp.text.ToString() == "" (that is empty string) if it is, then do not try to convert it into int. The problem appears when you try to convert "null" value to int.
Inside the listener add a check for for EditText to check whether it is empty or not,
btnConverter.setOnClickListener {
// Add the validation check here ... like this -> if(etTemp.length() > 0){
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this#MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}
// Close the check here -> }
else{
// Prompt the user to put some text in the field - this is called form validation before processing
// Toast.makeText(.....).show
}
}
check if the user has entered some input or not, one way is like below (Kotlin):
if(!etTemp.text.isNullOrEmpty())
{
temp =etTemp.text.toString().toInt()
}