Spinner with sqlite database in Android - android

I have one spinner, one button and a ListView.
I want to choose item from spinner and after clicking button the match of spinner and database content must be show in the ListView. The database values are of string data type.
Please anybody can guide me how I can do it?

For spinner,first create an adapter like:
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.months, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// Here R.array.months are string array created at string.xml file and then open ur database:
if(mydb_expenditure!=null)
{
mydb_expenditure.close();
}
mydb_expenditure=this.openOrCreateDatabase("Database_name", MODE_PRIVATE, null);
if(mydb_expenditure!=null)
{
Cursor cursor = mydb_expenditure.rawQuery("select column name from "+TableName , null);
cursor.moveToFirst();
int column=cursor.getColumnIndex("column name");
if(cursor!=null)
{
do
{
column=cursor.getInt(column);
adapter12.add(column);
}while(.moveToNext());
}
spinner.setAdapter(adapter12);
}
This will add ur ur database column value into the spinner

For example:
setContentView(R.layout.main);
ListView lv=(ListView)findViewById(R.id.listview);
Button b=(Button)findViewById(R.id.button);
Spinner sp=(Spinner)findViewById(R.id.spinner);
final ArrayList<String> options=new ArrayList<String>();
Cursor cursor=dbHelper.getOptions();//method to get all options to be displayed in spinner,coming from your database
if(cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i=0;i<cursor.getCount();i++)
{
options.add(cursor.getString(cursor.getColumnIndex("field_name")));
cursor.moveToNext();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,options);
sp.setAdapter(adapter);
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Cursor c=db_helper.getRelatedItems(spinner.getSelectedItem().toString()); //get related data from database according to the item selected in spinner
if(c.getCount()>0)
{
CustomAdapter ca=new CustomAdapter(context,R.layout.listitem_layout,cursor,new String[]{"field 1","field 2"},new int[]{R.id.textview1,R.id.textview2});
//here you would have to pass your custom layout file containing textviews or other component to display your data using CustomAdapter.class which you had prepared
listview.setAdapter(ca);
ca.notifyDataSetChanged();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//catch onClick on items of listview here
}
});
}
}
});

you can follow this steps assuming spinner is populated with string array:
i) In setOnItemSelectedListener event get position of selected position by
int pos=urspinner.getSelectedItemPosition() and get string by
strsel=arrstr[pos];
ii) on button click listener use strsel to populate listadapter by querying database
DONE!!!!

Related

How do I put a product in a category using spinner dropdown?

enter image description hereI wanted to add a function to my spinner
I want to ADD a PRODUCT in my Food TABLE, I input a name of product "ADOBO" and I input a PRICE "50" and I want to put a "ADOBO" in FOOD CATEGORY and there's two item in my spinner, Category food and Category drinks. How do I put my Product in FOOD TABLE using Spinner
//SPINNER DROPDOWN
List<String> List = new ArrayList<>();
List.add("Food");
List.add("Drinks");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, List);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCT.setAdapter(adapter);
}
public void Addproduct(){
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = NameOfProduct.getText().toString().trim();
String price = PriceOfProduct.getText().toString().trim();
spinnerCT.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String itemvalue = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
Remove Spinner onItemSelectedListener from onClick
And inside onClick use:
spinnerCT.getSelectedItem()
It gives you the category
And if you need to set the onItemSelectedListener, please set it in onCreate after setting adapter.

How to load data to spinner with id and name

I have a table Facilities with field FacilityID and field FacilityName. I have a spinner load data to SQLite.
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spin2.setAdapter(dataAdapter);
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + Facibilities;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
I have a Company form for users enter the information of company such as: Company ID, Company Name, Address, Phone, Facility,...and a 'Create' button. In Facility field I use spinner to display FacilityName, when users click on Create button, I want save FacilityID into the table Company
try like this
1) Declare a public String variable 'id' to store selected id;
2) save the ids in a seperate arraylist.
3) Inside the spinner.OnitemSelectedListener->
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
id=ids.get(position);
}
});
3) inside create button onclick method pass the variable named id.
To manage such a data set, what you can do is:
Declare a Faculty class with faculty ID and faculty name.
Query the database and prepare an Arraylist with all the faculty objects, like ArrayList<Faculty>.
You can get the particular faculty data with the index/position of the selected item.
You have to create new Class such as Data with two feild like id and label also the getter and setter for it.
class Data {
private String id;
private String label;
//create getter and setter for above properties.
}
Then do some changes in getAllLabels method such as:
public List<Data> getAllLabels(){
List<Data> lstData = new ArrayList<Data>();
// Select All Query
String selectQuery = "SELECT * FROM " + Facibilities;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
Data data = new Data();
do {
data .setId(add(cursor.getString(1)))
data .setLabel(add(cursor.getString(2)));
lstData.add(data);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning data object with id and labels
return lstData;}
then create one list of String labels and id from returned list:
List <String> labels= new ArrayList<String>();
List <String> ids= new ArrayList<String>();
foreach(data in lstData){
ids.add(data.getId());
labels.add(data.getLabel());
}
and then pass the lables list to the adapter and onSelect of adapter item you will get the id from it from its position:
spin2.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected( AdapterView<?> parent, View view, int pos, long id){
// you will get your id here of selected item and then you can use it //wherever you want
String singleId= id.get(position);
}
public void onNothingSelected( AdapterView<?> parent){
Log.d(TAG,"Nothing selected ");
selectedCurrency=-1;
}
}
);

How can I delete a row from a database from the ListView onClickAdapter?

I want to delete a row in a database with a click from the list view!
I have everything set up, but when I go to do so it either A) doesn't delete the row. or B) deletes the top row! Let me know what I'm doing wrong! Thanks!
This is in my database:
public boolean deleteKey(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(KeyEntry.TABLE_NAME, KeyEntry.KEY_ID + "=?",
new String[]{name})>0;
}
and this is in my list view:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view__list);
list = (ListView) findViewById(R.id.ListView1);
openDatabase();
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, keyList));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view,
int position, long id)
{
String name = String.valueOf(id);
keyManager.deleteKey(name);
Toast.makeText(View_List.this, "Key will be deleted",
Toast.LENGTH_LONG).show();
}
});
}
Where am I going wrong?
The ArrayAdapter returns the position as id. Then the id does not match with KeyEntry.KEY_ID on database.
The best way to use Database and ListView together is using the CursorAdapter. In this case, the id parameter at onItemClick Listener will be the database id. The CursorAdapter require more code to implement, but it is much more flexible.

How can I see a value on the spinner?

My question is: I am using spinner on my android app. However, I can't see the default value shown on the spinner, at all. I can select elements but I can't see any text on the spinner. It seems like the value is hidden and doesn't show anything, just the spinner itself and drop down arrow.
mDbHelper = new DbAdapter(this);
mDbHelper.open();
cursor = mDbHelper.fetchAllBusinessCards();
startManagingCursor(cursor);
contactSpinner = (Spinner) findViewById(R.id.contactSpinner);
contactSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
fillData();
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext(), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
private void fillData() {
/*Create an array to specify the fields we want to display in the list (only the 'colourName' column in this case) */
String[] from = new String[]{DbAdapter.getKeyTitle() };
/* and an array of the fields we want to bind those fields to (in this case just the textView 'tvDBViewRow' from our new db_view_row.xml layout above) */
int[] to = new int[]{R.id.tvDBViewRow};
/* Now create a simple cursor adapter.. */
SimpleCursorAdapter colourAdapter =
new SimpleCursorAdapter(this,R.layout.db_view_row, cursor, from, to);
/* and assign it to our Spinner widget */
contactSpinner.setAdapter(colourAdapter);
//contactSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
contactSpinner.setSelection(0);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mDbHelper != null) {
mDbHelper.close();
}
}
}
You can call spinner.setSelection to set the current state of the
spinner to whatever you want. And that definitely works
spinner.setSelection(0);
but you must also call
setDropDownViewResource()
let say
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);

how to add item to Spinner's ArrayAdapter?

i had a EditText , a button and a spinner . When click the button , the spinner will add a new item with name you entered in the EditText. But here is the question, my adapter.add() method seems doesn't work...here is my code:
public class Spr extends Activity {
Button bt1;
EditText et;
ArrayAdapter<CharSequence> adapter;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt1 = (Button)this.findViewById(R.id.bt1);
et = (EditText)this.findViewById(R.id.et);
spinner = (Spinner)this.findViewById(R.id.spr);
adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = et.getText().toString();
adapter.add(temp);
adapter.notifyDataSetChanged();
spinner.setAdapter(adapter);
}
});
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Toast.makeText(parent.getContext(), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
}
}
thanks! ...still waitting
When you have created your ArrayAdapter you haven't assigned a resizeable List to it, so when you do add() it cannot increment the size of it and throws a UnsupportedOperationException.
Try something like this:
List<CharSequence> planets = new ArrayList<CharSequence>();
adapter = new ArrayAdapter<CharSequence>(context,
R.array.planets_array, planets);
//now you can call adapter.add()
You should use a List. With an Array such as CharSequence[] you would get the same UnsupportedOperationException exception.
Javi is right except don't reference an array for the second parameter.
adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item,
someList);
I believe this is working as designed, but not as expected. ArrayAdapter used to only take an array, but the list constructor was added later. I'm guessing its just doing a toArray() on your list. This is why you have to either call add on the adapter, or create a new adapter when your List changes.
you can create an arraylist and copy all recourse to this object then create arrayadaptor and send this arraylist and in onclicklistener of button, add edittext content to arraylist object then call notifydatasetchanged of adator

Categories

Resources