Search code examples
androidandroid-preferencesandroid-sharedpreferences

ImageButton and SharedPreferences / Preferences


I want to allow the user to select a website from Preferences in my Android app. But when user choose a website from preferences list , imagebutton's image and its loadurl code must change.The image and loadurl should then remain the same even if the app closes.

now i ve preferences menu and values.but how can i change imagebutton's image and its url i dont know. thank you.


Solution

  • Just save the info to shared preferences, then use an if statement to load the shared preferences. as in

    if (preferences == websiteOne){
    //load shared preferences  for websiteOne here
    } else {
    // load shared preferences for websiteTwo here
    }
    

    If you have more than two websites, you can set up a switch/case

    EDIT

    switch (website){
    case websiteOne:
    // shared preferences for websiteOne
    imageView.setImageResource(imageResourceFromSharedPreferences);
    url.setText(urlFromSharedPreferences)
    break;
    case websiteTwo:
    // shared preferences for websiteTwo
    break;
    }
    

    Do that for all 10 websites

    EDIT 2

    to set up a default sharedPreferences, in your onCreate() of an early activity, you can use

    data = getSharedPreferences(filename, 0);
    SharedPreferences.Editor e = data.edit();
            e.putString("website", websiteVariable);
            e.commit();
    

    Do the same for the URL, and add these two variables SharedPreferences data; and public static String filename = "fileName";