0

I would like to add multiple dynamic buttons. Their texts are saved in SharedPreferences.

LinearLayout layout = view.findViewById(R.id.root);
SharedPreferences mPrefs = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
    mPrefs = getContext().getSharedPreferences("k-texts", Context.MODE_PRIVATE);
}
Map<String, ?> allEntries = mPrefs.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
    Button btn = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        btn = new Button(this.getContext());
    }
    btn.setText(entry.getValue().toString());
    btn.setTextColor(Color.BLUE);
    btn.setBackgroundColor(Color.RED);
    layout.addView(btn);
}

The problem is, I get only 1 button with the text ["1","2","3"]. Why is my loop adding only 1 button, instead of 3?

xRay
  • 543
  • 1
  • 5
  • 29

1 Answers1

0

This is how I could do it:

LinearLayout layout = view.findViewById(R.id.root);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    for(String text : readFromSharedPreferences(getContext())) {
        Button btn = new Button(this.getContext());
        btn.setText(text);
        btn.setTextColor(Color.BLUE);
        btn.setBackgroundColor(Color.RED);
        layout.addView(btn);
    }
}

Using Gson to store all data in an ArrayList:

public ArrayList<String> readFromSharedPreferences(Context context) {
    String file = "k-texts";
    SharedPreferences mPrefs = context.getSharedPreferences(file, Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = mPrefs.getString("k-text", null);
    Type type = new TypeToken<List<String>>() {
    }.getType();
    return gson.fromJson(json, type);
}
xRay
  • 543
  • 1
  • 5
  • 29