1

i have one dynamic view with edittext and textview, when user click on add button, it will add one row, when user click remove button, it will remove one row. every user add one row, it will inflate one layout, my problem is every time when i add a row ,all the widget of row have same id and name. it will give me a problem when i want to save it into my sqlite, because it only save the last row, not all row. enter image description here

enter image description here

so my question is : 1. how to change the name and id of widget on add button click. 2.add how to store multiple row into table of database. this is how i add my view :

   public class Pemegang_polis extends Activity{
    Cursor model=null;
    spaj1_adapter adapter=null;
    DBSpaj helper=null;
    int count_anak = 0; 
    int counter = 1;    
    EditText nama_pp;
    TextView adapter_no_dana,adapter_jenis_dana,adapter_jelaskan_dana,nomor,anggota,ttl;
    EditText nama;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //hide title bar
        BasicDisplaySettings.toggleTaskBar(Pemegang_polis.this, false);
        //show status bar
        BasicDisplaySettings.toggleStatusBar(Pemegang_polis.this, true);
        super.onCreate(savedInstanceState);

         helper=new DBSpaj(this);
         model=helper.getAll();
         startManagingCursor(model);
        adapter= new spaj1_adapter(model);
    setContentView(R.layout.pemegang_polis2);

        mContainerView = (LinearLayout) polis.findViewById(R.id.parentView);
        btn_save=(Button)menu.findViewById(R.id.btn_save);
        list_terkirim.setAdapter(adapter);
        list_terkirim.setOnItemClickListener(onListClick);
// add view
        inflateEditRow(counter,"Istri/Suami");
        nama_pp=(EditText)polis.findViewById(R.id.nama_pp);

//saving into database    
        btn_save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                helper.insert(nama_pp.getText().toString(), 
                        nomor.getText().toString(),
                        anggota.getText().toString(),
                        nama.getText().toString(), 
                        ttl.getText().toString()
            );  
                model.requery();
                nama_pp.setText(null);
                anggota.setText(null);
                nama.setText(null);
                ttl.setText(null);
//              mContainerView.removeView((View) v.getParent());
            }
        });

    }
//Adapter for display saved data

        private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                model.moveToPosition(position);
                nama_pp.setText(helper.getNamaPP(model));
        for (int i=0;i<helper.getNo(model).length();i++){
            nomor.setText(helper.getNo(model));
            anggota.setText(helper.getAnggota(model));
            nama.setText(helper.getNama(model));
            ttl.setText(helper.getTTL(model));
        }   
            }
            };

// Helper for inflating and add a new row private void inflateEditRow(int counter2,String name) {

                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View rowView = inflater.inflate(R.layout.row, null);
                deleteButton = (ImageButton) rowView.findViewById(R.id.buttonDelete);
                nomor = (TextView) rowView.findViewById(R.id.nomor);
                anggota = (TextView) rowView.findViewById(R.id.anggota);
                nama = (EditText) rowView.findViewById(R.id.nama);
                ttl = (TextView) rowView.findViewById(R.id.ttl);
                button_tanggal_anak=(ImageView)rowView.findViewById(R.id.button_tanggal_anak);
                button_tanggal_anak.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        showDialog(1);
                    }
                });

                if (name != null && !name.isEmpty()) {
                    anggota.setText(name);
                    nomor.setText(String.valueOf(counter2));
                } else {
                    mExclusiveEmptyView = rowView;
                    deleteButton.setVisibility(View.VISIBLE);
                }

                // A TextWatcher to control the visibility of the "Add new" button and
                // handle the exclusive empty view.
                anggota.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void afterTextChanged(Editable s) {

                        if (s.toString().isEmpty()) {
                            deleteButton.setVisibility(View.INVISIBLE);

                            if (mExclusiveEmptyView != null
                                    && mExclusiveEmptyView != rowView) {
                                mContainerView.removeView(mExclusiveEmptyView);
                            }
                            mExclusiveEmptyView = rowView;
                        } else {

                            if (mExclusiveEmptyView == rowView) {
                                mExclusiveEmptyView = null;
                            }
                            deleteButton.setVisibility(View.VISIBLE);
                        }
                    }
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count,
                            int after) {}
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before,
                            int count) {}
                });

                // Inflate at the end of all rows but before the "Add new" button
                mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
            }
            //end


    //add view list // onClick handler for the "Add new" button;
            public void onAddNewClicked(View v) {
                counter++;
                count_anak++;
                inflateEditRow(counter, "anak "+count_anak);
                v.setVisibility(View.VISIBLE);
            }

            // onClick Hapus
            public void onDeleteClicked(View v) {
                counter--;
                count_anak--;
                mContainerView.removeView((View) v.getParent());
                anggota.setText("anak"+count_anak);
                nomor.setText(String.valueOf(counter));

            }
    }

this is my row.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border_for_table"
    android:orientation="horizontal" >
    <ImageButton
        android:id="@+id/buttonDelete"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:background="@drawable/remove"
        android:contentDescription="Hapus"
        android:onClick="onDeleteClicked"/>

                                     <View
                                        android:layout_width="2dp"
                                        android:layout_height="match_parent"
                                        android:background="#EEEEEE"/>
                                    <TextView
                                        style="@style/textview_with_weight_1"
                                        android:id="@+id/nomor"
                                        android:layout_width="50dp"
                                        android:layout_height="65dp"
                                        android:textStyle="bold"
                                        android:gravity="center_vertical"
                                        android:text="" />

                                    <TextView
                                        style="@style/textview_with_weight_1"
                                        android:id="@+id/anggota"
                                        android:textStyle="bold"
                                        android:layout_width="110dp"
                                        android:layout_marginRight="10dp"
                                        android:layout_height="65dp"
                                        android:gravity="center_vertical"
                                        android:text="" />

                                    <EditText
                                        android:id="@+id/nama"
                                        android:layout_width="330dp"
                                        android:layout_height="65dp"
                                        android:layout_marginBottom="1.25dp"
                                        android:layout_marginRight="10dp"
                                        android:maxLength="25"
                                        style="@style/edittext_with_weight_2"
                                        android:background="@drawable/border_corner_4"
                                        android:hint=". . ." />

                                    <TextView
                                        style="@style/textview_with_weight_1"
                                        android:id="@+id/ttl"
                                        android:layout_width="110dp"
                                        android:layout_height="65dp"
                                        android:textStyle="bold"
                                        android:gravity="center_vertical"
                                        android:text="" />
                                     <ImageView
                                            android:id="@+id/button_tanggal_anak"
                                            style="@style/spinner_image"
                                            android:layout_width="25dp"
                                            android:layout_height="fill_parent"
                                            android:src="@drawable/espaj_button_calendar" />

</LinearLayout>

this is my class for my sqlite:

 class DBSpaj extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="dbspaj.db";
    private static final int SCHEMA_VERSION=1;

    public DBSpaj(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }

    //koma jangan lupa
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS table_spaj");
        db.execSQL("CREATE TABLE if not exists table_spaj (_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                " nama_pp TEXT,"+
                " no TEXT,"+
                " anggota TEXT,"+
                " nama TEXT,"+
                " ttl TEXT"+
                ");");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // no-op, since will not be called until 2nd schema
        // version exists
    }

    public Cursor getAll() {
        return(getReadableDatabase()
                        .rawQuery("SELECT _id, nama_pp,no,anggota,nama,ttl FROM table_spaj ORDER BY no", null));
    }

    public void insert(
            String nama_pp,
            String no,
            String anggota,
            String nama,
            String ttl
            ) {
        ContentValues cv=new ContentValues();
        cv.put("nama_pp", nama_pp);     
        cv.put("no", no);
        cv.put("anggota", anggota);
        cv.put("nama", nama);
        cv.put("ttl", ttl);

        getWritableDatabase().insert("table_spaj", "name", cv);
    }

    public String getNamaPP(Cursor c) {
        return(c.getString(1));
    }

    public String getNo(Cursor c) {
        return(c.getString(2));
    }

    public String getAnggota(Cursor c) {
        return(c.getString(3));
    }

    public String getNama(Cursor c) {
        return(c.getString(4));
    }

public String getTTL(Cursor c) {
        return(c.getString(5));
    }
Aoyama Nanami
  • 2,532
  • 9
  • 32
  • 50
  • when you will add row you will generate unique id for the row layout, inside it can be the same. AS you will retrieve row (unique id) and then access it's fields using static ids. – Lukasz 'Severiaan' Grela Nov 28 '13 at 07:41
  • @Lukasz'Severiaan'Grela would you like to help me for putting the code? – Aoyama Nanami Nov 28 '13 at 07:48
  • where you retrieve `rowView` use `setId` on it as @Techfist said. Then you don't have to change or make unique the id's inside the row layout. – Lukasz 'Severiaan' Grela Nov 28 '13 at 08:03
  • also the row id can contain the `_id` from database to "connect" it with database entry – Lukasz 'Severiaan' Grela Nov 28 '13 at 08:05
  • @Lukasz'Severiaan'Grela so what about id that i've create in my xml? setId is like this answer or not? http://stackoverflow.com/questions/3216294/programatically-add-id-to-r-id – Aoyama Nanami Nov 28 '13 at 08:36
  • within row you can keep whatever was set in xml why do you need to change it when uniqueness is at the row level as long as you can identify row columns within that row are safe. – Lukasz 'Severiaan' Grela Nov 28 '13 at 08:42
  • Also to cut the discussion: this should not be linear layout with rows manualy added as you are doing as there is class for that: ListView and CursorAdapter that way you are only ever interested in designing your row and doing insert delete to database. – Lukasz 'Severiaan' Grela Nov 28 '13 at 08:49

1 Answers1

0

After inflating new views for addition, just use setId method to assign them a unique ID, this same ID you can use later on to fetch the data it hold and then easily put them into sqlite.

Techfist
  • 4,314
  • 6
  • 22
  • 32
  • The part of code where you are inflating views right, once you inflate them assign them a unique ID as per your use. let me know if you need any further help. – Techfist Nov 28 '13 at 09:01
  • as you are adding one more when user clicks a button, as eventually you want to put this values into database so to ease up all the operations I would suggest you to do this. 1. When user clicks on add row, create a dummy row in your database, use the same row id to assign ID to newly inflated views 2. Maintain a schema to store newly generated IDS, for whome values are yet to be pupulated in database 3. At the time of saving data, just fetch the correct values and update the database rows. Hope this clear things up. – Techfist Nov 28 '13 at 09:42