Search code examples
androidandroid-tablelayout

Refreshing TableLayout to show new rows inserted


Background:

I have created an Orders table in a database and I am manipulating it in two activities namely CurrentOrders and NewOrders respectively.

CurrentOrders activity shows the current orders stored inside the database in a TableLayout. And to add new orders to the table I have specified a button namely addOrders which when clicked loads NewOrders activity.

CurrentOrders:

public class CurrentOrders extends AppCompatActivity {
    
    private TableLayout table;
    populateTable(Cursor records){
           
           TableRow row = new TableRow(this);
           TextView product = new TextView(this);
           TextView price = new TextView(this);        

           product.setText(records.getString(1));        
           price.setText(records.getString(2));          
           row.addView(product);
           row.addView(price);

           table.addView(row);
    } 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_current_orders);
        
        Cursor cursor = db.query("orders", null, null,
                null, null, null, null);  

        table = findViewById(R.id.tab);             

        while(cursor.moveToNext())                 
           populateTable(cursor);
    }

    public void addOrders(View view){
       startActivity(new Intent(getApplicationContext(), NewOrders.class));        
    } 
}

NewOrders activity acts like a form by having a TableLayout whose cells/fields are specified as EditText in order to let user type the orders they want to store. And to save the orders inside the database I have specified a submit button which when clicked store the value of EditText inside the Orders table in database and then goes back to parent activity (CurrentOrders) to show all the orders in the database.

NewOrders:

public class NewOrders extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_orders);                        
    }

    public void submit(View view){
        
        TableLayout table = findViewById(R.id.newOrders);
        int count = table.getChildCount();
        
        for (int idx = 0; idx < count; idx++){

            TableRow row = (TableRow) table.getChildAt(idx);

            EditText product = (EditText) row.getChildAt(1);
            EditText price = (EditText) row.getChildAt(2);

            String productVal = product.getText().toString();
            double priceVal = Double.parseDouble(price.getText().toString());

            long result = db.insert(productVal, priceVal);           
        }
        Toast.makeText(this, "Saved.", Toast.LENGTH_SHORT).show();
         onBackPressed();
    }
}

Problem:

I don't see new records inserted until an unless I reload the CurrentOrders activity. I want to show all the records (included new ones) without having to reload the activity.


Solution

  • Finally created a simple solution:

    First we need to modify our startActivity of CurrentOrder in such a way so that It receives data from NewOrders activity:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        
        // add newly added orders
        
        if (data != null) {
            String response = data.getStringExtra("newOrders");
            if (requestCode == RequestCode && resultCode == RESULT_OK && !response.isEmpty()){
                String[] orders = response.trim().split(" ");
                for (String order : orders) {
                    // get new orders from the database
                    Cursor records = db.query("orders", null, "id = ?", 
                                              new String[] {String.valueOf(id)},
                                              null, null, null);
                    records.moveToNext();
                    populateTable(records);
                }
            }
        }
    }
    

    Then in addOrders method you need to replace startActivity with the following code:

    startActivityForResult(new Intent(getApplicationContext(), NewOrders.class), 2);
    

    Now coming to NewOrders activity here I have created a string variable that stores id's of the newly created orders:

    public class NewOrders extends AppCompatActivity {
        
        // created a string variable
        private String newOrdersId = "";
    
        // reset of the code
    
        public void submit(View view){
            
            // rest of the code
            
            for (int idx = 0; idx < count; idx++){
                
                // rest of the code 
                
                // record id's of orders inserted into the database
                newOrderId += result + " "; 
            }
            // reset of the code
        }
    }
    

    And lastly you need to send the data to CurrentOrders by overriding onBackPressed method like this:

    @Override
    public void onBackPressed(){
        Intent intent = getIntent();
        intent.putExtra("newOrders", newOrdersId);
        setResult(RESULT_OK, intent);
        finish();
    }