简体   繁体   中英

How to populate a spinner which is dynamically generated on click of button in android

I was searching for how to add/Remove Layout Dynamically on click of button in android and found this .

I used the codes from above mentioned tutorial and designed a page which generates a layout on every click of button. This layout contains a Spinner , EditText & Button .

My code successfully adds/removes the layout on button click.

So my first problem is that all the generated spinners are empty ie they are not populated with the data from database after their creation and second problem is that how can I fetch the selected/entered data from dynamically created Spinner/EditText as I don't know their id.

The DBHelper class works fine with my other apps so I haven't posted it here.

This is the MyLayoutOperation class:-

    public class MyLayoutOperation extends Activity {
    static Spinner s;

public static void display(final Activity activity, Button btn)
    {
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);

                java.util.ArrayList<String> msg = new ArrayList<String>();

                for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
                {
                    LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
                    s = (Spinner) innerLayout.findViewById(R.id.spinner1);
                    EditText edit = (EditText) innerLayout.findViewById(R.id.editDescricao);

                    //msg.add(products.getSelectedItem().toString());
                    msg.add(edit.getText().toString());

                }

                Toast t = Toast.makeText(activity.getApplicationContext(), msg.toString(), Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }
    public static void add(final Activity activity, ImageButton btn)
    {
        final LinearLayout linearLayoutForm = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);;

        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final LinearLayout newView = (LinearLayout)activity.getLayoutInflater().inflate(R.layout.rowdetail, null);

                newView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

                ImageButton btnRemove = (ImageButton) newView.findViewById(R.id.btnRemove);
                btnRemove.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        linearLayoutForm.removeView(newView);
                    }
                });

                linearLayoutForm.addView(newView);
            }
        });
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rowdetail);

         s = (Spinner) findViewById(R.id.spinner1);
         // Loading spinner data from database
            try {
                loadSpinnerData();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

    private void loadSpinnerData() throws IOException {

        // database handler
        DBHelper db = new DBHelper(getApplicationContext());

        // Spinner Drop down elements
        List<String> products = db.getAllProducts();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, products);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        s.setAdapter(dataAdapter);

    }
}

LogCat :-

07-22 08:23:27.090: E/AndroidRuntime(1834): FATAL EXCEPTION: main
07-22 08:23:27.090: E/AndroidRuntime(1834): Process: com.example.teste1, PID: 1834
07-22 08:23:27.090: E/AndroidRuntime(1834): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.teste1/com.example.teste1.MainActivity}: java.lang.NullPointerException
07-22 08:23:27.090: E/AndroidRuntime(1834): Caused by: java.lang.NullPointerException
07-22 08:23:27.090: E/AndroidRuntime(1834):     at com.example.teste1.MyLayoutOperation.add(MyLayoutOperation.java:73)
07-22 08:23:27.090: E/AndroidRuntime(1834):     at com.example.teste1.MainActivity.onCreate(MainActivity.java:22)
07-22 08:23:27.090: E/AndroidRuntime(1834):     at android.app.Activity.performCreate(Activity.java:5231)

Line 73 of MyLayoutOperation :- btn.setOnClickListener(new View.OnClickListener() {

Line 22 of MainActivity :- MyLayoutOperation.add(this, btnAdd);

MainActivity.java :-

 public class MainActivity extends Activity {

    Button btnDisplay;
    ImageButton btnAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnAdd = (ImageButton) findViewById(R.id.btnAdd);
        btnDisplay = (Button) findViewById(R.id.btnDisplay);

        MyLayoutOperation.add(this, btnAdd);
        MyLayoutOperation.display(this, btnDisplay);
    }

    @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;
    }

}

rowdetail.xml :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowdetail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="94dp"
        android:layout_height="45dp" />

    <EditText
        android:id="@+id/editDescricao"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.01"
        android:ems="10"
        android:inputType="text" />

    <ImageButton
        android:id="@+id/btnRemove"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/btnRemove"
        android:src="@android:drawable/ic_delete" />

</LinearLayout>

activity_main.xml :-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layoutTeste"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="95dp"
            android:layout_height="fill_parent"
            android:layout_alignBottom="@+id/btnAdd"
            android:layout_alignParentLeft="true"
            android:layout_toLeftOf="@+id/btnAdd"
            android:gravity="center_vertical|center_horizontal"
            android:text="@string/titleTecnologies"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <ImageButton
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:contentDescription="@string/btnAdd"
            android:src="@android:drawable/ic_input_add" />

    </RelativeLayout>

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="275dp" >

        <LinearLayout
            android:id="@+id/linearLayoutForm"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnDisplay" />

</LinearLayout>

Please help.

Edit: You don't need your extra activity. You simply need one activity, that will display your layout, and update it on your button click.

public class TestActivity extends Activity {

    Button btnDisplay;
    ImageButton btnAdd;
    LinearLayout container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        container = findViewById(R.id.linearLayoutForm);
        btnAdd = (ImageButton) findViewById(R.id.btnAdd);
        btnDisplay = (Button) findViewById(R.id.btnDisplay);

        btnAdd.setOnClickListener(addListener);
        //TODO: btnDisplay
    }

    /*
     * We define our OnClickListener that will act when we click on the btn.
     */
    View.OnClickListener addListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final LinearLayout newView = (LinearLayout) getLayoutInflater().inflate(R.layout.rowdetail, null);

            newView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            ImageButton btnRemove = (ImageButton) newView.findViewById(R.id.btnRemove);
            btnRemove.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    container.removeView(newView);
                }
            });

            container.addView(newView);

            //Now we load your data into your spinner
            Spinner s = newView.findViewById(R.id.spinner1);
            try {
                loadSpinnerData(s);
            } catch (IOException e) {
                //TODO: catch exception
                e.printStackTrace();
            }

        }
    };

    /*
     * This function is supposed to load the data into the given spinner.
     * It would be better to load the data an other way, i.e.: using ASyncTask
     */
    private void loadSpinnerData(Spinner s) throws IOException {

        // database handler
        DBHelper db = new DBHelper(getApplicationContext());

        // Spinner Drop down elements
        List<String> products = db.getAllProducts();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, products);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        s.setAdapter(dataAdapter);

    }
}

I haven't tested this code, so you might have to tweak it so it matches your needs, but I think the main idea is there. Your activity's onCreate inflates your layout. In there you set your button, and save information about your "container".

On click on your add button, your simply inflate your new layout, and set your spinner data using your loadSpinnerData(s); , which loads the data from the database into your spinner.

Note that it is not a good way of getting the information from the database. Doing so can block the UI thread as retrieving lots of information can be time consuming. It's better to use a loader, or an asynctask to do so. I can redirect you to Vogella tutorials that explains very well (and is very easy to understand) how to manage a database efficiently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM