How to access Sqlite Adapter class to MainActivity using Arraylist? - java

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

Related

ConcurrentModificationException when im not modifying the array?

I'm getting java.util.ConcurrentModificationException and i don't know why.
In the Logcat it points to this code but i don't see anything that could cause a ConcurrentModificationException.
private void initRecyclerView() {
Main.musicList = Main.songs.songs;
Log.d(TAG, "Main.musicList: " + String.valueOf(Main.musicList));
if ((Main.musicList != null) && (!Main.musicList.isEmpty())) {
// Connects the song list to an adapter
// (Creates several Layouts from the song list)
allSongsAdapter = new AllSongsAdapter(getActivity(), Main.musicList);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerViewSongs.setLayoutManager(linearLayoutManager);
recyclerViewSongs.setHasFixedSize(true);
recyclerViewSongs.setAdapter(allSongsAdapter);
}
}
Main.musicList is a public static ArrayList musicList = null; in another class.
And Main.songs.songs is a public ArrayList songs = null; in my class where i get all the songs on the device and populate the arraylist with them.
in onDestroy i call:
musicList = null;
EDIT
Ok i found the problem, when i'm not calling onDestroy musicList = null there is no ConcurrentModificationException.
But how do i dereference an arraylist in onDestroy so it can be garbage collected?
EDIT
So the problem wasn't the onDestroy call, the error occurs when i open the app and my arraylists are populated with all songs, then i close the app and reopen it and then the exception is thrown.
How i populate the songs array
songs = new ArrayList<>();
// Columns retrieved from the system database (MediaStore.Audio.Media).
String[] projection1 = {
SONG_ID,
SONG_TITLE,
SONG_ARTIST,
SONG_ALBUMID,
SONG_ALBUM,
SONG_FILEPATH,
SONG_DURATION,
SONG_YEAR,
};
// Limits results to only show MUSIC files.
// It's a SQL "WHERE" clause - it becomes `WHERE IS_MUSIC NOT EQUALS ZERO`.
final String musicsOnly = SONG_IS_MUSIC + "!=0";
// Querying the Media DATABASE.
cursor = resolver.query(musicUri, projection1, musicsOnly, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
do {
// Creating a SONG from the VALUES in each column.
Song song = new Song(cursor.getLong(cursor.getColumnIndexOrThrow(SONG_ID)),
cursor.getString(cursor.getColumnIndexOrThrow(SONG_FILEPATH)));
song.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(SONG_TITLE)));
song.setArtist(cursor.getString(cursor.getColumnIndexOrThrow(SONG_ARTIST)));
song.setAlbumID(cursor.getLong(cursor.getColumnIndexOrThrow(SONG_ALBUMID)));
song.setAlbum(cursor.getString(cursor.getColumnIndexOrThrow(SONG_ALBUM)));
song.setDuration(cursor.getLong(cursor.getColumnIndexOrThrow(SONG_DURATION)));
song.setYear(cursor.getInt(cursor.getColumnIndexOrThrow(SONG_YEAR)));
// Using the previously created maps to add the current song GENRE.
String currentGenreID = songIdToGenreIdMap.get(Long.toString(song.getId()));
String currentGenreName = genreIdToGenreNameMap.get(currentGenreID);
song.setGenre(currentGenreName);
// Adding the Song to the global array list 'songs'.
songs.add(song);
} while (cursor.moveToNext());
}
}catch (Exception e){
// Exception caught because no songs were found.
Log.e(TAG, "Exception caught because no songs were found!", e);
throw new Exception();
}finally {
if (cursor != null ){
cursor.close();
}
}
Here is a high level approach which will allow GC to clear your memory properly.
Inside your Activity class define member:
private List<Song> mMySongs;
In onCreate method, you init RecyclerView and then read songs to the array:
// getSongs is your models method where you read the songs and return them as array
mMySongs = getSongs();
// Enter code to create the adapter and set it for RecyclerView
Now that you are using strong reference instead of static reference, when your Activity is destroyed, GC can clear up the memory and when you relaunch the Activity it will query the songs again.

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

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

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

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