Search code examples
androidsaverowandroid-tablelayouttablerow

Add, save and delete tablerow


I want to create a table with a button that every time it is clicked adds a tablerow with three TextView. For the moment I could only add to the tablerow without TextView, however, has the problem that when I close the application the lines created are not saved, who can help me?

This is my code:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnAddItem = (Button) findViewById(R.id.addItemTableRow);
        btnAddItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);

                TableRow row = new TableRow(MainActivity.this);

                TextView t = new TextView(MainActivity.this);

                t.setText("Add table row");

                row.addView(t);

                table.addView(row, new TableLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));

            }
        });
    }
}

Solution

  • You can't add permanently views to a Layout ("permanently" means that survive to the application being closed).

    If you are referring to the application being put in background (i.e. when the user presses the home button), or when the user turns the device, or when you start another activity and you go back to this one android gives you the possibility to "save" the state of your activity with two callbacks: namely onSaveInstanceState and onRestoreInstanceState

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt("numRows", rowsNum);
        for (int i=1;i<rowsNum+1;i++) {
             savedInstanceState.putString("row"+i+"1", "Text of the first row first cell");
             savedInstanceState.putString("row"+i+"2", "Text of the first row second cell");
             savedInstanceState.putString("row"+i+"3", "Text of the first row third cell");
        }
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        int numRows = savedInstanceState.getInt("numRows");
        for (int i=1;i<rowsNum+1;i++) {
             String cell1 = savedInstanceState.getString("row"+i+"1");
             String cell2 = savedInstanceState.getString("row"+i+"2");
             String cell3 = savedInstanceState.getString("row"+i+"3");
             //re-create the table here from the strings
        }
    }
    

    Hope this helps