1

I have programmatically created an Android TextView on a Click event.

public class FireMissilesDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();

        builder.setView(inflater.inflate(R.layout.dialog_addvehicles, null))
        // Add action buttons
               .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int id) {

                        Dialog dialogAddVehicles = (Dialog) dialog;
                        etVehicleModel = (EditText) dialogAddVehicles.findViewById(R.id.etModel);
                        String vehicleModel = etVehicleModel.getText().toString();
                        SharedPreferences.Editor editor = myVehicleData.edit();
                        editor.putString("VehicleModel", vehicleModel);
                        editor.commit();

                        vehicleModelReturned = myVehicleData.getString("VehicleModel", "");

                        TextView valueTV = new TextView(AddMyVehicle.this);
                        linearLayout.addView(valueTV);

                        valueTV.setText(vehicleModelReturned);
                        valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
                        valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
                        valueTV.setTextColor(Color.parseColor("#333333"));
                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       FireMissilesDialogFragment.this.getDialog().cancel();
                   }
               });      
        return builder.create();
    }
}

The above code works perfectly and creates a new TextView, But when I close the application and re-run it the TextView would not display.

Is there any method that I could use to save the TextView so that even if I close the Application the TextView would remain.

You can find the whole code Here -> http://pastebin.com/0MZRmNAA

Kanwaljit Singh
  • 4,339
  • 2
  • 18
  • 21
Chamara Keragala
  • 5,627
  • 10
  • 40
  • 58

5 Answers5

3

You can create a boolean variable on the activity class and set it to true when the button is clicked. That would mean that the textview has been created.

You should put the code to create the textview also into onResume method and check the boolean variable to see if you need to re-create the textview.

You can also save the information whether the button has been added in state so that the text view is re-created when the activity is re-created (e.g. after orientation change).

All that will work if you do not need to persist the information after the app killed. If you need to, use shared preferences (see other answers).

UPDATE:

Here is a sample activity that shows the code what needs to be done:

public class MainActivity extends Activity {

    private boolean textViewAdded; // whether the textview has been added
    private final String STATE_TEXTVIEWADDED = "STATE_TEXTVIEWADDED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) // restore state
            textViewAdded = savedInstanceState.getBoolean(STATE_TEXTVIEWADDED);
    }

    @Override
    protected void onResume() {
        if (textViewAdded) addTextView();
        super.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(STATE_TEXTVIEWADDED, textViewAdded); // save state
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void buttonClick(View view) { // method called when a button is clicked.
        if (!textViewAdded) addTextView();
    }

    private void addTextView() {
        LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);
        TextView valueTV = new TextView(MainActivity.this);
        valueTV.setText("Sample");

        main.addView(valueTV);
        textViewAdded = true;
    }

}
Szymon
  • 42,577
  • 16
  • 96
  • 114
  • If you don't mind can you please provide me with a sample code. You can find my code here -> http://pastebin.com/0MZRmNAA – Chamara Keragala Dec 30 '13 at 06:02
  • I added a sample activity that shows you what can be done. I also added saving/restoring from state to cater for re-creation of the activity. – Szymon Dec 30 '13 at 08:39
3

You can use SharedPreferences.

Initially, do the following:

SharedPreferences SP = getSharedPreferences("preferences name", MODE_PRIVATE);
Editor edit = SP.edit();

When you do the setText() call the following:

edit.putString("text", your_value);
edit.commit();

and before your activity loads, you could call to check if you have the following "text":

SP.getString("text", "");

I would recommend you creating a separate class for the SharedPreferences operations. And also do override the onResume() and onPause(). For reference, see this, the example implements the SharedPreference as a separate class.

Update: I think in your case, you are always creating a new SharedPreference, rather than using the existing one, create a separate class and I think all will go well.

Rakeeb Rajbhandari
  • 5,043
  • 6
  • 43
  • 74
0

If you need to persist your text view only during the lifetime of your application you can just write the code for creating the text view in onResume() method based on a flag, refer the answer by Szymon. But if you are looking to keep it beyond the normal life cycle of your app, i.e even after you have forcefully stopped your app, you can write the details of the textview created(textview with its parameters ) in a file in onDestroy() of your activity. Later when restarting your activity, you can check this file and recreate the textviews into your layout as per the file. Hope this helps.

Kanwaljit Singh
  • 4,339
  • 2
  • 18
  • 21
nikvs
  • 1,090
  • 5
  • 9
  • I don't think onDestroy() is good here, since it won't be called if system destroys process and activity is recreated. – Steve M Dec 30 '13 at 06:14
  • @svenoaks , true, so we can just write this into a text file at the same time of creating the textviews. So it works fine. – nikvs Dec 30 '13 at 06:16
  • yes, or in onPause() - think prefs is fine here though, no need for file – Steve M Dec 30 '13 at 06:22
0
try This
=====
LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
TextView valueTV = new TextView(this);
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
valueTV.setTextColor(Color.parseColor("#333"));
valueTV .setLayoutParams(lpView);
linLayout.addView(valueTV );
ishu
  • 1,322
  • 1
  • 11
  • 15
0

I think you are in need of persistent storage. You can do it in two ways:

  1. Preferences
  2. Database

In your case, you need to use Preferences (you can use database, too, but that would be cost effective in terms performance).

Check this link: http://developer.android.com/training/basics/data-storage/shared-preferences.html

Clearly explains how to use preferences for saving and retrieving data.

For tutorial, you can go here:

How to use SharedPreferences in Android to store, fetch and edit values

Community
  • 1
  • 1
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174