How to insert the values of spinner to SQL lite database in android?
for instance my code has
ArrayList<String> yr = new ArrayList<String>();
for (int i = 2015; i <= 2030; i++) {
yr.add(Integer.toString(i));
}
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yr);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
year.setAdapter(adapter1);
and i want to save the year selected by the user on the database
Implement OnItemSelectedListener for your class then call setOnItemSelectedListener for the spinner.
spinner.setOnItemSelectedListener(this);
Then add the following which gets invoked after year is selected in the dropdown:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
//insert item to db
}
May be this will work
public void insertValuesInDb(ArrayAdapter adapter) {
for(int i = 0; i < adapter.size(); i++) {
item = adapter.getItem(i)
//insert item in database
}
}
If it helps you then don't forget to mark answer as accepted and if you have any further queries you can ask them in comments!
Related
Please tell me how can I hide the item at index 0 from the dropdown in the spinner in Android Studio? I am using this code, it works, but when I open the list, it shows at the bottom. That is, it is focused on the elements below. what do i need to change?
SpinnerName = (Spinner) v.findViewById(R.id.spinner1);
ArrayList<String> names = new ArrayList<>();
names.add(0, "SELECT");
names.add(1, "Name1");
names.add(2, "Name2");
final int listsize = names.size()-1;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names){
#Override
public int getCount() {
return(listsize);
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerName.setAdapter(adapter);
adapter.setDropDownViewResource(R.layout.spinner_list);
SpinnerName.setSelection(listsize);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
....
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
SpinnerName.setSelection(listsize);
your problem is here! you are passing the total list size number and
that where you are doing wrong, because setSelection method use to
show default index of spinner.
you can simply do that SpinnerName.setSelection(1); that would give you the fist spinner item unless showing the names.add(0, "SELECT"); item
The code for the spinner is below, The spinners on my app tend to duplicate it's content sometimes for some weird reason. How do I prevent this from happening?:
Spinner spinnerG = (Spinner) findViewById(R.id.spGroup);
final ArrayAdapter<String> dataAdapterG = new ArrayAdapter<>
(this, R.layout.simple_spinner_item, groups);
dataAdapterG.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinnerG.setAdapter(dataAdapterG); //general basics //sets up the group spinner, filled with the groups list
spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
selectedGroup = groups.get(position);
studentsToShow.clear();
for(int i = 0; i < studList.size(); i++){
if(studList.get(i).getGroup().equals(selectedGroup)){
Students a = new Students();
a.setFirstName(studList.get(i).getFirstName());
a.setLastName(studList.get(i).getLastName());
a.setStudentID(studList.get(i).getStudentID());
a.setGroup(studList.get(i).getGroup());
studentsToShow.add(a); //when a new group is chosen the list of students in the selected group needs to be updated
} //this re uses the code earlier to make a list of student in the selected group
}
updateSpS(); //updates the student spinner
}
public void onNothingSelected(AdapterView<?> parent){
}
});
The spinner will duplicate if you have put this oncreate event. Put the spinner population code on the onResume method.
From the snippet shared with the question, its hard to guess why OP would have duplicate value. An educated guess is his onItemSelected() is being called multiple times.
Spinner's (in my personal view, is one of the worst android widget) onItemSelected() can be called multiple times for different reasons, one of the thing I would recommend to try this way -
class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
boolean userSelect = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (userSelect) {
// Your selection handling code here
userSelect = false;
if(view!=null){
selectedGroup = groups.get(position);
studentsToShow.clear();
for(int i = 0; i < studList.size(); i++){
if(studList.get(i).getGroup().equals(selectedGroup)){
Students a = new Students();
a.setFirstName(studList.get(i).getFirstName());
a.setLastName(studList.get(i).getLastName());
a.setStudentID(studList.get(i).getStudentID());
a.setGroup(studList.get(i).getGroup());
studentsToShow.add(a); //when a new group is chosen the list of students in the selected group needs to be updated
} //this re uses the code earlier to make a list of student in the selected group
}
updateSpS(); //updates the student spinner
}
}
}
}
And then set -
SpinnerInteractionListener listener = new SpinnerInteractionListener();
spinnerG.setOnTouchListener(listener);
spinnerG.setOnItemSelectedListener(listener);
This at the same time takes care unwanted callbacks of onItemSelected() without user touch and if any previous leaked listeners.
Currently, in anotherclass, I need to delete 1 item when I upload success a file call deleteCallWhenUploadSuccess.
In this class, I using fileName to determined item need to delete.
But it doesn't delete item in ListView from Layout activity_call_history.xml
In DAO class I delete with code:
public void deleteCallWhenUploadSuccess(String fileNameWhis)
{
db = callDatabaseHelper.getWritableDatabase();
String where = CallDatabaseHelper.FILE_NAME + "='" + fileNameWhis + "'";
db.delete(CallDatabaseHelper.TABLE_NAME, where, null);
}
And in other class I using it:
DAO.deleteCallWhenUploadSuccess(filename);
I write code to remove an item on ListView in event onActionItemClicked.
On the DAO class I start to delete an item with rowId:
public void deleteCallV2(int rowId) {
db = callDatabaseHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+CallDatabaseHelper.TABLE_NAME+" where rowId = "+String.valueOf(rowId),null);
while(cursor.moveToNext()){
this.rowId = CallDatabaseHelper.ROW_ID +"="+cursor.getString(cursor.getColumnIndex(CallDatabaseHelper.ROW_ID));
}
db.delete(CallDatabaseHelper.TABLE_NAME, this.rowId, null);
}
Code I used to delete item in ListView of Layout historyAdapter write code in HistoryFragment.java, I was comment in code to easy read:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.deleteAction:
// Calls getSelectedIds method from ListViewAdapter Class
selected = historyAdapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
Call selecteditem = historyAdapter
.getItem(selected.keyAt(i));
// Remove selected items following the ids
historyAdapter.remove(selecteditem);
}
}
getFragmentManager().beginTransaction().replace(R.id.container,new HistoryFragment()).commit();
// Close CAB
mode.finish();
return true;
case R.id.allAction:
historyAdapter.toggleAll(listView);
Toast.makeText(getActivity(), "Đã chọn tất cả", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
But it only work when I select item with long press and select item or select all to delete. It using ID to delete item.
Since I didn't got much but according to the heading of the question which says to remove an item in list I can suggest you to use notifyDataSetChanged() whenever you are removing a view so that your listview could update itself whenever its changed
A little code which demonstrate this task is
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
I created a Data-Base table student which contains two fields like student_id and student_name. This table contains some data for student.
My actual problem is I want to set ID and name of student in spinner like in html select tag, so when select spinner item I must get this ID to get another data from database.
You can have two arraylist for name and id;
List<String> sIds = new ArrayList<String>();//add ids in this list
List<String> names = new ArrayList<String>();//add names in this list
Then you can retrive here inside spinner select. It will work even if two names are same in the spinner which may be the case:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int id = sIds.get(position);//This will be the student id.
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
To add values into Spinner you can do it something like this Test
public class Test extends Activity
{
ArrayList<String> InfoStudent = new ArrayList<String>();
ArrayList<String> IdStudent = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//Here you'll have to make a query to get ID and Name then with
InfoStudent.add("TheID" + "InfoStudentReturnedByQuery");
//TheID should go in IdStudent ArrayAdapter and InfoStudentReturnedByQuery should go in InfoStudent ArrayAdapter
// Then you create the arrayAdapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Test.this
,android.R.layout.simple_spinner_item,difficultyLevelList);
// Set the Adapter
spinner.setAdapter(arrayAdapter);
If you want to know what spinner is selected you should do something like this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"You Selected : "
+ TheMainAdapterOfStudents.get(i)+" Student ",Toast.LENGTH_SHORT).show();
}
This only it's a guide how to, hope it helps :)
1. Declare type Like:
public class Item
{
public long id;
public String name;
}
2. Fill spinner with data (Item[]):
Item[] data = new Item[3];
data[0] = new Item(1, "Item 0");
data[1] = new Item(2, "Item 1");
data[2] = new Item(3, "Item 2");
ArrayAdapter<Item> dataAdapter = new ArrayAdapter<Item>(this,android.R.layout.simple_spinner_item, data);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
3. Get your id where you need it:
Item item = (Item)spinner.getSelectedItem();
return item.id;
Assuming I am reading your list correctly, if you want to set an Id to your Spinner programically just use..
mSpinner.setId(int)
In this code replace mSpinner with the reference to your Spinner and int with the desired Id
The title says it all, I'm trying to do that because I obtain a list from parse and the user must choose one of them from a spinner and based on the user's choice it responds and sets another filter to another spinner. The problem I'm having (really not much of a deal, but it's something that I'd like to do) is that when the list gets obtained from Parse it automatically selects the first one it retrieves and fills all the spinners automatically (of course you can change it and it will work perfectly).
The question is, how do I retrieve a list from parse, add it into a spinner in a way that it doesn't fill everything by itself ?
Here's my piece of code where I obtain the list and add it into a spinner:
groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Group Item Selected Ran");
final String spinI1 = groupSpinner.getSelectedItem().toString();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("grupo", spinI1);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
int size = 0;
size = parseObjects.size();
String[] mod = new String[size];
for (int i = 0; i < parseObjects.size(); i++) {
mod[i] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i]);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(HandsetLocation.this, android.R.layout.simple_spinner_item, mod);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
hospitalSpinner.setAdapter(spinnerArrayAdapter);
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Any help would be appreciated greatly!
At my phone so cannot properly indent the code but here it goes:
String[] mod = new String[size+1];
mod[0] = "select value";
for (int i = 0; i < parseObjects.size(); i++) {
mod[i+1] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i+1]);
}