Android - How can I retrieve a database row with a WHERE condition? - android

I am trying to fill 2 different ListView with 2 different groups of data based on its "status". My current code runs with no error but my ListViews are not getting filled. I have multiple test data with both complete or incomplete status.
Java code:
public class view_to_do_task extends AppCompatActivity {
private dbasemanager2 dBase2;
private ListView taskList;
private ListView taskList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_to_do_task);
dBase2 = new dbasemanager2(this);
dBase2.openReadable();
taskList = (ListView)findViewById(R.id.incompleteTaskList);
ArrayList<String> dBaseContent = dBase2.retrieveIncompleteRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
taskList.setAdapter(arrayAdpt);
taskList2 = (ListView)findViewById(R.id.completeTaskList);
dBaseContent = dBase2.retrieveCompleteRows();
arrayAdpt = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dBaseContent);
taskList.setAdapter(arrayAdpt);
}
Retrieve Functions:
public ArrayList<String> retrieveIncompleteRows() {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"tid", "task", "status"};
String s = "Incomplete";
Cursor cursor = db.query(DB_TABLE, columns, "status=?", new String[] { s }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
studentRows.add(cursor.getString(0) + ". " + cursor.getString(1));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}
public ArrayList<String> retrieveCompleteRows() {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"tid", "task", "status"};
String s = "Complete";
Cursor cursor = db.query(DB_TABLE, columns, "status=?", new String[] { s }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
studentRows.add(cursor.getString(0) + ". " + cursor.getString(1));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}

Create separate Adapters with separate string list for both ListViews.
I have created seprate string list and adapter below
ArrayList<String> dBaseContent = dBase2.retrieveIncompleteRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
taskList.setAdapter(arrayAdpt);
ArrayList<String> dBaseContentComplete = dBase2.retrieveCompleteRows();
ArrayAdapter<String> arrayAdptComplete = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dBaseContentComplete);
taskList2.setAdapter(arrayAdptComplete);
Where Condition
public ArrayList<String> retrieveIncompleteRows() {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"tid", "task", "status"};
String s = "Incomplete";
//make changes here... and similarly while getting complete records other funtion.
Cursor cursor = db.query(DB_TABLE, columns,
"status = '"+ s + "'", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
studentRows.add(cursor.getString(0) + ". " + cursor.getString(1));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}

Why can't you have one function instead of two with an argument?
public ArrayList<String> retrieveCompleteRows(String s) {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"tid", "task", "status"};
Cursor cursor = db.query(DB_TABLE, columns, "status=?", new String[] { s}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
studentRows.add(cursor.getString(0) + ". " + cursor.getString(1));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}
And you can use a CursorLoader instead of this as that is asynchronous

try this
public ArrayList<String> retrieveIncompleteRows() {
ArrayList<String> studentRows = new ArrayList<>();
String s = "Incomplete";
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_NAME + " = " + s + "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
studentRows.add(cursor.getString(0) + ". " + cursor.getString(1));
} while (cursor.moveToNext());
}
return studentRows;
}

Related

Android - SQLite rawQuery Listview

I am trying to query all the users data that belong to him uniquely. through FK_ID of the user in the notes table.
// Listing all notes
public Cursor listNotes() {
SQLiteDatabase db = help.getReadableDatabase();
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Count how many Notes user has
public int NoteCount() {
String countQuery = "SELECT * FROM " + help.NOTE_TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public void editNote(long id, String title, String body) {
ContentValues edit = new ContentValues();
edit.put(help.COLUMN_TITLE, title);
edit.put(help.COLUMN_BODY, body);
open();
db.update(help.NOTE_TABLE, edit, help.NOTES_ID + "=" + id, null);
close();
}
// Deleting single note
public void deleteNote(long id) {
open();
db.delete(help.NOTE_TABLE, help.NOTES_ID + "=" + id, null);
close();
}
}
I have a tab that will then return all the users data uniquely to him. This tab is a fragment.the Method populateList() will be called onCreateView
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
This is a null pointer. Am i passing the data wrong
Cursor cursor = control.listNotes();
Your listNotes method should look like :
public Cursor listNotes(long userId) {
Cursor c = getActivity().getContentResolver().query(yourTodoTableURI, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, help.COLUMN_USER_ID + " = ?", new String[]{String.valueOf(userId)} , null);
return c;
}
try this:
public List<String> getAllTask(int userID){
String query = "Select * from tablename where ID =" + userID;
cursor = db.query(); //do your code here
int id = cursor.getInt(cursor.getColumnIndex(tablename.ID));
List<String> task = new ArrayList<String>();
String query = "Select * from tableTask where ID =" + id";
cursor = db.query(); //
if (cursor != null) {
cursor.movetofirst();
// do your code here
do{
String task = cursor.get......
task.add(task);
}while(cursor.movetonext);
}
return task;
}

Delete number from contacts

The following code lets me display duplicate contacts.
And when I try to delete, it deletes the duplicated number as well as the original number.
I want it to delete only the duplicated number present in the listview.
Here is my code.
public class MainActivity extends Activity {
ListView listView;
ArrayList<String> listItems = new ArrayList<String>();
Set<String> dupesRemoved = new HashSet<String>();
String[] newList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,order);
Cursor cursor = null;
if(curLog != null) {
while(curLog.moveToNext()) {
String str = curLog.getString(curLog.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//contactid = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
listItems.add(str);
}
}
dupesRemoved = findDuplicates(listItems);
String listString = dupesRemoved.toString();
listString = listString.substring(1,listString.length()-1);
newList = listString.split(", ");
//Arrays.sort(newList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, newList);
listView.setAdapter(adapter);
}
public void deleteDupes(View view) {
String[] info = new String[2];
for (String s : newList) {
info = (getContactInfo(s));
updateContact(info[0],this,info[1]);
listView.invalidateViews();
}
}
public void updateContact(String contactId, Activity act, String type){
/* ASSERT: #contactId alreay has a work phone number */
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String selectPhone = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'" + " AND " + ContactsContract.CommonDataKinds.Phone.TYPE + "=?";
String[] phoneArgs = new String[]{contactId,type /*String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)*/};
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs).build());
try {
act.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
public static Set<String> findDuplicates(List<String> listContainingDuplicates) {
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
for (String yourInt : listContainingDuplicates) {
if (!set1.add(yourInt)) {
setToReturn.add(yourInt);
}
}
return setToReturn;
}
private String[] getContactInfo(String number)
{
String[] contactInfo = new String[2];
ContentResolver context = getContentResolver();
/// number is the phone number
Uri lookupUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.TYPE };
Cursor cur = context.query(lookupUri,mPhoneNumberProjection, null, null, null);
try
{
if (cur.moveToFirst())
{
contactInfo[0] = cur.getString(0);
contactInfo[1] = cur.getString(2);
return contactInfo;
}
}
finally
{
if (cur != null)
cur.close();
}
return contactInfo;
}
}
Use hashmap instead of arraylist to store items in key value pair as duplicate keys are not allowed in a map.
Java code for delete contact:
public static boolean deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return true;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return false;
}
Manifest permission:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

Return String[] From database

I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}

update two tables on click inside a listview and passing parameters for the update

Goodyear to everyone.
well, this is the question, i would like to understand the logic of the listview, and how to retrieve informations on the item clicked in it.
i have done and customized a bunch of tutorials to do this app, and now i'm trying to figure out what i'm doing in this ugly and dirty code.
i have a activity where it lists a series of questions, after you select a category, selecting a question, brings you to the next activity, where some answers are listed and the user could select one. I would like to list ONLY those questions that the user has to answer, instead of all, so i've added a new column to the categories table called "fatta" - "done" in english that i would like to change to 1 when the user clicks the answer of that question.
so the idea was to pass the id of the question, so in the activity where i list al the answers, i could update both the answers and the questions tables, to set to 1 the "done field".
but something goes wrong. here's the code:
The Activity:
public class sondaggioActivity extends ListActivity{
private static final String strdomanda = null;
private pollDataSource datasource;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maindomanda);
long domanda = getIntent().getExtras().getLong("domanda");
TextView text = (TextView) findViewById(R.id.domanda);
String strdomanda = Long.toString(domanda);
// text.setText(strcategory);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getTestoRisposte(strdomanda);
// data? if (values.moveToFirst())
// System.out.println(values.getString(values.getColumnIndex("sondid")));
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_RISPOSTA // Contract class constant containing the word column name
};
int[] mWordListItems = { R.id.categoria_label };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
//values.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
datasource.setRispostaSelezionata(Long.toString(id));
datasource.setDomandaFatta(strdomanda);
datasource.close();
finish();
}
}
as you can see here at the end there is the onListItemClick where i use the strdomanda that i have defined at the top as private static final String strdomanda = null; the datasource is like this:
public class pollDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };
private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_CATID,MySQLiteHelper.COLUMN_WEBID,MySQLiteHelper.COLUMN_FATTA, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID,MySQLiteHelper.COLUMN_WEBID, MySQLiteHelper.COLUMN_RISPOSTA,
MySQLiteHelper.COLUMN_SELEZIONATA };
public pollDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
public void deleteCategoria(categorie categoria) {
long id = categoria.getId();
System.out.println("Categoria cancellata, id: " + id);
database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public sondaggi createSondaggio(String domanda, int catid, int webid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
values.put(MySQLiteHelper.COLUMN_WEBID, webid);
values.put(MySQLiteHelper.COLUMN_FATTA, "0");
long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
sondaggi newSondaggio = cursorToSondaggi(cursor);
cursor.close();
return newSondaggio;
}
public void deleteSondaggio(sondaggi sondaggio) {
long id = sondaggio.getId();
System.out.println("Sondaggio cancellato, id: " + id);
database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public Cursor getAllCategorie() {
List<categorie> categorie = new ArrayList<categorie>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
categorie categoria = cursorToCategorie(cursor);
categorie.add(categoria);
cursor.moveToNext();
}
// Make sure to close the cursor
// cursor.close();
return cursor;
}
public Cursor getDomanda(String id) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_ID + "=?",
new String[] { id }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
private categorie cursorToCategorie(Cursor cursor) {
categorie categorie = new categorie();
categorie.setId(cursor.getLong(0));
categorie.setPreferita(cursor.getLong(1));
categorie.setNome(cursor.getString(2));
return categorie;
}
private sondaggi cursorToSondaggi(Cursor cursor) {
sondaggi sondaggi = new sondaggi();
sondaggi.setId(cursor.getLong(0));
sondaggi.setDomanda(cursor.getString(1));
sondaggi.setCatid(cursor.getLong(2));
sondaggi.setwebid(cursor.getLong(3));
return sondaggi;
}
public Cursor getAllDomandeCategoria(String catid) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_CATID + "=?",
new String[] { catid }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
public Cursor getTestoRisposte(String strdomanda) {
List<testo_risposte> domande = new ArrayList<testo_risposte>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_TESTORISPOSTE,
allRisposteColumns,
MySQLiteHelper.COLUMN_SONDID + "=?",
new String[] { strdomanda }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
testo_risposte sondaggio = cursorToTestoRisposte(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
private testo_risposte cursorToTestoRisposte(Cursor cursor) {
testo_risposte testo_risposte = new testo_risposte();
testo_risposte.setId(cursor.getLong(0));
testo_risposte.setCatid(cursor.getLong(1));
testo_risposte.setWebid(cursor.getLong(4));
testo_risposte.Setselezionata(cursor.getLong(2));
testo_risposte.setDomanda(cursor.getString(3));
return testo_risposte;
}
public void setRispostaSelezionata(String id) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_SELEZIONATA, "1");
database.update(MySQLiteHelper.TABLE_TESTORISPOSTE,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { id });
}
public void setDomandaFatta(String strdomanda) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_FATTA, "1");
database.update(MySQLiteHelper.TABLE_SONDAGGI,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { strdomanda });
}
}
but as i run the activity, only the first updadate gone good, the other one, the one with which i would like to "deactivate" the question... does nothing... i suppose that the way i pass the strdomanda is not the good way. Any help? Advice? thanks in advance.
SOLVED:
i have mistaken this line:
private static String strdomanda = null;
I have deleted the Final property and i have deleted the other declaration of the same variable...
now it works.

List View Array from Database

I have retrieved data and successfully shown it in text view.
What do I have to modify in my code to make it look like a list view?
And also how do modify my listview programatically(adding size and padding)?
Here is a part of my DBclass in selecting the items that I've displayed
getFAData() {
// TODO Auto-generated method stub
String [] columns = new String[]{Row_Name};
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
String res = "";
int iRow = c.getColumnIndex(Row_Name);
//int iDesc = c.getColumnIndex(Row_Desc);
//int iID = c.getColumnIndex(Row_id);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
res = res + c.getString(iRow) + "\n";
}
return res;
}
And here is the class file:
public class FirstAid extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.firstaid);
displayresult();
}
public void displayresult (){
TextView tvFa = (TextView) findViewById(R.id.tvFA);
tvFa.setMovementMethod(new ScrollingMovementMethod());
DbHelper tblFa = new DbHelper(this);
tblFa.open();
String result = tblFa.getFAData();
tblFa.close();
tvFa.setText(result);
}
}
Create ArrayList int the get data function of database
public ArrayList<String> getFAData() {
ArrayList<String> comments = new ArrayList<String>();
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
int iRow = c.getColumnIndex(Row_Name);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
comments.add(c.getString(iRow ));
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
in your activity retrieve data like this.
ArrayList<String> array = new ArrayList<String>();
array = tblFa.getFAData();
you need to implement a method in your dbhelper class like this
public List<String> selectAll_data() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME_2, new String[] { "str" },
null , null, null, null, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Now in your activity
List<String> events = dh.selectAll_data();
String[] arr = new String[events.size()];
arr = events.toArray(arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
If you want to see a real time example check this url

Categories

Resources