How to Fill a Spinner with Database Info - java

I have a spinner that I need to fill with information from a database, but the examples that i found don't work.
Here is my code:
public void consulta() {
AdminSQLiteOpenHelper admin =
new AdminSQLiteOpenHelper(this, "administracion", null, 1);
SQLiteDatabase bd=admin.getWritableDatabase();
Cursor c = bd.rawQuery("select name from category",null);
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"name"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spinner1.setAdapter(adapter);
bd.close();
}

This is how I do it:
db = SQLiteDatabase.openDatabase("/data/data/packagename/databases/mydata.db", null, SQLiteDatabase.OPEN_READONLY);
Cursor c_cat = db.rawQuery("select _id, column_desc from your_table", null);
startManagingCursor(c_cat);
spinner = (Spinner) findViewById(R.id.spinnername);
String[] from = new String[]{"column_desc"};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c_cat, from, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mAdapter);
db.close();
I did all that in my onCreate. I declared all my variables outside the method so that they are public to the whole class. One thing I made a mistake of in the past was closing the cursor after filling the spinner. The cursor must remain open if you want to see data in the spinner.
I hope this solves it for you.
EDIT: I noticed you are not querying for _id in your rawQuery. You must include that if you wish to populate the spinner. Analyze the code I provided.

Assuming you didn't leave any code out, you need to find/define spinner1, so that the framework knows where to put your info from the adapter.
private Spinner spinner1;
spinner1 = (Spinner) view.findViewById(R.id.yourspinnerid);
// rest of your code

Related

How to add EditText's value to the listview items?

I want to add the content from an EditText to a ListView here is my code that dosen't work:
mass = userInput.getText().toString();
//fruits is a String[]
final List<String> fruits_list = new ArrayList<String(Arrays.asList(fruits));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context.getApplicationContext(), android.R.layout.simple_list_item_1, fruits_list);
fruits_list.add(mass);
lv.setAdapter(arrayAdapter);
The code adds the item to the listview but when the process is repeated it replaces the previously added string from the EditText.
Your code appears to create a new fruits_list array every time you read the user's entry from the EditText. This will result in only the latest entry being added to your list, replacing any previously added entries.
You need to create the array once (probably as a class member) and then update it each time you read the user input, e.g. something like:
private ArrayList<String> fruits_list;
private ArrayAdapter<String> arrayAdapter;
...
public void initialise(Context context) {
fruits_list = new ArrayList<>(Arrays.asList(fruits));
arrayAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, fruits_list);
lv.setAdapter(arrayAdapter);
}
....
public void getInput(
mass = userInput.getText().toString();
fruits_list.add(mass);
arrayAdapter.notifyDataSetChanged();
}
Note the use of arrayAdapter.notifyDataSetChanged() to signal that new data has been added to the underlying data set.
As #Aaron says, you should also look at RecyclerView as a possible replacement, although that's a little bit more complicated to set up.

Speed up Listview load and sort it

I have small Android app, but the Sqlite database is big, and the form loading is slow. How Can I speed up Listview load and sort it by name?
My code is here:
public void nameload(){
ArrayList<String> names = new ArrayList<String>();
db = openOrCreateDatabase(Adatbazis, MODE_PRIVATE, null);
Cursor Namecursor = db.rawQuery("select DISTINCT name from Table WHERE ztr='"+ztrcode+"'", null);
Namecursor.moveToFirst();
String name = "";
while (!Namecursor.isAfterLast()) {
name = "" + Namecursor.getString(Namecursor.getColumnIndex("name"));
names.add(name);
Namecursor.moveToNext();
}
//A tömb elemeinek betöltése a UI-ba
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
names);
namelist.setAdapter(adapter1);
Namecursor.close();
}
Thank you for help me :)
Always remember Closing the cursor after setAdapter() may prevent the adapter from accessing the data which makes the loading slow.
So move your Namecursor.close(); after the loop, before ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(..)

After Binded Spinner , How to Do not select first item?

public void DatabaseConn(){
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Driver", null);
startManagingCursor(c);
//create an array to specify which fields we want to display
String[] from = new String[]{"Driver_Name"};
//create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
//create simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//get reference to our spinner
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
s.setAdapter(adapter);
db.close();
}
This is the code how i bind my Spinner with my DataBase,
But After Binded Spinner, will automatically selected first item,
i would like to let User select the Spinner by themself, how to do with this?
read this documentation page: http://developer.android.com/reference/android/widget/AbsSpinner.html
Just add a default selection after populating the spinner something like --select driver-- then do a check in your listener to not do anything when the spinner position is 0
SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Vehicle", null);
//=====Add Additional=====
MatrixCursor extras = new MatrixCursor(new String[] { "_id", "Plat_No" });
extras.addRow(new String[] { "-1","< Select Vehicle >" });
Cursor[] cursors = { extras, c };
c = new MergeCursor(cursors);
//===========================
Just Add the First Items as blank or i have added "< Select Vehicle >" as the first item

How to display data fetched from the database table into listview?

My Function In SQLAdapter class is
public ArrayList<Airline> getairlinedetails(String bookingdate) {
Cursor curCalllog =db.rawQuery("SELECT * FROM "+ BOOK +
" WHERE " + date +
" BETWEEN '" + startdate + "' AND '" + enddate + "'", null);
if (curCalllog != null) {
if (curCalllog.moveToFirst()) {
do {
a=new Airline();
//a.setBookingdate(curCalllog.getString(1));
a.setPickupadd(curCalllog.getString(2));
a.setCity(curCalllog.getString(3));
a.setTrip(curCalllog.getString(4));
a.setFdate(curCalllog.getString(5));
a.setFtime(curCalllog.getString(6));
a.setCdate(curCalllog.getString(7));
a.setPtime(curCalllog.getString(8));
a.setSeats(curCalllog.getInt(9));
a.setAmount(curCalllog.getInt(10));
update.add(a);
} while (curCalllog.moveToNext());
}
}
return update;
}
M Fetching data between two dates and
I Want To show the fetched data into listview please help me how to do it I m new in android development.
You can use SimpleCursorAdapter for showing Databse contents in Listview. Make instance of SimpleCursorAdapter and pass Cursor object into it. Refer this link
If you want Customized Listview, you can customize SimpleCursorAdapter by extending this with your custom adapter class.
you can follow this example :
DataManipulator.java -helper class
//to retrieve data in a list
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","name","number","skypeId","address" },
null, null, null, null, "name asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
CheckData.java
// to show data in a list view
public class CheckData extends ListActivity {
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] name : names2) {
stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,
stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(stg1[position]);
}
}
follow this link for complete tutorial
I assume you are getting data from database and there by complete ArrayList with Airline objects.
Now to display data in ListView from ArrayList<Airline>, you have to define Custom adapter class by extending either BaseAdapter or ArrayAdapter.
Here you go: How to define custom adapter for ListView?
I Want To show the fetched data into listview please help me how to do
it I m new in android development
Simpliest way is to use ArrayAdapter with build-in ListView's row layout.
ListView list = (ListView) findViewById(R.id.yourList);
ArrayList<Airline> data = db.getairlinedetails("someString");
ArrayAdapter<Airline> adapter = new ArrayAdapter<Airline>(this,
android.R.layout.simple_list_item_1, data);
list.setAdapter(adapter);
But since this you need to also override toString() method in your Airline class.
Reason is that your ArrayAdapter will convert each child(provided list of airlines) to String and if you won't override toString() you will get default string representation of object but you probably need to show for instance name of airline so your method can looks like
#Override
public String toString() {
return this.name;
}
Note:
This is simple way. But if you want to get more control over ListView and create custom list i recommend you to create own subclass of ListAdapter for example BaseAdapter and define your own Adapter. Sorry but i won't write you implementation because it requires much more code but nice examples you can find here:
Customizing Android ListView Items with Custom ArrayAdapter
Android ListView, ListActivity and ListFragment - Tutorial
Android Custom ListView with Image and Text

Show two columns from SQLite as same string in a listview in android

Hi I am developing an android in which I am loading data from database and showing it in a List View.
My code is as follows
public class rel extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.refill);
//Creating an object called mydbhelper
Dbms mydbhelper = new Dbms(this);
//Loading the database in writable format
SQLiteDatabase db=mydbhelper.getWritableDatabase();
String[] id= new String[]{"_id","medicine","hs"};
//Cursor
Cursor c = db.query("medicines",id,null,null,null, null,null);
startManagingCursor(c);
String[] from = new String[]{"medicine"};
int[] to = new int[] { R.id.textlist1};
// Now creating an array adapter and set it to display using my row
SimpleCursorAdapter notes =new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
What i want to achieve is show a list view as "Medicine-hs" in which medicine is from one column and hs is from an another column of database. For example as
XYZ-HS1
ABC-HS2
as the listview contents
How to achieve this?
Right now I am able to get only Medicine
Please give your kind suggestions
}
I want to say replace this:
String[] from = new String[]{"medicine"};
int[] to = new int[] { R.id.textlist1};
with this:
String[] from = new String[]{"medicine", "medicine-hs"};
int[] to = new int[] { R.id.textlist1, R.id.textlist2};
You will of course need to have a R.id.textlist2 available to use in your layout.
EDIT: Reverted back to the previous revision, which solved the problem.
What you could do is execute the rawQuery() method off the DBHelper class with SQL that combines the fields like so:
SELECT medicine + "-" + hs AS medicineHs FROM medicines ...
so the string array would be
String[] from = new String[]{"medicineHs"};

Categories