1

I have this nested view created from another activity. The values (texts to show, background color, etc) mainly are inputted by the user from the other activity. Here is the code on how I dynamically create the views:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {

                // Create a New Linear Layout
                LinearLayout ll = new LinearLayout(this);
                ll.setOrientation(LinearLayout.VERTICAL);
                LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);

                float scale = getResources().getDisplayMetrics().density;
                //Set Bottom Margin
                float margin = 5; //RESIZE BOTTOM MARGIN HERE!
                int margs = (int) (margin * scale + 0.5f);

                //Set padding in dp
                float padding = 5; //RESIZE PADDING HERE!
                int pads = (int) (padding * scale + 0.5f);
                llParams.setMargins(0,0,0,margs);

                //Set Parameters for Android
                ll.setLayoutParams(llParams);
                ll.setPadding(pads, pads, pads, pads);

                //Set Background Color on Layout
                String chosenColor = data.getStringExtra("sendChosenColor");
                if (chosenColor.equals("Green")){
                    ll.setBackgroundResource(R.color.HoloGreen);
                }else if (chosenColor.equals("Blue")){
                    ll.setBackgroundResource(R.color.HoloBlue);
                }else if (chosenColor.equals("Gray")){
                    ll.setBackgroundResource(R.color.HoloGray);
                }else if (chosenColor.equals("Orange")){
                    ll.setBackgroundResource(R.color.HoloOrange);
                }else {
                    ll.setBackgroundResource(R.color.HoloYellow);
                }

                //Adding Layout to Appropriate Container
                int layoutCountLeft = subjectLeft.getChildCount();
                int layoutCountRight = subjectRight.getChildCount();

                if (layoutCountLeft <= layoutCountRight){
                    subjectLeft.addView(ll);
                } else {
                    subjectRight.addView(ll);
                }

                //Create TextView for SubjectName
                TextView SubjectName = new TextView(this);
                SubjectName.setText(data.getStringExtra("sendSubjectName"));
                SubjectName.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                SubjectName.setTextSize(22);
                SubjectName.setTypeface(Typeface.DEFAULT_BOLD);

                //Create TextView for SubjectNumber
                TextView SubjectNumber = new TextView(this);
                SubjectNumber.setText(data.getStringExtra("sendSubjectNumb"));
                SubjectNumber.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                SubjectNumber.setTextSize(16);


                //Creating the divider line
                ImageView divider = new ImageView(this);
                LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2);
                divider.setLayoutParams(dividerParams);
                divider.setBackgroundResource(R.color.Black);

                //Add Views into the Layout
                ll.addView(SubjectNumber);
                ll.addView(SubjectName);
                ll.addView(divider);

        }
    }
}

Can I save this without using databases?

DirkJan
  • 581
  • 2
  • 7
  • 22
  • You can do this with SharedPreferences. Check http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values – longi May 22 '13 at 16:46
  • SharedPrefs are used for key-value pairs, I think. How can I implement the Shared Prefs in saving nested views. – DirkJan May 22 '13 at 17:24
  • maybe i misunderstood your question, but instead of save your view, you only save the values to create your view and recreate the view if needed?! – longi May 22 '13 at 17:35
  • i don't know how many views you like to store, but for example you can create JSON-Object with all your values (background, texts), and save your JSON-Object.toString() in your SharedPreferences as a String....or a list of JSON-Objects if you need to save several different views... – longi May 22 '13 at 17:38

2 Answers2

1

The key for save / restore is a unique id.

Only views with id set (either on xml files or dynamically created) can hold their state on configuration changes, such as device rotation.

File CustomTextView.java

package example;

import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomTextView extends TextView {

    private static final String INSTANCE_STATE = "instance_state";
    private static final String VALUE          = "value";

    private int value;

    public CustomTextView(Context context) {
        this(context, null);
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // init ...
        setId(R.id.custom_view);
        value = 123;
    }

    // methods ...

    @Override
    public Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
        bundle.putInt(VALUE, value);
            // other fields...
        return bundle;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            value = bundle.getInt(VALUE);
                    // other fields...

            state = bundle.getParcelable(INSTANCE_STATE);
        }
        super.onRestoreInstanceState(state);
    }
}

An easy way to get a unique id is statically.

File ids.xml (in res/values)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="custom_view" />
</resources>
KitKat
  • 1,495
  • 14
  • 15
0

You have 4 possibilities to save data on Android devices: SharedPreferences, DB, File or a server. See here for more information.

SimonSays
  • 10,867
  • 7
  • 44
  • 59
  • What do you think is the most appropriate method to do this in my case, which is a nested view? – DirkJan May 22 '13 at 17:12
  • That really depends on your app. it does sound though as if SharedPrefs would be the best solution in that case. also, as longilong mentions, do not save the whole View, only save the values that can change, like text or colors, and recreate the view when your app starts again. – SimonSays May 22 '13 at 17:39
  • Oh, okay. I get the idea. One more question. How will I get the data from numerous views and how do I recreate the views? – DirkJan May 22 '13 at 17:57
  • What about saving the data as it changes? e.g. the user sets a text and you save it right away. You could then make a method that updates the UI according to that saved data. You can also just keep the data in memory and save it in the onStop() method of your Activity. – SimonSays May 22 '13 at 18:36
  • Can I make my own class, say Subjects class. And save the instances onStop? Then recreate the instances? – DirkJan May 23 '13 at 14:06
  • Sure, why not? But be careful with saving data in the onStop() method. It runs on the UI thread and your App might get unresponsive when closing it or open another activity. – SimonSays May 23 '13 at 18:08
  • I used shared preferences in doing this. When the user submits the inputs, I save it in the app's shared preference then, on the main activity, I use a for loop to make a layout for each user data. Thanks so much! – DirkJan May 27 '13 at 15:17