Error while fetching data from SQlite in Android Studio - java

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

Related

Using List<Custom_Class> in ListView

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

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 correctly to close the cursor Android Java

If I try to close the cursor with onSets.close(); in method getData(), the data does not appear in the position. If I do not close the cursor method, then Eclipse complains and says that the base or the cursor is not closed.
But if I add a line c.moveToFirst(); in the method getSets(String toexes_ids, String toprog_dif), the error does not appear. Why is that?
I have two method:
One method in MyDatabase.java
public Cursor getSets(String toexes_ids, String toprog_dif) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"_id", "exes_ids", "sets_ids", "sets_weight", "sets_ones"};
String sqlTables = "Sets";
String selection = "exes_ids = " + toexes_ids + " AND " + "prog_dif = " + toprog_dif;
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, selection, null, null, null, null);
c.moveToFirst();
return c;
}
Second method in MainActivity.java
public void getData() {
db = new MyDatabase(this);
onSets = db.getSets(toexes_ids, toprog_dif);
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.itemsets, onSets,
new String[] {"sets_ids", "sets_weight", "sets_ones"},
new int[] {R.id.itemsets_ids, R.id.itemsets_weight, R.id.itemsets_ones});
listSets.setAdapter(adapter);
db.close();
}
Error:
12-29 16:17:09.335: D/dalvikvm(571): GC_CONCURRENT freed 393K, 53% free 2759K/5767K, external 1574K/1802K, paused 5ms+10ms
12-29 16:17:09.355: E/Database(571): close() was never explicitly called on database '/data/data/com.exp.exp_betta/databases/fitsdbsqlite3'
12-29 16:17:09.355: E/Database(571): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
12-29 16:17:09.355: E/Database(571): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1847)
Try to close the database connection as soon as you finished taking data from it. Remained it open makes the database leaked that's why Eclipse throws the Error For not closing DatabaseObjectNotClosedException
public Cursor getSets(String toexes_ids, String toprog_dif) {
SQLiteDatabase db=getReadableDatabase();
//Querying the database
db.close(); //as you get the cursor you can now close the connection here.
return cursor;
}
public void getData()
{
}
I think you need to close the db instance created in getSets() method

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