Issue in Data filled in Spinner from Database - android

I have an External Database into assets folder. I have been successful into loading it on my Emulator and performing operations on it.
I also know how to fill data using queries in Spinner and ListView.
The main issue: I am running a query which gives me all data from the table. I store them in a Bean class. Now i have successfully filled one of the column data into a spinner.
BUT, when i open the spinner, i don't get Database values but object name into spinner
FOR e.g -- com.mypackageName.BeanPackage.BeanClass#411da123
I get the whole spinner full of this, not the Data which is in Database( e.g 13, 13/1) .
My Code :
Query in DBHelper Class :
public Cursor getBusNumbers() {
// date="21-10-2013";
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
return db.rawQuery("select * from table", null);
}
In My Main Activity :
Adapter code :
adapter = new Adapter(MainActivity.this,android.R.layout.simple_spinner_item, array);
route.setAdapter(adapter);
adapter.notifyDataSetChanged();
My GetView method:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(layout, null);
}
final Bean item = items.get(position);
final TextView km = (TextView) convertView
.findViewById(android.R.id.text1);
km.setText(item.getRouteNumber());
km.setTextSize(22);
return convertView;
}
}
Method which fills the Array :
private void loadFieldDatabase() {
Cursor c = dbhelper.getBusNumbers();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Bean detail = new Bean();
detail.setRouteNumber(c.getString(c
.getColumnIndex("route_number")));
array.add(detail);
c.moveToNext();
}
c.close();
//dbhelper.close();
}

Here in your code your setting the Bean object into the Text view insted of which item you need to set that.
Try this code this may help you.
private void loadSpinnerCourse() {
// TODO Auto-generated method stub
List<String> lables = getAllCourse();
// Creating adapter for spinner
dataAdapterCourse = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapterCourse
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
mLesson_course.setAdapter(dataAdapterCourse);
}
private List<String> getAllCourse() {
// TODO Auto-generated method stub
List<String> labels = new ArrayList<String>();
mCoureseIdList = new ArrayList<String>();
ExamDatabaseConnector dbConnector = new ExamDatabaseConnector(
getActivity());
dbConnector.open();
String selectQuery = "SELECT * FROM courses_stud";
Cursor cursor = dbConnector.database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
mCoureseIdList.add(cursor.getString(0));
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
dbConnector.database.close();
// returning lables
return labels;
}

Cursor cursor = db.getAllBhashat();
SpinnerArr = new String[cursor.getCount()+1];
SpinnerArr[0] = "<-SELECT->";
if(cursor.moveToNext()){
int i = 1;
do {
SpinnerArr[i] = cursor.getString(cursor
.getColumnIndex("LocalityTitle_E"));
i++;
} while (cursor.moveToNext());
}if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
ArrayAdapter<String> adapter_sorCat = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, SpinnerArr);
Spinner.setAdapter(adapter_sorCat);
adapter_sorCat
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}

Related

Retrieving data from SQLite and displaying in Listview

I am trying to display the contents of my mysqlite database into a listview,
I am able to get the contents and display them in a textview, but for some
reason I can't add the details to an arraylist ? I am not too sure what am doing
wrong. I have looked for multiple solutions but none of them seem to work, am getting an error
Android.database.CursorIndexOutOfBoundsExecption: Index requested -1
Here is what I currently have:
OnCreate:
ArrayAdapter<Contact> currentContactsAdapter = new ContactArrayAdapter();
ListView lvcontacts = (ListView) findViewById(R.id.lvContacts);
lvcontacts.setAdapter(currentContactsAdapter);
tdb = new TestDBOpenHelper(this, "contact.db", null, 1);
sdb = tdb.getWritableDatabase();
new MyContacts().execute();
ListView Adapter:
private class ContactArrayAdapter extends ArrayAdapter<Contact>{
public ContactArrayAdapter(){
super(MainActivity.this, R.layout.listviewitem, addedContacts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.listviewitem, parent, false);
}
Contact currentContact = addedContacts.get(position);
TextView name = (TextView) itemView.findViewById(R.id.tvNameitem);
name.setText(currentContact.getName());
TextView phone = (TextView) itemView.findViewById(R.id.tvPhoneitem);
phone.setText(currentContact.getPhone());
TextView email = (TextView) itemView.findViewById(R.id.tvEmailitem);
email.setText(currentContact.getEmail());
return itemView;
}
}
GetContacts:
class MyContacts extends AsyncTask<String, String, String> {
List<Contact> retrievedContacts = new ArrayList<Contact>();
protected String doInBackground(String... args) {
String cname;
String cphone;
String cemail;
// name of the table to query
String table_name = "contact";
// the columns that we wish to retrieve from the tables
String[] columns = {"FIRST_NAME", "PHONE", "EMAIL"};
// where clause of the query. DO NOT WRITE WHERE IN THIS
String where = null;
// arguments to provide to the where clause
String where_args[] = null;
// group by clause of the query. DO NOT WRITE GROUP BY IN THIS
String group_by = null;
// having clause of the query. DO NOT WRITE HAVING IN THIS
String having = null;
// order by clause of the query. DO NOT WRITE ORDER BY IN THIS
String order_by = null;
// run the query. this will give us a cursor into the database
// that will enable us to change the table row that we are working with
Cursor c = sdb.query(table_name, columns, where, where_args, group_by,
having, order_by);
for(int i = 0; i < c.getCount(); i++) {
cname = c.getString(c.getColumnIndex("FIRST_NAME"));
cphone = c.getString(c.getColumnIndex("PHONE"));
cemail = c.getString(c.getColumnIndex("EMAIL"));
c.moveToNext();
retrievedContacts.add(new Contact(cname,cphone,cemail));
}
return null;
}
//Update Contact list when response from server is received
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
for(Contact contact: retrievedContacts)
addedContacts.add(contact);
}
}
It seems that your table "contact" doesn't have the exact structure you are trying to read.
Android.database.CursorIndexOutOfBoundsExecption: Index requested -1
This means that one of these column names is not part of it.
c.getColumnIndex("FIRST_NAME")
c.getColumnIndex("PHONE")
c.getColumnIndex("EMAIL")
So one of them return -1 instead of the index because they not exist in the table.
EDIT:
Then the for loop may be faulty. I suggest to use something like:
if (c != null ) {
if (c.moveToFirst()) { // Always move at the first item
do {
cname = c.getString(c.getColumnIndex("FIRST_NAME"));
cphone = c.getString(c.getColumnIndex("PHONE"));
cemail = c.getString(c.getColumnIndex("EMAIL"));
retrievedContacts.add(new Contact(cname, cphone, cemail));
} while (c.moveToNext());
}
}
c.close(); // always close when done!

Insert and retrieval from database in android (Stucked in infinite loop)

The problem is i inserted only two rows but on execution it enters into infinite loop and repeatedily showing the same data..Any kind of help would be appreciated
Here is my code.
This is my databse class (i.e DbAdapter)
public Cursor getAllRows() {
String[]columns = new String[]{ KEY_MODEL,KEY_BRAND, KEY_PRICE};
Cursor c = db.query(TABLE_LAPTOPS, columns, null, null, null, null, null);
if (c != null) {
c.moveToLast();
}
return c;
}
This is my main class (i.e Laptops)
DbAdapter obj = new DbAdapter(this);
obj.open();
obj.insertRow("Dell1", "Dell", 345);
obj.insertRow("Hp1", "HP", 546);
obj.close();
obj.open();
Cursor c1 = obj.getAllRows();
try{
if(c1 != null){
ListView empListView = (ListView)findViewById(R.id.listView1);
ArrayList<String> data1 = new ArrayList<String>();
for(c1.moveToFirst();!c1.isAfterLast();c1.moveToNext())
{
Toast.makeText(getApplicationContext(), c1.getString(0), Toast.LENGTH_LONG).show();
}
//empListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1));
}}catch(SQLException e){
e.printStackTrace();
}
obj.close();
c.moveToLast();
here is the issue
c.moveToFirst();
try this..
Try with Like This
listView = (ListView) rootView.findViewById(R.id.Assignment_VM_List);
AssignmentDatabaseConnector dao = new AssignmentDatabaseConnector(getActivity());
List<AssignmentPojo> assignments = dao.getAllAssignmentList();
AssignmentCustomAdapter assignmentCustomAdapter = new AssignmentCustomAdapter(getActivity(),
assignments, this);
listView.setAdapter(assignmentCustomAdapter);
AssignmentDatabaseConnector :
public List<AssignmentPojo> getAllAssignmentList() {
open();
List<AssignmentPojo> assignmentList = new ArrayList<AssignmentPojo>();
// Select All Query
String selectQuery = "SELECT * FROM Assignment";
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) { // ##Your Main Issue is Here ##
do {
AssignmentPojo assignment = new AssignmentPojo();
assignment.setAssign_Id(cursor.getString(0));
assignment.setAssign_Course(cursor.getString(1));
// Adding contact to list
assignmentList.add(assignment);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
// return contact list
return assignmentList;
}
This is just a sample code you can utilize this code according to your requirements

Android: Redundancy issue in datahelper class

I have two tables with names disease_table and sysmptoms_table. I retrieved the data from disease_table from the DB and displayed on the listview and when the listitem is clicked, I have to select and display disease category symptoms accordingly and I did that successfully but my code has redundancy, I had to write two methods in the datahelper class to retrieve the symptoms as per the disease in another listview. and I am retrieving the symptom data in list view with the query with the condition of WHERE "disease_id=1" with foreign key reference
the code for the methods is as follows,
//getting pain symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,symptompain));
public List<String> getAllSymptomPain() {
List<String> symptompain = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=1", null, null, null, null);
if(null != cr){
symptompain = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptompain.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptompain;
}
//getting colorchange symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,symptomcolorchange));
public List<String> getAllSymptomColorChange() {
List<String> symptomcolorchange = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=2", null, null, null, null);
if(null != cr){
symptomcolorchange = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptomcolorchange.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptomcolorchange;
}
How can I write these two in a single method and then call it in class which extends listactivity under onListItemclick method?
And my OnListItemClick() method is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String item=(String)getListAdapter().getItem(position);
if(item.equals("Pain in Teeth")){
// passing the method here
}
else if(item.equals("Pain in Gums")){
// passing the method here
}
else if(item.equals("Pain in Mucosa")){
// passing the method here
}
else if(item.equals("Pain in TMJoint")){
// passing the method here
}
else if(item.equals("Non-Specific Pain")){
// passing the method here
}
}
Try this:
public List<String> getSymptomsByDiseaseId(long diseaseId) {
List<String> symptomsList = new ArrayList<String>();
String selection = "diseaseid=?";
String[] selectionArgs = { String.valueOf(diseaseId) };
Cursor cursor = db.query(false, SYMPTOM_TABLE_NAME, null, selection, selectionArgs, null, null, null, null);
if (cursor.moveToFirst()) {
do {
symptomsList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
return symptomsList;
}

List View Array from Database

I have retrieved data and successfully shown it in text view.
What do I have to modify in my code to make it look like a list view?
And also how do modify my listview programatically(adding size and padding)?
Here is a part of my DBclass in selecting the items that I've displayed
getFAData() {
// TODO Auto-generated method stub
String [] columns = new String[]{Row_Name};
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
String res = "";
int iRow = c.getColumnIndex(Row_Name);
//int iDesc = c.getColumnIndex(Row_Desc);
//int iID = c.getColumnIndex(Row_id);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
res = res + c.getString(iRow) + "\n";
}
return res;
}
And here is the class file:
public class FirstAid extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.firstaid);
displayresult();
}
public void displayresult (){
TextView tvFa = (TextView) findViewById(R.id.tvFA);
tvFa.setMovementMethod(new ScrollingMovementMethod());
DbHelper tblFa = new DbHelper(this);
tblFa.open();
String result = tblFa.getFAData();
tblFa.close();
tvFa.setText(result);
}
}
Create ArrayList int the get data function of database
public ArrayList<String> getFAData() {
ArrayList<String> comments = new ArrayList<String>();
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
int iRow = c.getColumnIndex(Row_Name);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
comments.add(c.getString(iRow ));
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
in your activity retrieve data like this.
ArrayList<String> array = new ArrayList<String>();
array = tblFa.getFAData();
you need to implement a method in your dbhelper class like this
public List<String> selectAll_data() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME_2, new String[] { "str" },
null , null, null, null, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Now in your activity
List<String> events = dh.selectAll_data();
String[] arr = new String[events.size()];
arr = events.toArray(arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
If you want to see a real time example check this url

How to see database values inside the spinner?

I have a spinner and a database so when i click the spinner i want to show the value(name) of the contacts in it but in a simple code. so they are separetated javas and xml layouts the spinner is in the (Novamensagem.java novamensagem.xml) and the contacs database is in the (Adicionarcontato.java adicionarcontato.xml) if you can specify and simply the code is better, thanks
final TextView spinnerContato = (TextView) findViewById(R.id.spinner);
String[] campos = new String[] {"nome", "telefone"};
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
lista = lista + c.getString(c.getColumnIndex("nome")).toString() + "";
if(!c.moveToNext()) break;
}
spinnerContato.setText(lista);
}
thats the code but it gives the erros (more explained in comments)
//
the entire code:
ArrayList<String>() list = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.novamensagem);
db = openOrCreateDatabase("banco.db", Context.MODE_WORLD_WRITEABLE, null);
SalvaMensagem();
//Data e Hora
setCurrentDateOnView();
addListenerOnButton();
setCurrentTimeOnView();
addListenerOnButton2();
//Spinner
DadosSpinner();
}
private void DadosSpinner() {
// TODO Auto-generated method stub
final TextView spinnerContato = (TextView) findViewById(R.id.spinner);
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}`
there is.
Check this
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
This helps you to get an arrayList of items.
Next do this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Be back if you have any issues
To load the spinner data from SQLite database you have to:
Read the contacts from database and save it into the list (for example)
Create an adapter for the spinner
Method would look like this:
private void loadSpinnerData()
{
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> contacts = db.getAllContacts();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, contacts);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
And getAllContacts() method will return all the contacts:
public List<String> getAllConatcts(){
List<String> contacts = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contacts.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning contatcs
return contacts;
}
For more information check this tutorial: http://www.androidhive.info/2012/06/android-populating-spinner-data-from-sqlite-database/

Categories

Resources