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
Related
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.
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
}
}
} ```
I'm trying to pass data from a RecyclerView that contains a list of photos to a separate Activity that should show Details about the selected photo.
since im new to Kotlin, i've tried a lot and failed to come up with a solution.. I'd be thankful if anyone has a word on this.
PhotosActivity.kt
package com.example.wallpaperapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class PhotosActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_photos)
val recyclerPhotos = findViewById<RecyclerView>(R.id.rv_photo)
recyclerPhotos.layoutManager = LinearLayoutManager(this)
recyclerPhotos.adapter = PhotosAdapter(getPhotosData(), this)
}
private fun getPhotosData(): List<PhotoModel>{
return listOf(
PhotoModel(R.drawable.photo1),
PhotoModel(R.drawable.photo2),
PhotoModel(R.drawable.photo3),
PhotoModel(R.drawable.photo4),
PhotoModel(R.drawable.photo5),
PhotoModel(R.drawable.photo6),
PhotoModel(R.drawable.photo7),
PhotoModel(R.drawable.photo8)
)
}
}
PhotosModel.kt
package com.example.wallpaperapp
import java.io.Serializable
data class PhotoModel(
val image: Int,
): Serializable
PhotosAdapter.kt
package com.example.wallpaperapp
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
class PhotosAdapter(val listOfPhotos: List<PhotoModel>,
val context: Activity): RecyclerView.Adapter<PhotosAdapter.ViewHolder>() {
inner class ViewHolder(view: View): RecyclerView.ViewHolder(view){
val img = view.findViewById<ImageView>(R.id.img_test)
init{
itemView.setOnClickListener {
val intent = Intent(context, PhotoDetailsActivity::class.java)
intent.putExtra("PHOTO", listOfPhotos[adapterPosition])
context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotosAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_photo, parent,false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return listOfPhotos.size
}
override fun onBindViewHolder(holder: PhotosAdapter.ViewHolder, position: Int) {
holder.img.setImageResource(listOfPhotos[position].image)
}
}
PhotoDetailsActivity.kt
package com.example.wallpaperapp
import android.app.WallpaperManager
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat.setBackground
class PhotoDetailsActivity : AppCompatActivity() {
lateinit var arrow: ImageView
lateinit var img: ImageView
lateinit var btn_set: Button
lateinit var bitmap: Bitmap
lateinit var manager: WallpaperManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_photo_details)
val selectedPhoto = intent.extras?.getSerializable("PHOTO") as PhotoModel
arrow = findViewById(R.id.img_arrow)
arrow.setOnClickListener {
val intent = Intent(this, PhotosActivity::class.java)
startActivity(intent)
}
img = findViewById(R.id.img_detail)
btn_set = findViewById(R.id.btn_wallpaper)
btn_set.setOnClickListener(View.OnClickListener {
fun setOnClickr(l: (View) -> Unit){
setBackgroundd()
}
})
}
fun setBackgroundd() {
val bitmap = BitmapFactory.decodeResource(resources, R.layout.activity_photos)
img.setImageBitmap(bitmap)
manager = WallpaperManager.getInstance(getApplicationContext())
manager.setBitmap(bitmap)
}
}
thanks in advance!
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.
I am having trouble ScrollBar it shows error when I add it in a Kotlin class. Import library is also showing an error. What should I do? Below is the code:
import android.widget.Toast
import com.github.barteksc.pdfviewer.PDFView
import com.github.barteksc.pdfviewer.ScrollBar
import kotlinx.android.synthetic.main.activity_pdf.view.*
import java.io.File
class PDF_Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pdf)
val pdfView = findViewById(R.id.pdfView) as PDFView
val scrollBar = findViewById<ScrollBar>(R.id.scrollBar)
pdfView.setScrollBar(scrollBar)
scrollBar.setHorizontal(false)
val i = this.intent
val path = i.extras!!.getString("PATH")
val file = File(path!!)
if (file.canRead()) {
pdfView.fromFile(file).defaultPage(1).onLoad { nbPages -> Toast.makeText(this#PDF_Activity, nbPages.toString(), Toast.LENGTH_LONG).show() }.load()
}