How can I populate a spinner content from database (SQLite)
I have POJO: categories, contain id and name,
I have the table already, with a function to get the ArrayList like this:
public List<SetcardCategory> getAllSetcardCategory()
{
List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
String selectQuery = "SELECT * FROM " + TABLE_SETCARD_CATEGORIES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
SetcardCategory setcardCategory = new SetcardCategory();
setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
setcardCategory.setName(c.getString(c.getColumnIndex("name")));
// adding to tags list
setcardCategories.add(setcardCategory);
} while (c.moveToNext());
}
return setcardCategories;
}
Then on Activity I call it like this:
List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
this, android.R.layout.simple_spinner_item, setcardCategories);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
sItems.setAdapter(arrayAdapter);
when I run it, it loads string like this: "schema.SetcardCategory#22293c98" and many others values similar to that.
How can I populate the spinner to show the name field as a label, and id field as the value that we fetch to save into DB?
class Pojo{
private String name;
#Override
public String toString() {
return name;
}
}
do it like this in the pojo class, so this will return a value for the object when it uses the to string method in the adapter, to load the data
Solution 1
Overide the toString method in your SetcardCategory class
class SetcardCategory {
...
...
#Override
public String toString() {
return this.name;
}
}
Solution 2
If you just want to show the name, Just pick name only from DB
public List<String> getAllSetcardCategory()
{
List<String> setcardCategories = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_SETCARD_CATEGORIES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
// adding to tags list
setcardCategories.add(c.getString(c.getColumnIndex("name")));
} while (c.moveToNext());
}
return setcardCategories;
}
And create Array Adapter as
List<String> setcardCategories = db.getAllSetcardCategory();
ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
this, android.R.layout.simple_spinner_item, setcardCategories);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Related
Sorry if this is a stupid question but I am new to Android Development. I am trying to create a login screen which will direct doctors to a one activity and nurses to another activity when they login. This does not seem to work. I have put code into the login.java class:
btLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String email = loginemail.getText().toString();
String password = loginpassword.getText().toString();
Boolean Chkemailpass = db.emailpassword(email, password);
if(Chkemailpass == true) {
Cursor typeofuser;
typeofuser = db.checkUser(loginemail.getText().toString()); //get user type from database
if(typeofuser.equals("Nurse")) {
Intent mainintent = new Intent(Login.this, NurseHome.class);
startActivity(mainintent);}
else if (typeofuser.equals("Doctor")){
Intent intent = new Intent(Login.this, DoctorHome.class);
startActivity(intent);}
}
else
Toast.makeText(getApplicationContext(),"Wrong email or password", Toast.LENGTH_SHORT).show();
}
});
}
}
And I also have this code in the databasehelper class relating to the usertype:
public Cursor checkUser(String email) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT TYPEOFUSER from user_table WHERE EMAIL=email", null);
return res;
}
All help would be appreciated, thank you.
The argument email of checkUser() is a string, so in your sql statement it should be enclosed inside single quotes like this:
SELECT TYPEOFUSER from user_table WHERE EMAIL = 'email'
but the correct way to pass parameters to rawQuery() is with the use of ? placeholders and the use of the 2nd argument as an array of string parameters (instead of null).
Also don't return the Cursor, but the type of user as a String from checkUser().
So change to this:
public String checkUser(String email) {
String result = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(
"SELECT TYPEOFUSER from user_table WHERE EMAIL = ?",
new String[] {email}
);
if (res.moveToNext()) {
result = res.getString(0);
}
res.close();
return result;
}
and instead of:
Cursor typeofuser;
typeofuser = db.checkUser(loginemail.getText().toString());
use this:
String typeofuser = db.checkUser(loginemail.getText().toString());
Ive created a class Contact which contains the general structure of my SQL Db. I wish to recieve my data in the form of a List so I use the following code in my MainActivity
List<Contact> contacts = db.getAllContacts();
// Error in this line
ArrayAdapter adapter = new ArrayAdapter<List<Contact>>(this, R.layout.activity_main, contacts);
contactList.setAdapter(adapter);
This gives the error Cannot resolve constructor
the getAllContacts() looks like this
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
So how do I receive my data as List and populate my list?
Template of the ArrayAdapter is the record type, in your case Customer, not List
so correct code will be
ArrayAdapter adapter = new ArrayAdapter<Contact>(this, R.layout.activity_main, contacts);
I have a JSON Array. I'm using DatabaseHelper to transfer the data but I'm not able to fetch the data. I know I'm making a simple mistake but it's just not visible.
This is the onCreate method
arrayList = database.getAllData();
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.activity_list_item,
android.R.id.text1,
arrayList);
listView.setAdapter(adapter);
And this is the getAllData
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
This is something I did once. Can you get an idea from this? :)
public ArrayList<Item_Record> getAllRecords_ArrayList (String Table_Name) {
// Create an array list
ArrayList<Item_Record> List_Of_Records = new ArrayList<>();
// Create a database object
SQLiteDatabase DB = this.getReadableDatabase();
// Create a cursor file we get from executing this above command
Cursor crsr = DB.query(
Table_Name,
new String[] {COLUMN_DATE, COLUMN_CATEGORY, COLUMN_AMOUNT},
null, null, null, null, COLUMN_DATE);
crsr.moveToFirst();
while (! crsr.isAfterLast()) {
// Add that to the array list
List_Of_Records.add(new Item_Record(
crsr.getString(crsr.getColumnIndex(COLUMN_DATE)),
crsr.getString(crsr.getColumnIndex(COLUMN_CATEGORY)),
crsr.getDouble(crsr.getColumnIndex(COLUMN_AMOUNT))));
// Go to the next row
crsr.moveToNext();
}
// Closes database and cursor and return the list
crsr.close(); DB.close();
return List_Of_Records;
}
I have used a database class, datamodel class and main activity in my application. I am not populating spinner values from sqlite database but I am storing selected spinner values in db. I have a text entry too. I declared datamodel object separately.
StudentModel student=new StudentModel();
I have used this is at two diff places.The first one inside Onclick(text)
if(v == findViewById(R.id.add)){
tv.setText("");
student.name = name.getText().toString();
}
The next inside OnItemSelected(Spinner)
student.subject=subject.getItemAtPosition(position).toString();
In the databasehelper class I insert value like
public long addStudentDetail(StudentModel student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SUBJECT, student.subject);
values.put(KEY_NAME, student.name);
long insert = db.insert(TABLE_STUDENT, null, values);
return insert;
}
And in the databasehelper class I retrieve them like
if (c.moveToFirst()) {
do {
StudentModel students = new StudentModel();
students.id = c.getInt(c.getColumnIndexOrThrow(KEY_ID));
students.name = c.getString(c.getColumnIndexOrThrow(KEY_NAME));
students.subject = c.getString(c.getColumnIndexOrThrow(KEY_SUBJECT));
studentsArrayList.add(students);
} while (c.moveToNext());
}
I get java.lang.IllegalArgumentException: column 'subject' does not exist while running.
I am creating a sample gallery app, I am trying to store Gallery Items in local sqlite database
Methods for Adapter.class :
public List<String> getImagePath()
{
ArrayList<String> paths = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + Databaseconnect.TABLE_FILE;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
paths.add(cursor.getString(3).toString());
// Log.d("getPathImage:", cursor.getString(0).toString());
} while (cursor.moveToNext());
}
return paths;
}
than
MuAdapter= new muadapter(Activityname.this);
mudapter.open();
ArrayList<String> list =getImagePath();
but I'm having an error On
ArrayList<String> list =getImagePath();
How to initialize this method? Please Give me a solution.
MuAdapter= new muadapter(Activityname.this);
// this line is broke. Use something like "MuAdapter muAdapter = new ..."
mudapter.open();
// then this line can work
ArrayList<String> list =getImagePath();
// not sure about this, but don't you need an objectrefernece here, that you call getImagePath() on?!