Android ListView with SQLite - android

I'd like to refresh the Listview items. These items are populated from SQLite database. My code is below
public class Weeve extends Activity {
private String[] lv_arr;
protected ListView CView;
private DBAdapter mDbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
Cursor c = mDbHelper.getAll();
if (c.getCount() > 0)
{if (c.moveToFirst())
{
ArrayList strings = new ArrayList();
do {
String mC = c.getString(0);
strings.add(mC);
} while (c.moveToNext());
lv_arr = (String[]) strings.toArray(new String[strings.size()]);
}
}
else Toast.makeText(this,
"No more Records",
Toast.LENGTH_SHORT).show();
c.close();
ListView CView = new ListView(this);
CView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lv_arr));
setContentView(CView);}}
I'd like to make refreshing this list view after adding, updating or deleting SQLite table. These operations are called by content or option menu. I tried to create these code into a separated function and call it after every operation. But can't. I think setContentView(CView) statement.
I also tried to use SimpleCursorAdapter like notepad sample from Android.com. I got Thread error. Help me.

You can do that using Adapter.notifyDataSetChanged().
However, I find your code slightly off. You're fetching rows from the database using a cursor, just to create a new ArrayAdapter for the row values. Why not use a CursorAdapter to back your list? That's what it's meant for.

make sure all your activities are in the manifest

Related

Retrieve values from database and launch a new activity when listview item is clicked

I created a listview using an adapter. The list view contains elements retrieved from a SQLite database using a distinct query.
When the listview item is clicked, it should retrieve all items which have that value used to do the distinct query.
My query looks like this:
#Override
public List<Registro> distinctByCol3(){
List aux = new ArrayList();
Cursor cursor = db.query(true,Registro.TABLE_NAME,new String[]{
BaseColumns._ID,
RegistroColumns.Col1,
RegistroColumns.Col2,
RegistroColumns.Col3,
},null,null,RegistroColumnas.Col3,null,null,null);
if (cursor.moveToFirst())
do {
Registro registro = this.parseCursorToR(cursor);
if (registro != null)
aux.add(registro);
}
while (cursor.moveToNext()) ;
if(!cursor.isClosed()){
cursor.close();
}
return aux;
}
The java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_registros);
final ListView listView = (ListView) findViewById(R.id.lvRegistros);
DataManager servicio = new DataManagerImpl(this);
List<Registro> listRM = service.getRegistroDistinctedByCol3();
final ArrayAdapter<Registro> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listRM);
listView.setAdapter(adapter);
After click in the element, I need to launch a new activity and show all the elements whit COL3, which is the value I used in my query.
How can I achieved my goal?
If some clarification is needed, let me know. Thanks.

How I retrieve data from SQLite DB in a ListView? [duplicate]

I'd like to refresh the Listview items. These items are populated from SQLite database. My code is below
public class Weeve extends Activity {
private String[] lv_arr;
protected ListView CView;
private DBAdapter mDbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
Cursor c = mDbHelper.getAll();
if (c.getCount() > 0)
{if (c.moveToFirst())
{
ArrayList strings = new ArrayList();
do {
String mC = c.getString(0);
strings.add(mC);
} while (c.moveToNext());
lv_arr = (String[]) strings.toArray(new String[strings.size()]);
}
}
else Toast.makeText(this,
"No more Records",
Toast.LENGTH_SHORT).show();
c.close();
ListView CView = new ListView(this);
CView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lv_arr));
setContentView(CView);}}
I'd like to make refreshing this list view after adding, updating or deleting SQLite table. These operations are called by content or option menu. I tried to create these code into a separated function and call it after every operation. But can't. I think setContentView(CView) statement.
I also tried to use SimpleCursorAdapter like notepad sample from Android.com. I got Thread error. Help me.
You can do that using Adapter.notifyDataSetChanged().
However, I find your code slightly off. You're fetching rows from the database using a cursor, just to create a new ArrayAdapter for the row values. Why not use a CursorAdapter to back your list? That's what it's meant for.
make sure all your activities are in the manifest

How to create a list view from a string variable which is from an SQLite Database

In my database code I am currently going through the ID column of my SQLite database. Now at the moment this is returning a string variable which is listing ALL entries when I put it is a textview for example. But I want to put that variable in some sort of listview (or similar) and for the user to be able to click that listview and bring up the rest of the information relating to that primary key. I have been doing research and have found tutorials to do this but they do not suite what I want to do and didn't exactly work for me. Here is the code below which is in the activity that I want to show the list view. Thanks.
public class View_Saved_Dates extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_saved_dates);
list = (ListView)findViewById(R.id.listView1);
Database info = new Database(this);
info.open();
//I want to put the variable below which lists all data within the id column of my database into a list view or some sort of list where I can
//click the id and bring up the rest of the information in the databse.
String cowid = info.getCowid();
info.close();
}
}
Try the below links-
http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html
http://androidtuts4u.blogspot.in/2012/11/android-sqlite-and-listview-example.html
How to Read Data from SQLite Database and show it on a list view
Display data from SQLite database into ListView in Android
How to get data form SQLite database and display it in ListView
how to fetch the data from sqlite database and show in listview in android
It may help you.
I beleive that this should fix your problem. In your database class, instead of putting all your queried data into a string put it into a string array.
public String[] getid() {
// TODO Auto-generated method stub
ArrayList<String> strings = new ArrayList<String>();
String[] id = new String[]{KEY_ID};
Cursor c = ourDatabase.query(DATABASE_TABLE, id, null, null, null, null, null);
int i = c.getColumnIndex(KEY_ID);
while(c.moveToNext()){ strings.add(c.getString(i));
}
String[] mString = (String[]) strings.toArray(new String[strings.size()]);
return mString;
}
Then in your main class where you want this list view to be displayed create a list view and use the following code and it should work
lv = (ListView)findViewById(R.id.list_view);
Database info = new Database(this);
info.open();
String [] id = info.getid();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, id);
lv.setAdapter(arrayAdapter);
info.close();
I hope that works for you

Items are duplicating each time I start the app in a ListView with SimpleCursorAdapter

ListView is populating with the items from the Cursor wich I pass in the SimpleCursorAdapter, but each time I open the application these items are re-added to the listview increasing it continously. When I use SimpleAdapter, i do something like this:
static final ArrayList<HashMap<String, String>> foobar = new
ArrayList<HashMap<String,String>>();
SimpleAdapter adapter = new SimpleAdapter(this, foobar, R.layout.list_item, String[] from, int[] to);
setListAdapter(adapter);
Doing next, solve my problem:
#Override
public void onDestroy(){
super.onDestroy();
foobar.removeAll(foobar);
}
But now, I don't want to delete the database content,so how to solve it if I have a SimpleCursorAdapter? like this one:
> SimpleCursorAdapter myadapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, String[] from, int[] to);
I have tried setListAdapter(null) or cursor.close(),and many others, but no efect...
Now, these hapen when I exit the application using "back" button of the device. If I press "home" button, when I came back I have the same number of items.So the list is duplicating every time I exit with "back" button.
Solved thanks to Kaediil's answer.The commented lines is what I have improved. The hole class:
public class DataBaseActivity extends ListActivity {
DataBaseMethods dbmet; //is the class that handle database and auxiliar methods working on it
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
dbmet = new DataBaseMethods(this);
Cursor mycursor= dbmet.getItems(); // 1. add new cursor
try{
if(!mycursor.moveToFirst()){ //2.check if there are items in the database
dbmet.addItems("Daniel","Son","Karate-kid");
dbmet.addItems("Silv", "Stalone", "Terminator");
dbmet.addItems("foo", "bar", "buz");
} //
showDatabaseContent();
}
finally{
dbmet.close();
}
}
public void showDatabaseContent(){
DataBaseMethods dbmet = new DataBaseMethods(this);
try{
Cursor cursor = dbmet.getItems();
SimpleCursorAdapter myadapter = new SimpleCursorAdapter(this, R.layout.item_list, cursor, dbmet.FROM, TO);
setListAdapter(myadapter);
}
finally{
dbmet.close();
}
}
Umm, this line is suspect:
If does it matter, I'm populating the database in this activity's onCreate(), but I have tried to populate it also from other activity and I get the same behaviour for the listview.
In the populating of the database call do you check to see if the database is already populated?
It sounds like you just keep adding more copies to the DB that the cursor is pointing to.
public void showDatabaseContent(){
DataBaseMethods dbmet = new DataBaseMethods(this);
try{
Cursor cursor = dbmet.getItems();
SimpleCursorAdapter myadapter = new SimpleCursorAdapter(this, R.layout.item_list, cursor, dbmet.FROM, TO);
setListAdapter(myadapter);
-->> myadapter.notifyDataSetChanged(); <<----
}
finally{
dbmet.close();
}
}
You need to call notifyDataSetChanged() to signal the list to invalidate itself ONLY with the new data.
NOTE:
If the issue is from the Database class. Make sure you are not reinserting items in the database every time you start the application. I might mixed your problem, wither the items are duplicate in the listview or in the database. I'm deeply sure that you are reinserting the data every time you run the app.

Problem using Cursor to populate a spinner

I'm having a problem populating my spinner with data from my SQLite database. Here's the code from my Activity. The Activity crashes with an Unable to start Activity ComponentInfo error where indicated with an arrow.
public class ProjectsActivity extends Activity {
private ReelDbAdapter dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_select);
fillProjectSpinner();
}
private void fillProjectSpinner(){
// initialize cursor to manage data binding to spinner
Cursor projectCursor = null;
Spinner spnExistingProjects = (Spinner)findViewById(R.id.spnExistingProject);
---> projectCursor = dbHelper.getExistingProjects();
//startManagingCursor(projectCursor);
/*
//get the list of project names from the database
String[] from = new String[] {dbHelper.clmProjectName};
//add a new item to the spinner for each of the rows in the database
int [] to = new int[]{R.id.txtViewProjectRow};
//initialize a cursor adapter (similar to ArrayAdapter when populating a spinner from a pre-defined array)
SimpleCursorAdapter projectAdapter = new SimpleCursorAdapter(this, R.layout.view_project_row, projectCursor, from, to);
//add all the rows to the spinner
spnExistingProjects.setAdapter(projectAdapter);
*/
}
Here's the code from the getExistingProjects method from my dbAdapter
public Cursor getExistingProjects() {
if(mDb == null)
{
this.open();
}
return mDb.query(dbTableProject, new String[] {clmProjectName, clmProjectShootingTitle, clmProjectJobNumber},
null, null, null, null, null);
}
Any clues on what I might be doing wrong?
TIA for any help.
Norm
Why don't you try making sure the query is returning something before returning the cursor in your method? Put a log line in that spits out the count of the cursor. Also, you should be able to see this easily while stepping through with the debugger.
Also, why assign null to the cursor's deceleration when you're just going to initialize it a few lines down. Do it all in one line.
Lastly, what db are you trying to one with that this.open() line? I obviously can't tell with just the code you've posted, but put a try catch around that whole thing and spit out the strackTrace. You should see your issue.

Categories

Resources