2

I have a problem with saving the ImageButton in SharedPreferences.

Basically, I have a special REFRESH button:

     bbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {... }

and when clicking on it, it creates another ImageButton in a HorizontalScrollView's LinearLayout with background called "a" from drawables folder. That new generated ImageButton will have its own onClick function. However, before creating it there is no ImageButton in that activity, it will appear in a "LinearLayoutScrollView" only after clicking on the special REFRESH button with a couple of "if and else if" statements which will generate ImageButtons with different drawable backgrounds.

All I want is that after creating new ImageButton (with its own background from drawables) it would stay in the app till the user deletes the app or the ImageButton itself. However, I want to see saved ImageButton even after restarting the app.

What I am trying to do now is shown below but it does not work so probably I am doing something wrong. Maybe anyone knows what I need to change?

Right in the end I am using SharedPreferences code to save newly created ImageButton with background of drawable "a". And after that else if follows a few more else if's which are basically the same as the one in the top only with different drawable backgrounds for different selections which I get as url's from intents in another activity...

EDITED according to your advice (but still it doesnt save the image):

                final SharedPreferences prefs  = getSharedPreferences("MySavedHomeFile", MODE_PRIVATE);
                final LinearLayout Row = (LinearLayout) findViewById(R.id.LinearLayoutScrollView);

            bbutton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

            Intent a = getIntent();
            Intent b = getIntent();
            String url1 = a.getStringExtra("url1");
            String url2 = b.getStringExtra("url2");                         
                if (url1 == null && url2 == null && url3 == null) {
                Toast.makeText(getApplication(), "No new clients added!", Toast.LENGTH_SHORT).show();
            } else if (url1 != null) {
                int backgroundRes = prefs.getInt("savedImageButton" , R.drawable.a);
                final ArrayList<String> Keys = new ArrayList<String>();
                for(int ii = 0; ii < 1; ii ++){
                    Keys.add("Keys is : " + String.valueOf(ii));
                }

                LinearLayout Row = (LinearLayout) findViewById(R.id.LinearLayoutScrollView);

                int width = 240;
                int height = 240;

                final ImageButton[] my_button = new ImageButton[Keys.size()];

                for (int bt = 0; bt < Keys.size(); bt ++) {
                    final int Index = bt;

                    my_button[Index] = new ImageButton(HomePageNews.this);

                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, height);
                    lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, R.id.imageButton11);

                    my_button[Index].setLayoutParams(lp);
                    my_button[Index].setId(Index);
                    my_button[Index].setBackgroundResource(backgroundRes);

                    my_button[bt].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (my_button[Index].getId() == ((ImageButton) v).getId()) {

                            }
                        }
                    });

                    Row.addView(my_button[Index]);
                }

                SharedPreferences saveNewHome = getSharedPreferences("MySavedHomeFile", MODE_PRIVATE);
                SharedPreferences.Editor editor = saveNewHome.edit();
                editor.putInt("savedImageButton", R.drawable.a);
                editor.apply();

            }else if (url2 != null) {
                int backgroundRes = prefs.getInt("savedImageButton" , R.drawable.b) ;
                final ArrayList<String> Keys2 = new ArrayList<String>();
                for(int ee = 0; ee < 1; ee ++){
                    Keys2.add("Keys is : " + String.valueOf(ee));
                }

                LinearLayout Row2 = (LinearLayout) findViewById(R.id.LinearLayoutScrollView);

                int width = 240;
                int height = 240;

                final ImageButton[] my_button2 = new ImageButton[Keys2.size()];

                for (int bt2 = 0; bt2 < Keys2.size(); bt2 ++){
                    final int Index2 = bt2;

                    my_button2[Index2] = new ImageButton(HomePageNews.this);

                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, height);
                    lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, R.id.imageButton11);

                    my_button2[Index2].setLayoutParams(lp);
                    my_button2[Index2].setId(Index2);
                    my_button2[Index2].setBackgroundResource(backgroundRes);

                    my_button2[bt2].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (my_button2[Index2].getId() == ((ImageButton) v).getId()){

                            }
                        }
                    });

                    Row2.addView(my_button2[Index2]);
                }


                SharedPreferences prefs = getSharedPreferences("MySavedHomeFile", MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("savedImageButton", R.drawable.b);
                editor.apply();
Liutavaras
  • 31
  • 4
  • you need to save a condition for that View and then Create it If the the condition occurs. – Elias Fazel Apr 20 '17 at 23:21
  • I have a condition, this is not a full code, I will edit and submit the whole button with if and else if statements for you to get a better idea. :) – Liutavaras Apr 20 '17 at 23:35
  • 1
    I don't get it. You are trying to encode a drawable as a string and save it in an XML file? – Jeffrey Blattman Apr 20 '17 at 23:41
  • You'd have to serialize a Bitmap to a byte array... But realistically SharedPrefences are not what you want. You can write a Bitmap to disk and persist the image that way – OneCricketeer Apr 20 '17 at 23:44
  • I am trying to generate ImageButtons using different if else statements which will mean different backgrounds (drawables) depends on user selections in another activity. I should actually save a generated ImageButton, however I need to keep its special drawable background with it and it will depend on which image URL selection user made in previous activity. I hope it helps, its a bit complicated... :/ – Liutavaras Apr 20 '17 at 23:47
  • @cricket_007 Maybe you have any examples of how I could do that? Or anything similar? – Liutavaras Apr 20 '17 at 23:52
  • You can save the R.drawable value as an integer. All I'm saying is that a Bitmap image shouldn't be saved in SharedPreferences – OneCricketeer Apr 20 '17 at 23:54
  • @cricket_007 so it means that what I am doing right now in the end of my code is not okay, as I am trying to: editor.putString("savedImageButton", String.valueOf(getResources().getDrawable(R.drawable.a))); ? Sorry I am not really experienced in this. – Liutavaras Apr 20 '17 at 23:57
  • I don't think your edits make the code compile... You have two prefs variables and two Row variables – OneCricketeer Apr 21 '17 at 13:35

1 Answers1

0

Don't store the whole image. Just store the resource that creates the drawable

  editor.putInt("savedImageButton", R.drawable.a);

Then, get it out

// move this outside of the button setOnClickListener 
final SharedPreferences prefs  = getSharedPreferences("MySavedHomeFile", MODE_PRIVATE);
final LinearLayout Row = (LinearLayout) findViewById(R.id.LinearLayoutScrollView);

When you create the button...

// Getting the drawable 
int backgroundRes = prefs.getInt("savedImageButton" , R.drawable.a) ;
// setting the imagebutton 
my_button[Index].setBackgroundResource(backgroundRes);

That new generated ImageButton will have its own onClick function.

There are ways to setup one OnClickListener interface that all buttons share. You simply would need to dynamically use the necessary data in each button's event


Not really sure what you're trying to do here, though.

Every click of bbutton, you create an empty list, empty array, and brand new buttons (well, one button since there's only one element in Keys)

Also this is always true. Casting to an ImageButton does nothing. if (my_button[Index].getId() == ((ImageButton) v).getId())

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Okey, so it means that by doing that I am storing the background of the ImageButton. Then maybe you know how do I call this saved imagebutton with its background back in this activity to see it in a HorizontalScrollView after I restart my app? – Liutavaras Apr 21 '17 at 00:03
  • I'm not sure what that means. This will only allow you to save one image for the entire app, not one per button. I'm not sure if that's the intended function, but my answer is simply a replacement for your `String.valueOf(getResources().getDrawable` – OneCricketeer Apr 21 '17 at 00:05
  • If you need a different image on the button, you need to get a different image and fix `my_button[Index].setBackgroundResource(R.drawable.a)` to use the new value, as I've shown – OneCricketeer Apr 21 '17 at 00:07
  • I see now, thank you, but do you know the code to get it back, I think its something very similar to storing? And where do I put this "int backgroundRes = ", do I put it in the button with if statements? Or just in activities view? – Liutavaras Apr 21 '17 at 00:08
  • The preferences can be a global variable. And getting is very similar yes http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values – OneCricketeer Apr 21 '17 at 00:14
  • I see, its getting a lot clearer, thank you so much!!! But if I change setBackgroundResource(R.drawable.a) to my_button[Index].setBackgroundResource(backgroundRes); then after clicking first time on the REFRESH button the created ImageButton wont show up? – Liutavaras Apr 21 '17 at 00:25
  • I don't know why the refresh button is necessary or where that's in the question – OneCricketeer Apr 21 '17 at 00:32
  • Also, you're only ever setting and getting drawable `a` in the question, so I don't see why it should be anything different – OneCricketeer Apr 21 '17 at 00:33
  • Hello again, I will edit my code now for you to see exactly what I am doing. – Liutavaras Apr 21 '17 at 09:10
  • I have just tried your code and it does not store ImageButton neither with a nor with b drawable. I think its because (as you can see in edited code above) I am saving the resource not the newly generated ImageButton so even if I actually save the background, after restarting the app, it does not know where to put it - as the ImageButton is gone. then... – Liutavaras Apr 21 '17 at 09:53
  • **`editor.putInt("savedImageButton", R.drawable.a);` is terrible idea** ... it should be `editor.putString("savedImageButton", getResources().getResource(Entry)Name(R.drawable.a));` as resource int id may changewith next build, which could make next version not compatible with current setting stored in shared preferences – Selvin Apr 21 '17 at 11:19
  • @Selvin what do you mean by .getResource(Enrty)Name? What should I put there, as it shows an error – Liutavaras Apr 21 '17 at 11:23
  • `getResourceName` or `getResourceEntryName` method depends on your needs then use `getIdentifier` for optain int id from string id – Selvin Apr 21 '17 at 11:24
  • Could you tell me what is the difference between them? And I change it in storing data part in else if's, but should I change anything in the beginning of the code when I receive it? – Liutavaras Apr 21 '17 at 11:27
  • It does not work, how do you put getIdentifier in retrieving part? – Liutavaras Apr 21 '17 at 11:34
  • @Selvin I don't think OP is really caring about future code compatibility at the moment. If you are following the whole thread, storing the actual image in SharedPreferences is also a terrible idea. I simply felt like this was the lesser of the terrible ideas – OneCricketeer Apr 21 '17 at 13:32
  • @cricket_007 Okey, so do you have any other suggestions of how I could save that button which is created after pressing on the button? Thanks! – Liutavaras Apr 21 '17 at 14:23
  • @Liutavaras I don't know what "saving a button" means. All you should be saving is the data required to generate the view when the Activity is recreated. I also don't know what `url1` or `url2` are in the question, you have two calls to `getIntent()`, and as stated, you are re-creating practically everything when you click on a `bbutton`... so your code doesn't make sense to me, sorry. Maybe if you edit your question to include a screenshot of what you're seeing vs expecting, that would help – OneCricketeer Apr 21 '17 at 15:11