Using List<Custom_Class> in ListView - java

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);

Related

Populate spinner from database content (SQLite)

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);

Error while fetching data from SQlite in Android Studio

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;
}

Cannot retrieve spinner values from sqlite database

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.

How to access Sqlite Adapter class to MainActivity using Arraylist?

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?!

How to get values from database[Cursor Adapter] and store it to an array in java?

I would like to get the values from database of a particular column by executing a query. Is it possible to do it after we do it to the Cursor Adapter or can we attain the values well before itself. Kindly help on this with a snippet or a guide.
Context context = getApplicationContext();
final DataBaseHelper db = new DataBaseHelper(context);
...
...
db.createDataBase();
..
...try catch logic etc
....
final Cursor c = db.getAllRows();
....
c.getString(4) // String value of 5th Column in Database
Cursor Adapter to Array
ArrayList<String> mArrayList = new ArrayList<String>();
c.moveToFirst();
while(!c.isAfterLast()) {
mArrayList.add(c.getString(c.getColumnIndex(DataBaseHelper.KEY_NAME));
c.moveToNext();
}
DataBaseHelper class has following
public Cursor getAllRows()
{
return myDataBase.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_NAME,
KEY_YEAR,
KEY_QUOTE,
KEY_REF},
null,
null,
null,
null,
null);
}

Categories