SharedPreference instanciation

Résolu/Fermé
lukas6410 Messages postés 25 Date d'inscription mardi 24 mars 2020 Statut Membre Dernière intervention 19 mai 2021 - Modifié le 29 mars 2020 à 09:26
BunoCS Messages postés 15472 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 25 mars 2024 - 30 mars 2020 à 09:37
Bonjour,
je doit sauvegarder des donnés dans mon activité ,pour ça j'ai utilisé les SharedPreference ,j'ai fait des recherches et apparemment j'aurai instancié la variable au mauvaise endroit je vous donne mon code ainsi que les logs pouvez vous m'aider merci je tien à préciser que je suis sous kotlin

package com.example.coockiemania

import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity() {
    val sharedPreference: SharedPreferences =  getSharedPreferences("SAUVEGARDES",0)
    private val editor = sharedPreference.edit()
    private var compteur = sharedPreference.getInt("nbr_click",0)


    private var set_click_par_sec = 0
    private var recup_click_par_sec = 0
    private val ameliorationsPrix = Ameliorations_prix(amel1 = 10,amel2 = 100,amel3 = 1000)
    private val nombreAmel = Nombre_amelioration(nbr_amel1 = sharedPreference.getInt("amel1_nbr",0),nbr_amel2 = sharedPreference.getInt("amel2_nbr",0),nbr_amel3 = sharedPreference.getInt("amel3_nbr",0))
    private var parSecAmel= Par_sec_amel(amel1 = 1000,amel2 = 2000,amel3 = 5000)
    private val myHandler: Handler = Handler()

    private val myRunnable = object : Runnable {
        override fun run() {
            compteur + sharedPreference!!.getInt("click_par_sec",0)
            compteur_click.text = compteur.toString()+"click"
            myHandler.postDelayed(this,500)
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //compter par_sec
        val myHandler = Handler()
        myHandler.postDelayed(myRunnable,500)
        //define listView
        val listView = findViewById<ListView>(R.id.list_amel)
        val listAmeliorations = listOf<String>(
            "amelioration 1 : +1 click per sec"+ "prix :"+ (ameliorationsPrix.amel1.toString())+(nombreAmel.nbr_amel1.toString()),
            "amelioration 2 : +2 click per sec"+ "prix :"+ (ameliorationsPrix.amel2.toString())+(nombreAmel.nbr_amel2.toString()),
            "amelioration 3 : +3 click per sec"+ "prix :"+ (ameliorationsPrix.amel3.toString())+(nombreAmel.nbr_amel3.toString())
        )
        val adapterView = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listAmeliorations)
        listView.adapter = adapterView
        //reagir au clic d'un element listview
        listView.setOnItemClickListener{parent, view, position, id ->
            if (position==0){
                Toast.makeText(this,"amelioration 1 selectionner",Toast.LENGTH_SHORT).show()
                if (compteur < ameliorationsPrix.amel1){
                    Toast.makeText(this,"achat reussi",Toast.LENGTH_SHORT).show()
                    compteur -= ameliorationsPrix.amel1
                    nombreAmel.nbr_amel1 + 1


                }
            }
            if (position==1){
                Toast.makeText(this,"amelioration 2 selectionner",Toast.LENGTH_SHORT).show()
                if (compteur < ameliorationsPrix.amel2){
                    Toast.makeText(this,"achat reussi",Toast.LENGTH_SHORT).show()
                    compteur -= ameliorationsPrix.amel2
                    nombreAmel.nbr_amel2 + 1

                }
            }
            if (position==2){
                Toast.makeText(this,"amelioration 3 selectionner",Toast.LENGTH_SHORT).show()
                if (compteur < ameliorationsPrix.amel3){
                    Toast.makeText(this,"achat reussi",Toast.LENGTH_SHORT).show()
                    compteur = compteur - ameliorationsPrix.amel3
                    nombreAmel.nbr_amel3 + 1

                }
            }
        }
        //imagelistener
        val imageView = findViewById<ImageView>(R.id.imageView)
        val compter_click = findViewById<TextView>(R.id.compteur_click)
        imageView.setOnClickListener {
            ++compteur
            compter_click.text = compteur.toString()+"click"
        }
        //ajoute textviex click_par_sec
        recup_click_par_sec = ((nombreAmel.nbr_amel1*parSecAmel.amel1)+(this.nombreAmel.nbr_amel2*this.parSecAmel.amel2)+(this.nombreAmel.nbr_amel1*this.parSecAmel.amel1))
        set_click_par_sec = recup_click_par_sec
        val textView_click_sec = findViewById<TextView>(R.id.click_par_sec)
        textView_click_sec.setText(set_click_par_sec.toString())

    }

    override fun onPause() {
        super.onPause()
        //savegardes


        //ajoute click par sec
        editor.putInt("click_par_sec",set_click_par_sec)
        //ajoute nbr_amel
        editor.putInt("amel1_nbr",nombreAmel.nbr_amel1)
        editor.putInt("amel2_nbr",nombreAmel.nbr_amel2)
        editor.putInt("amel3_nbr",nombreAmel.nbr_amel3)
        editor.putInt("nbr_click",compteur)
        editor.commit()

    }

    override fun onResume() {
        super.onResume()

    }

    override fun onStop() {
        super.onStop()
        if (myHandler != null){
            myHandler.removeCallbacks(myRunnable)}


    }

    override fun onRestart() {
        super.onRestart()
        myHandler.postDelayed(myRunnable,500)
    }
}


et voici la console debug


E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.coockiemania, PID: 12732
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coockiemania/com.example.coockiemania.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

1 réponse

BunoCS Messages postés 15472 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 25 mars 2024 3 894
30 mars 2020 à 09:37
Hello,

Il faut le faire à partir d'un context créé, ou bien d'une instance d'Activity. Mets donc ta déclaration dans le onCreate(), ça fonctionnera mieux
0