0

I have an app that has an ImageView in it's MainActivity. And I'm trying to make it so that the image resets back to "backing" every midnight. So basically the user clicks the image, lets say, on May 24th and then the next time he opens the app it checks if it's a new day and resets the image to "backing". I managed to call up AlarmReceiver. But now whenever I'm trying to use cardback.setImageRes(R.drawable.backing) inside refreshdailycard() it throws a NullPointerException.

Any help would be appreciated.

Main Activity

 package com.example.godseye

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import android.app.AlarmManager
import android.content.Context
import android.app.PendingIntent
import android.app.PendingIntent.getActivity
import android.support.constraint.ConstraintLayout
import android.widget.ImageView
import android.widget.TextView
import com.example.godseye.R.id.imageView



class MainActivity : AppCompatActivity() {
    var dailycardshown=" "


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if(dailycardshown==" " )
        { cardback.setImageResource(R.drawable.backing) }
        if(cardback.drawable.constantState == resources.getDrawable(R.drawable.backing).constantState)
        { dailycardshown=" " }
        val singlecardintent = Intent(baseContext, SingleCard::class.java)
        val readingintent = Intent(baseContext, GetReading::class.java)
        val databaseintent = Intent(baseContext, TarotDatabase::class.java)
        val aboutintent = Intent(baseContext, ProjectAbout::class.java)
        cardback.setOnClickListener { _ ->
            if (dailycardshown == " ") {
                dailycardshown = choosedailycard()
                refreshdailycard()
                val res = resources
                val resID = res.getIdentifier(dailycardshown, "drawable", packageName)
                cardback.setImageResource(resID)
                setRecurringAlarm(baseContext)

            } else {
                singlecardintent.putExtra("card",dailycardshown)
                startActivity(singlecardintent)
            }
        }
        contrcontainer.setOnClickListener { _-> startActivity(readingintent) }
        database.setOnClickListener{ _-> startActivity(databaseintent)}
        aboutcontrainer.setOnClickListener { _-> startActivity(aboutintent)}
    }
    fun choosedailycard():String {
        val cardnames=resources.getStringArray(R.array.cardnames)
        var dailycard=ran(1,3)
        return cardnames[dailycard]


    }

    fun ran(from: Int, to: Int) : Int {
        val random = Random()
        return random.nextInt(to - from) + from
    }

    fun refreshdailycard(){
        dailycardshown= " "
    }

    private fun setRecurringAlarm(context: Context) {

        val updateTime = Calendar.getInstance()
        updateTime.timeZone = TimeZone.getTimeZone("GMT")
        updateTime.set(Calendar.HOUR_OF_DAY, 19)
        updateTime.set(Calendar.MINUTE, 54)
        val refresher = Intent(context, AlarmReceiver::class.java)
        val recurringDownload = PendingIntent.getBroadcast(context, 0, refresher, PendingIntent.FLAG_CANCEL_CURRENT)
        val alarms = baseContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.timeInMillis, AlarmManager.INTERVAL_DAY, recurringDownload)
    }

}

Alarm Receiver

package com.example.godseye

import android.content.Intent
import android.content.BroadcastReceiver
import android.content.Context
import android.util.Log


class AlarmReceiver : BroadcastReceiver()  {

    override fun onReceive(context: Context, intent: Intent) {
        Log.d(DEBUG_TAG, "Reccuring alarm for refresh backcard")
        val main = Intent(context, MainActivity::class.java)
        MainActivity().refreshdailycard()
    }

    companion object {

        private val DEBUG_TAG = "AlarmReceiver"
    }

}
CEO tech4lifeapps
  • 885
  • 1
  • 12
  • 31
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Chisko Jun 11 '18 at 00:08

2 Answers2

0

You mention this:

then the next time he opens the app

It means you don't need AlarmReceiver for this.

Beside, your AlarmReceiver code has lots of mistakes.

When Android System called your AlarmReceiver, it runs in the background and when it tries to call your MainActivity (which is not even started, because you just instantiate it as an object), of course it will throw NullPointerException.

Solution:

  1. Saved the last time User open your app in SharedPreferences (let's say it's called savedDate).

  2. Whenever the User open the app again, before you showed the image or daily cards, check whether it's still the same date with your savedDate in your SharedPreferences.

  3. If it's different day, you can use refreshdailycard(). If it's same, do whatever you want.

Yosi Pramajaya
  • 3,895
  • 2
  • 12
  • 34
0
MainActivity().refreshdailycard()

This is where you got it wrong. Your ImageView is a part of activity view which is drawn on to the screen when the activity is shown to the user not when you create an instance of activity. Doing it in AlaramManager is a wrong way of doing it. Follow the solution provided by the Yosi Pramajaya.

yeshu
  • 192
  • 1
  • 10