简体   繁体   中英

Saving Spinner selection into SQLite database

I have looked over all the question related to saving the spinner into database and nothing seems to be working.

I have started working on adding in the ItemSelectedListener but it's throwing back an error,

here's my code

the OnItemSelectedListener is here where my inserts for the rest of the table are

public class OnClickListenerCreateMenuItem implements View.OnClickListener {
@Override
public void onClick(View view) {


    final Context context = view.getContext();
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View formElementsView = inflater.inflate(R.layout.menuitem_input_form, null, false);

    final EditText editTextItemName = (EditText) formElementsView.findViewById(R.id.editTextItemName);
    final EditText editTextItemDesc = (EditText) formElementsView.findViewById(R.id.editTextItemDesc);
    final EditText editTextItemPrice = (EditText) formElementsView.findViewById(R.id.editTextItemPrice);
    final EditText editTextItemCost = (EditText) formElementsView.findViewById(R.id.editTextItemCost);
    final Spinner itemCategory = (Spinner) formElementsView.findViewById(R.id.spinnerCategory);

    itemCategory.setAdapter(
            ((SettingsMenuItem) context).loadSpinnerData()
    );

    itemCategory.setOnItemSelectedListener(
            ((SettingsMenuItem) context).loadSpinnerData()
    );


    new AlertDialog.Builder(context)
            .setView(formElementsView)
            .setTitle("Create Item")
            .setPositiveButton("Add",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {


                            String itemName = editTextItemName.getText().toString();
                            String itemDescription = editTextItemDesc.getText().toString();
                            String itemPrice = editTextItemPrice.getText().toString();
                            String itemCost = editTextItemCost.getText().toString();
                            String valueOfSelectedCat= itemCategory.getSelectedItem().toString();


                            ObjectMenuItem objectMenuItem = new ObjectMenuItem();
                            objectMenuItem.name = itemName;
                            objectMenuItem.description = itemDescription;
                            objectMenuItem.price = Float.parseFloat(itemPrice);
                            objectMenuItem.cost = Float.parseFloat(itemCost);
                            objectMenuItem.cat = valueOfSelectedCat;

                            boolean createSuccessful = new TableControllerMenuItem(context).create(objectMenuItem);


                            if(createSuccessful){
                                Toast.makeText(context, "Item was saved.", Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(context, "Unable to save item.", Toast.LENGTH_SHORT).show();
                            }
                            ((SettingsMenuItem) context).readRecords();
                            ((SettingsMenuItem) context).countRecords();



                            dialog.cancel();

                        }

                    }).show();




}

and my actual spinner is set up here and populated here

public class SettingsMenuItem extends AppCompatActivity {

Spinner spinner;
Context context;
String id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings_menu_item);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    countRecords();
    readRecords();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    Button buttonCreateLocation = (Button) findViewById(R.id.btnAdd);
    buttonCreateLocation.setOnClickListener(new OnClickListenerCreateMenuItem());
}

public void countRecords() {

    int recordCount = new TableControllerMenuItem(this).count();
    TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);
    textViewRecordCount.setText(recordCount + " records found.");

}

public void readRecords() {

    LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
    linearLayoutRecords.removeAllViews();

    List<ObjectMenuItem> menuitem = new TableControllerMenuItem(this).read();

    if (menuitem.size() > 0) {

        for (ObjectMenuItem obj : menuitem) {

            int id = obj.id;
            String menuitemName = obj.name;
            String menuitemDescription = obj.description;
            Float menuitemPrice = obj.price;
            Float menuitemCost = obj.cost;
            String itemCategory = obj.cat;

            String textViewContents = menuitemName;

            TextView textViewMenuItem = new TextView(this);
            textViewMenuItem.setPadding(0, 10, 0, 10);
            textViewMenuItem.setText(textViewContents);
            textViewMenuItem.setTag(Integer.toString(id));
            textViewMenuItem.setTextSize(20.0f);

            textViewMenuItem.setOnLongClickListener(new OnLongClickListenerMenuItem());


            linearLayoutRecords.addView(textViewMenuItem);
        }

    } else {

        TextView locationItem = new TextView(this);
        locationItem.setPadding(8, 8, 8, 8);
        locationItem.setText("No records yet.");

        linearLayoutRecords.addView(locationItem);
    }

}

public ArrayAdapter loadSpinnerData() {

    Log.d("CON", "setting spinner data");

    Spinner s = (Spinner) findViewById(R.id.spinnerCategory);
    DatabaseHandler h = new DatabaseHandler(getApplicationContext());

    List<String> names = h.getAllNames();

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);

    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);




    return dataAdapter;


}





    }

here's my crash log

--------- beginning of crash 02-14 08:29:07.627 14332-14332/com.jenovaprojects.restaurant E/AndroidRuntime: FATAL EXCEPTION: main Process: com.jenovaprojects.restaurant, PID: 14332 java.lang.ClassCastException: android.widget.ArrayAdapter cannot be cast to android.widget.AdapterView$OnItemSelectedListener at com.jenovaprojects.restaurant.OnClickListenerCreate.OnClickListenerCreateMenuItem.onClick(OnClickListenerCreateMenuItem.java:41) at android.view.View.performClick(View.java:5204) at android.view.View$PerformClick.run(View.java:21156) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5466) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Using this code from the Android guides, you should be able to implement OnItemSelectedListener

public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        // An item was selected. You can retrieve the selected item using
        parent.getItemAtPosition(pos)
    }
}

I'm not sure why it wouldn't work, but it's hard to tell without more of your code. If this doesn't help, post the code you are using to save the selection, so we can try to figure out what's happening.

Please put your LogCat to see those error and if possible show your DB query and table structure where you want to insert selected data .

Simple procedure is to put one listener of onItemSelected on the spinner in your case put this

itemCategory.setOnItemSelectedListener(replce your context here);

then do the needful implementation of interface of spinner

implements OnItemSelectedListener

when you select any item from the spinner this method onItemSelected will be called. It will return you the position of the item you clicked and from that you can easily find out which item was clicked.

adapter.getItemAtPosition(pos).toString()

through this you will get the item's text.

2nd Part - Inserting data to sqlite db

make an object of db and initialize it then call the appropriate method to insert your selected choice data.

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