Malopieds
Malopieds

Reputation: 393

Shared Preferences in Fragment with Kotlin

I'm making a counter app in Android using Kotlin. My code is working great in MainActivity but when it comes to fragment it's not working anymore.

class HomeFragment : Fragment()
{
    private lateinit var homeViewModel: HomeViewModel

    @SuppressLint("SetTextI18n")
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?
    {
        /*homeViewModel =
                ViewModelProvider(this).get(HomeViewModel::class.java)*/
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        val textView: TextView = root.findViewById(R.id.text_home)
        val button: Button = root.findViewById<Button>(R.id.button)
        var nombre = PrefConfing.loadTotalFromPref(this)
        button.setOnClickListener {
            nombre++
            textView.text = "vous l'avez fait $nombre fois"
            PrefConfing.saveTotalTimes(applicationContext, nombre)
        }

        return root
    }
}

This is my Kotlin HomeFragment code, and there is my Java code:

public class PrefConfing {
    private static final String TIMES = "com.example.alllerrr";
    private static final String PREF_TOTAL_KEY = "pref_total_key";

    public static void saveTotalTimes(Context context, int total) {
        SharedPreferences pref = context.getSharedPreferences(TIMES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putInt(PREF_TOTAL_KEY, total);
        editor.apply();
    }

    public static int loadTotalFromPref(Context context){
        SharedPreferences pref = context.getSharedPreferences(TIMES, Context.MODE_PRIVATE);
        return pref.getInt(PREF_TOTAL_KEY, 0);
    }
}

for the var nombre I can't add this to the context and I don't understand why.

Upvotes: 1

Views: 1985

Answers (2)

AMK
AMK

Reputation: 836

You'll know why:

If you chase inheritance of Activity class you'll find out that it inherits Context class so passing "this" has no problem, But when you chase Fragment class inheritance (androidx.fragment.app.Fragment), you'll never find that class inherits Context, so it's not acceptable to pass "this" as Context.

Actually getContext and requireContext returns their host's context, so you need to use them instead.

requireContext: returns a nonnull Context, or throws an exception when one isn't available.

getContext: returns a nullable Context.

see more about difference between "getContext" and "requireContext".

Upvotes: 1

iknow
iknow

Reputation: 9862

If in line

var nombre = PrefConfing.loadTotalFromPref(this)

You are getting:

Type mismatch.
Required: Context!
Found: HomeFragment

You have to do it like this:

var nombre = PrefConfing.loadTotalFromPref(requireContext())

Upvotes: 1

Related Questions