I'm having an issue where I've imported an import in order for a piece of code to work but no matter how many times I import the import, the code isn't recognizing that it's there. I've already tried invalidating and restarting, multiple times. I've read that another solution to this is to Sync with File System, but I don't appear to have that option under File.
The import in question is import java.text.MessageFormat.format
import android.content.ContentValues.TAG
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.squareup.okhttp.internal.http.HttpDate.format
import java.math.BigDecimal
import java.sql.Time
import java.sql.Timestamp
import java.text.DateFormat
import java.text.MessageFormat.format
import java.util.*
import kotlin.collections.ArrayList
class RemindersActivity : AppCompatActivity() {
lateinit var petID: String
val db = Firebase.firestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_reminders)
displayReminders()
petID = intent.getStringExtra("petID").toString()
val fab: View = findViewById(R.id.fab_reminders)
fab.setOnClickListener {
val intent = Intent(this, AddReminderActivity::class.java)
intent.putExtra("petID", petID)
startActivity(intent)
}
}
override fun onStart() {
super.onStart()
displayReminders()
}
private fun displayReminders() {
val recyclerview = findViewById<RecyclerView>(R.id.recyclerview_reminders)
recyclerview.layoutManager = LinearLayoutManager(this)
db.collection("pets").document(petID).collection("reminders").get().addOnSuccessListener { result ->
val data = mutableListOf<RemindersData>()
for (document in result) {
val title = document.data["title"].toString()
val timestamp = document.data["timestamp"] as Long
val cal = Calendar.getInstance()
cal.timeInMillis = timestamp * 1000L
val date = DateFormat.format("dd-MM-yyyy hh:mm:ss aa", cal).toString() //<- code note recognizing import is format
val frequency = document.data["frequency"].toString()
data.add(RemindersData(title, date, frequency))
}
val adapter = RemindersAdapter(data)
recyclerview.adapter = adapter
}.addOnFailureListener { e->
Log.w(TAG, "Error getting documents", e)
}
}
}
It just seems that you have added a few imports from the java packages instead of the android packages. It can happen when you use auto import in the IDE and there are multiple options and you click the wrong one.
When that happens you either have to undo the import or fix it manually.
Remove the import for
import java.text.DateFormat
Add the import for
import android.text.format.DateFormat
Afterwards, if there are any unused imports left, you can remove those as well.
Related
I'm trying to create a chart that displays sensor data from a cell phone in real time. I wrote a code for this, but the data was recorded, but the graph was recorded only on the same x-axis. The code is shown below. How should I solve this? If I need to create a separate thread, where should I add it?
package com.example.ex_linear_acc_graph
import android.content.Context
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.LinearLayout
import android.widget.TextView
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.concurrent.timer
class linearActivity : AppCompatActivity(), SensorEventListener {
private val mSensorManager by lazy {
getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
private lateinit var chart: LineChart
private lateinit var data: LineData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_linear)
chart = findViewById(R.id.chart_line)
chart.description.isEnabled = false
chart.setTouchEnabled(true)
chart.isDragEnabled = true
chart.setScaleEnabled(true)
chart.setPinchZoom(false)
chart.legend.form = Legend.LegendForm.LINE
chart.xAxis.position = XAxis.XAxisPosition.BOTTOM
chart.xAxis.setDrawLabels(true)
chart.xAxis.axisMaximum = 0f
chart.xAxis.setDrawAxisLine(true)
chart.xAxis.setDrawGridLines(false)
chart.axisRight.isEnabled = false
chart.legend.textColor = Color.WHITE
chart.animateXY(2000, 2000)
chart.invalidate()
data = LineData()
chart.data = data
}
override fun onResume() {
super.onResume()
mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)?.also{
linearacceleration -> mSensorManager.registerListener(
this,
linearacceleration,
SensorManager.SENSOR_DELAY_NORMAL,
SensorManager.SENSOR_DELAY_UI
)}
}
override fun onPause() {
super.onPause()
mSensorManager.unregisterListener(this)
}
override fun onSensorChanged(event: SensorEvent) {
var second : Float = 0f
timer(period = 1000, initialDelay = 1000){
second++
}
if(event.sensor.type == Sensor.TYPE_MAGNETIC_FIELD){
val mag_x = event.values[0]
val mag_y = event.values[1]
val mag_z = event.values[2]
val tv_mag : TextView = findViewById(R.id.tv_linear_acc)
tv_mag.text = "mag_x : ${mag_x}\nmag_y : ${mag_y}\nmag_z : ${mag_z}"
val dataSet = LineDataSet(listOf(Entry(second, mag_x), Entry(second, mag_y), Entry(second, mag_z)), "Accelerometer Data")
data.addDataSet(dataSet)
chart.notifyDataSetChanged()
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
// Do nothing
}
}
i'm practising a bit with kotlin and was testing Room and livedata, my app gets data from a json and the stores it in room, i want to move this network call to its own file and class, but if i do so the observer i set to get the changes don't trigger anymore, any help would be appreciated
here is a snipped of my mainactivity, if more is needed to know what happens please let me know
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.room.Room
import com.optiva.videoplayer.data.*
import com.optiva.videoplayer.network.GetData
import com.optiva.videoplayer.network.Networking
import com.optiva.videoplayer.network.RetrofitConnect
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dbcategories = Room.databaseBuilder(applicationContext, CategoriesDatabase::class.java,"categories.db").build()
val dbvideo = Room.databaseBuilder(applicationContext, VideosDatabase::class.java,"videos.db").build()
val retrofitData = RetrofitConnect.retrofitInst?.create(GetData::class.java)
val categoriesList = retrofitData?.getAll()
categoriesList?.enqueue(object: Callback<DataList> {
override fun onResponse(
call: Call<DataList>,
response: Response<DataList>
) {
val test = response?.body()
val cat = test?.categories
val vid = test?.videos
lifecycleScope.launch(Dispatchers.IO) {
if (cat != null) {
for(c in cat){
dbcategories.categoriesDAO().insertAll(CategoriesEntity(c.id,c.title,c.type))
}
}
if (vid != null) {
for(v in vid){
dbvideo.VideosDAO().insertAll(VideosEntity(v.id,v.thumb,v.videoUrl,v.categoryId,v.name))
}
}
}
}
override fun onFailure(call: Call<DataList>, t: Throwable) {
Toast.makeText(applicationContext,"error", Toast.LENGTH_LONG).show()
}
})
val textView: TextView = findViewById(R.id.test) as TextView
dbcategories.categoriesDAO().getALL().observeForever({categories ->
if(categories.size>0){
textView.text= categories[0].title
}
})
dbcategories.categoriesDAO().getALL().observe(this, {categories ->
if(categories.size>0){
textView.text= categories[0].title
}
}
} ```
So i was trying to get some text modifier with padding and it was all going good until I imported androidx.compose.foundation.layout.padding and the error on Modifier.padding(10.dp) didnt disapear, i tried searching if the import is moved/deprecated but i didnt see any changed releated to it. It also tells me the import isnt used so im really confused.
I use:
Android Studio - Arctic Fox 2020.3.1 canary 1
Kotlin Plugin - 1.4.10-Studio4.2-1\
My full code:
package com.example.weather
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.unit.dp
import androidx.ui.tooling.preview.Preview
import com.example.weather.ui.ExampleWeatherTheme
import java.lang.reflect.Modifier
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ExampleWeatherTheme {
Surface(color = MaterialTheme.colors.background) {
Column(modifier = Modifier.padding(10.dp)) {
FeelsLike(50)
}
}
}
}
}
}
#Composable
fun FeelsLike(feelstemp: Int) {
Text(text = "Feels Like: $feelstempĀ°")
}
#Composable
fun Temperature(temp: Int) {
Text(text = "$temp")
}
#Preview(showBackground = true)
#Composable
fun BasicPreview() {
ExampleWeatherTheme(darkTheme = true) {
FeelsLike(50)
}
}
This is your issue:
import java.lang.reflect.Modifier
You are importing the wrong Modifier class. It happened to me and the error can be quite missleading. Change the import to:
import androidx.compose.ui.Modifier
Hi everyone!
This is my code. I want to download a file from a web server.
The file is downloaded and stored, but in Downloads dir of Android Emulator device there are two files.
Why?
Can anyone help me please? *
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import java.io.File
class MainActivity : AppCompatActivity() {
var my_download_id : Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val text : TextView = findViewById(R.id.Text)
val button : Button = findViewById(R.id.Button)
button.setOnClickListener{
val request = DownloadManager.Request(
Uri.parse("https://my3xample.org/file.csv"))
.setTitle("FileExample")
.setDescription("File Example Downloading")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setAllowedOverMetered(true)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"Example.csv")
val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
my_download_id = dm.enqueue(request)
}
val br = object:BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if(id == my_download_id){
Toast.makeText(applicationContext, "Example File Download Completed", Toast.LENGTH_LONG).show()
}
}
}
registerReceiver(br, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
}
This is the Downloads Dir when I download the file.
Downloads Dir Screen
I'm trying to understand view models using kotlin for android, and I'm running into some difficulty. I have a very simple dummy app which allows a user to increment a number and then send that number to a second screen. That second screen will then display a random number between 0 and the sent number.
Here is the problem.
I understand how to send the data from the first page to the second using intents, and I know how to make a viewmodel in the second page. However, if I send the intent and then set the viewmodel equal to the set intent, it doesnt function properly. Rotating the screen will cause the intent to be resent and the viewmodel doesnt maintain the state of the data (the number rerandomizes).
Ideally, I'd like to just be able to just update the viewModel class in place of sending the intent, but the instance of the class is created when the second page is created, so that doesn't work.
Any ideas?
Based on the google codelabs "build my first android app" tutorial.
Here's my code; first page:
package com.example.patientplatypus.babbysfirstandroidapp
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.textView
import org.jetbrains.anko.db.PRIMARY_KEY
import org.jetbrains.anko.db.UNIQUE
import org.jetbrains.anko.db.createTable
import android.database.sqlite.SQLiteDatabase
import android.support.v4.content.ContextCompat.startActivity
import com.example.patientplatypus.babbysfirstandroidapp.R.id.textView
import org.jetbrains.anko.db.*
import org.jetbrains.anko.indeterminateProgressDialog
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main);
}
fun toastMe(view: View) {
val myToast = Toast.makeText(this, "Hello Toast!", Toast.LENGTH_SHORT)
myToast.show()
}
fun countMe (view: View) {
Log.d("insideCountMeCheck", "hey you are inside count me!")
val countString = textView.text.toString()
var count: Int = Integer.parseInt(countString)
count++
textView.text = count.toString()
}
fun randomMe (view: View) {
val randomIntent = Intent(this, SecondActivity::class.java)
val countString = textView.text.toString()
val count = Integer.parseInt(countString)
randomIntent.putExtra(SecondActivity.TOTAL_COUNT, count.toString())
startActivity(randomIntent)
}
}
Here's my code, second page:
package com.example.patientplatypus.babbysfirstandroidapp
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import java.util.*
import kotlinx.android.synthetic.main.activity_second.randomText
class CountViewModel : ViewModel() {
var TOTAL_COUNT = "total_count"
}
class SecondActivity : AppCompatActivity() {
lateinit var countModel: CountViewModel
companion object {
const val TOTAL_COUNT = "total_count"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.activity_second)
countModel = ViewModelProviders.of(this).get(CountViewModel::class.java)
countModel.TOTAL_COUNT = intent.getStringExtra(TOTAL_COUNT)
displayForRandomNum(countModel.TOTAL_COUNT);
showRandomNumber()
}
fun showRandomNumber() {
val count = countModel.TOTAL_COUNT.toInt()
val random = Random()
var randomInt = 0
if (count > 0) {
randomInt = random.nextInt(count + 1)
}
Log.d("randomFinal", Integer.toString(randomInt))
displayForRandomNum(Integer.toString(randomInt))
}
fun displayForRandomNum(totalCount: String){
randomText.text = totalCount
}
}
An orientation change causes the activity be destroyed then recreated. This means onCreate will be called on every rotate. The same intent that started the activity originally would still be available to it. So intent.getStringExtra(TOTAL_COUNT) would return the original value from the intent that start the activity every time the screen is rotated. ViewModel will retain the data through the rotation though.
Your issue is that your overriding you're ViewModel'sTOTAL_COUNT with the original value from the intent every time. What you can do is check that the TOTAL_COUNT value isn't "total_count" (meaning its already been set from the intent) before setting it in onCreate.