I am learning android programming and I am writing a small SQL to list app to get "comments" out of DB and put them on a list using a custom CursorAdapter. It all seems to be functional BUT on add/delete the list doesn't repopulate (delete seems to not function at all). I am calling changeCursor() but it does not appear as though my list updates. After a fresh run I can see the results of the previous run. Any help is greatly appreciated.
Here is my code:
CommentsDataSource.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class CommentsDataSource {
private MySQLiteHelper SQLhelper;
private SQLiteDatabase database;
public CommentsDataSource (Context context) {
// Create a link to database:
SQLhelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = SQLhelper.getWritableDatabase();
}
public void close () {
database.close();
}
public Comment createComment (String comment) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
long id = database.insert(MySQLiteHelper.TABLE_COMMENTS, null, values);
Cursor cursor = database.rawQuery("SELECT * FROM " + MySQLiteHelper.TABLE_COMMENTS + " WHERE " + MySQLiteHelper.COLUMN_ID + " = " + id, null);
cursor.moveToFirst();
Comment newComment = new Comment();
newComment.setId(cursor.getLong(0));
newComment.setComment(cursor.getString(1));
cursor.close();
return newComment;
}
public void deleteComment (Comment comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<Comment> getAllComments () {
List<Comment> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM " + MySQLiteHelper.TABLE_COMMENTS, null);
cursor.moveToFirst();
Comment newComment = new Comment();
while (! cursor.isAfterLast()) {
newComment.setId(cursor.getLong(0));
newComment.setComment(cursor.getString(1));
list.add(newComment);
cursor.moveToNext();
}
cursor.close();
return list;
}
public Cursor getCursor() {
List<Comment> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM " + MySQLiteHelper.TABLE_COMMENTS, null);
return cursor;
}
}
MainActivity:
public class MainActivity extends ListActivity {
private CommentsDataSource dataSource;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context= this;
dataSource = new CommentsDataSource(this);
dataSource.open();
List<Comment> values = dataSource.getAllComments();
/*ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_expandable_list_item_1, values);
setListAdapter(adapter);*/
Cursor cursor = dataSource.getCursor();
ListView lvItems = (ListView) findViewById(android.R.id.list);
CustomCursorAdapter adapter = new CustomCursorAdapter(this, cursor);
lvItems.setAdapter(adapter);
}
public void onClick(View view) {
#SuppressWarnings("unchecked")
Cursor cursor = dataSource.getCursor();
CustomCursorAdapter adapter = new CustomCursorAdapter(context, cursor);
Comment comment = null;
switch (view.getId()) {
case R.id.add:
String[] comments = new String[] { "Cool", "Very nice", "Hate it" };
int nextInt = new Random().nextInt(3);
// save the new comment to the database
comment = dataSource.createComment(comments[nextInt]);
break;
case R.id.delete:
if (adapter.getCount() > 0) {
Cursor d = (Cursor) adapter.getItem(0);
comment = new Comment();
comment.setComment(d.getColumnName(1));
dataSource.deleteComment(comment);
}
break;
}
Cursor newcursor = dataSource.getCursor();
adapter.changeCursor(newcursor);
}
}
customCursorAdapter:
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView type = (TextView) view.findViewById(R.id.setType_textView);
TextView name = (TextView) view.findViewById(R.id.exerciseName_textView);
name.setText(cursor.getString(1));
}
}
Related
I am trying to view the content of my database by listing it in a ListView. What am i doing wrong? The goal is to load a list of the database data when the page loads after a button click on the homepage.
The XML page simply has a ListView, named "studentList", inside a ScrollView
Java code:
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
This is openReadable() Function:
public dbasemanager openReadable() throws android.database.SQLException {
helper = new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
}
This is the retrieveRows() Function:
public ArrayList<String> retrieveRows() {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"sid", "first_name", "last_name"};
Cursor cursor = db.query(Table_Name, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
studentRows.add(cursor.getString(0) + ", " + cursor.getString(1)
+ ", " + cursor.getString(2));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}
Logcat:
There is a null pointer in line 17.
You need to construct databasemanager object before call it
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
// construct databasemanager
dBase = new dbasemanager(...);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
BTW, I recommend you to use java code conventions to name classes.
For example: edit_student should be editStudent and dbasemanager should be DBManager or DbManager.
I need help with summing all the values in one of the columns(amount) in my database. i can a get a particular value. .but i need sum of a specific column, somebody tell me what I'm doing wrong
This is my code
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
ArrayList<String> records = databaseAdapter.fetchAllRecords();
if (records.size() > 0) {
et.setText(records.get(0));
}
databaseAdapter.close();
}
});
//Create our database by opening it and closing it
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
databaseAdapter.close();
}
private Object append(CharSequence text) {
// TODO Auto-generated method stub
return null;
}
/** Create a new dialog for date picker */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
}
return null;
}
}
This is the database part DatabaseAdapter.java
package com.example.androidtablayout;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
public class DatabaseAdapter {
private Context context;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
this.context = context;
}
public DatabaseAdapter open() throws SQLException {
dbHelper = new DatabaseOpenHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createRecord(String text,int j,String text1,String text2) {
ContentValues contentValue = new ContentValues();
contentValue.put("date", text);
contentValue.put("amount", j);
contentValue.put("des", text1);
contentValue.put("category", text2);
return database.insert("Extable", null, contentValue);
}
public boolean updateRecord(long rowId,String text,int j,String text1,String text2) {
ContentValues contentValue = new ContentValues();
contentValue.put("date", text);
contentValue.put("amount", j);
contentValue.put("des", text1);
contentValue.put("category", text2);
return database.update("Extable", contentValue, "_id =" + rowId, null) > 0;
}
public boolean deleteRecord(long rowId) {
return database.delete("Extable", "_id =" + rowId, null) > 0;
}
public ArrayList<String> fetchAllRecords() {
Cursor cursor = database.query("Extable", new String[] { "_id", "date", "amount", "des", "category"},
null, null, null, null, null);
ArrayList<String> records = new ArrayList<String>();
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
records.add(cursor.getString(1));
cursor.moveToNext();
}
cursor.close();
return records;
}
public String fetchRecord(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "Extable", new String[] { "_id",
"date","amount", "des","category" }, "_id ="+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getString(1));
}
return null;
}
public Cursor rawQuery(String string, Object object) {
// TODO Auto-generated method stub
return null;
}
Pls anyone help to me.
Thank u
Do so:
Cursor cur = db.rawQuery("SELECT SUM(myColumn) FROM myTable", null);
if(cur.moveToFirst())
{
return cur.getInt(0);
}
this is what i have done, to retrieve the id but it says that getIndexColumn is not defined in the cursor... what i'm doing wrong?
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor data = (Cursor)l.getItemAtPosition(position);
String cat = Cursor.getString(Cursor.getIndexColumn(MySQLiteHelper.COLUMN_ID));
Intent myIntent = new Intent(MainActivity.this, sondaggioActivity.class);
myIntent.putExtra("categoriaId", cat);
MainActivity.this.startActivity(myIntent);
}
this is the category class:
public class categorie {
private long id;
private String nome;
private long preferita;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public long getPreferita() {
return preferita;
}
public void setPreferita(long preferita) {
this.preferita = preferita;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return nome;
}
}
and this is the datasource:
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_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID, 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) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
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;
}
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));
return sondaggi;
}
}
the main activity:
public class MainActivity extends ListActivity {
private pollDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getAllCategorie();
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_NOME // 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);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.add:
datasource.createCategoria("peppe");
break;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent myIntent = new Intent(MainActivity.this, sondaggioActivity.class);
myIntent.putExtra("categoriaId", id);
MainActivity.this.startActivity(myIntent);
//Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
I assume you have an activity with a list of categories, and onClick of a particular item you want to launch new activity with details of that Item.
I suggest you when you launch the listScreen, query all/some items and maintaine an arrayList of items and save that in some singleton class, then onClick of a particular item pass that index to detail screen via intent.putExtra("index", position) and on detail Screen get that index via getIntent().getIntExtra("index", -1) .now get details of that particular index from arraylist saved in singleton class.
This approach will reduce cost of querying every time from database and data will be available easily.
Change
Cursor data = (Cursor)l.getItemAtPosition(position);
String cat = Cursor.getString(Cursor.getIndexColumn(MySQLiteHelper.COLUMN_ID));
to
Cursor data = (Cursor)l.getItemAtPosition(position);
Long clid = data.getLong(data.getIndexColumn(MySQLiteHelper.COLUMN_ID));
String cat=Long.toString(clid);
those two lines:
Cursor data = (Cursor)l.getItemAtPosition(position);
String cat = Cursor.getString(Cursor.getIndexColumn(MySQLiteHelper.COLUMN_ID));
makes absolutely no sense at all! If you're using a CursorAdapter why are you creating an array of objects? If you're using a ArrayAdapter why are you getting data from cursor?
Also, Cursor don't have any static methods to be called like that. That shouldn't even compile.
If you're using a CursorAdater (or some class that extend it) you the id is passed to you long id here protected void onListItemClick(ListView l, View v, int position, long id)
I have to implement a listview in which my current data comes on top of the listview. Right now my recent data comes at the bottom and my first data is coming on the top of the listview. I'm attaching my work so far:
SearchActivity.java
public class SearchActivity extends Activity implements OnClickListener,
OnItemClickListener {
private EditText mHistoryNameEditText;
private Button mInsertButton;
private ListView mHistoryListView;
private ListAdapter mHistoryListAdapter;
private ArrayList<SearchHistoryDetails> searchArrayList;
private ArrayList<SearchHistoryDetails> HistoryObjArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHistoryNameEditText = (EditText) findViewById(R.id.editText1);
mInsertButton = (Button) findViewById(R.id.button1);
mInsertButton.setOnClickListener(this);
mHistoryListView = (ListView) findViewById(R.id.names_lsitviews);
mHistoryListView.setOnItemClickListener(this);
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
HistoryObjArrayList = new ArrayList<SearchHistoryDetails>();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
String providedUgraduateName = mHistoryNameEditText.getText()
.toString();
SearchHistoryDetails undergraduateDetailsPojoObj = new SearchHistoryDetails();
undergraduateDetailsPojoObj.setuGraduateName(providedUgraduateName);
HistoryObjArrayList.add(undergraduateDetailsPojoObj);
insertUndergraduate(undergraduateDetailsPojoObj);
finish();
}
}
public void insertUndergraduate(
SearchHistoryDetails paraUndergraduateDetailsPojoObj) {
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(
this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj
.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME,
paraUndergraduateDetailsPojoObj.getuGraduateName());
long affectedColumnId = sqliteDatabase.insert(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, contentValues);
sqliteDatabase.close();
Toast.makeText(this,
"Values inserted column ID is :" + affectedColumnId,
Toast.LENGTH_SHORT).show();
}
public List<String> populateList() {
List<String> uGraduateNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null,
null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String ugName = cursor
.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME));
SearchHistoryDetails ugPojoClass = new SearchHistoryDetails();
ugPojoClass.setuGraduateName(ugName);
searchArrayList.add(ugPojoClass);
uGraduateNamesList.add(ugName);
}
sqliteDatabase.close();
return uGraduateNamesList;
}
#Override
protected void onResume() {
super.onResume();
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
}
#Override
protected void onStart() {
super.onStart();
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Clicked on :" + arg2,
Toast.LENGTH_SHORT).show();
SearchHistoryDetails clickedObject = searchArrayList.get(arg2);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedUgraduateName",
clickedObject.getuGraduateName());
}}
This class helps me in getting the data from the database and populating it on the activity. My creating database class:
AndroidOpenDbHelper.java
public class AndroidOpenDbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "allsearch_history_db";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME_GPA = "search_table";
public static final String COLUMN_NAME_UNDERGRADUATE_NAME = "undergraduate_name_column";
public AndroidOpenDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sqlQueryToCreateUndergraduateDetailsTable = "create table if not exists "
+ TABLE_NAME_GPA
+ " ( "
+ BaseColumns._ID
+ " integer primary key autoincrement, "
+ COLUMN_NAME_UNDERGRADUATE_NAME
+ " text not null); ";
db.execSQL(sqlQueryToCreateUndergraduateDetailsTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
// Upgrade the database
}
}}
This is the class from which I create database and table.
Now, the real deal is that, when I try to populate data from the database it comes as the first one on top and the latest one on down. I want to revert it. Any help will be appreciated in overcoming this problem.
There are a few different ways to do this. I recommend using the ORDER BY clause of your query:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null,
AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME + " DESC");
Also if you are only going to read from one column, your query should only request that column. Otherwise you are wasting resources querying unused columns of information:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA,
new String[] {AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME},
null, null, null, null,
AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME + " DESC");
Lastly, you may want to look into using a SimpleCursorAdapter which allows you to bind a query to a ListView with minimal code.
Addition
I took a closer look at your code and try this:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null,
BaseColumns._ID + " DESC");
Well i can suggest you to get the data from the database and add the items in the reverse order in the adapter that you are setting for populating the listview.
Consider this as the sample where you can get the values from the database which returns an arraylist.
Now consider this arraylist and add each item to the arrayadapter from the last like :
for(i=arraylist.size()-1;i>0;i--)
{
adapter.add(arraylist.get(i));
}
and after setting for the first time you can call
adapter.notifyDataSetChanged()
to refresh the list automatically.
Give a try to this
When my fragment is built, I build the View from information in my local Database. Other tabs can modify this information, and when the user selects the tab, I would like the new information to be reflected.
public class RunningTotal extends SherlockFragment {
public static final String TAG = "Running Total";
private LinearLayout lv;
public View onCreateView(LayoutInflater li, ViewGroup vg,
Bundle savedInstanceState) {
SalesDataSource sds = BarcodeSaleTracker.SDS;
ArrayList<Item> items = sds.getAllItems();
String[] totals = sds.getPersonValues();
int totalsPosition = 0;
Log.v(TAG, "Items Length: " + items.size());
lv = new LinearLayout(this.getActivity());
String lastPerson = "";
if (items.size() > 0) {
for (Item i : items) {
if (lastPerson.equalsIgnoreCase(i.getPerson()) == false) {
lastPerson = i.getPerson();
TextView tv = (TextView) li.inflate(R.layout.list_title,
lv, false);
tv.setText(totals[totalsPosition]);
totalsPosition++;
lv.addView(tv);
}
TextView listItem = (TextView) li.inflate(R.layout.list_item,
lv, false);
listItem.setText(i.toString());
lv.addView(listItem);
}
} else {
TextView noItems = (TextView) li.inflate(R.layout.list_title, lv,
false);
noItems.setText(R.string.no_items);
lv.addView(noItems);
}
return lv;
}
}
It's a tabbed format, nearly identical to the Sherlock example:
public class BarcodeSaleTracker extends SherlockFragmentActivity {
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
public static SalesDataSource SDS;
public BarcodeSaleTracker() {
}
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Sherlock___Theme);
super.onCreate(savedInstanceState);
SDS = new SalesDataSource(this);
SDS.open();
if (savedInstanceState == null) {
setContentView(R.layout.fragment_tabs_pager);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
mTabsAdapter.addTab(mTabHost.newTabSpec("current_sale")
.setIndicator("Current Sale"), Current_Sale.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("running_total")
.setIndicator("Running Total"), RunningTotal.class, null);
mTabsAdapter.addTab(
mTabHost.newTabSpec("stats").setIndicator("Stats"),
CountingFragment.class, null);
} else {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
I just don't know how to communicate to RunningTotal that it needs to update itself.
EDIT Added the source of all the data I ask from the database
public class SalesDataSource {
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private String[] allColumns = { DatabaseHelper.COLUMN_ID,
DatabaseHelper.COLUMN_PERSON, DatabaseHelper.COLUMN_COST,
DatabaseHelper.COLUMN_ITEM };
public SalesDataSource(Context context) {
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
/**
* Creates an entry in the Database. Both a person and a cost are required.
* Item is not required. If one is not needed, simply pass null.
*
* #param person
* Who this sale belongs to.
* #param cost
* The amount (in pennies) that the sale was.
* #param item
* An optional description of the sold item
* #return The newly created Item.
*/
public Item addItem(String person, int cost, String item) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_PERSON, person);
values.put(DatabaseHelper.COLUMN_COST, cost);
values.put(DatabaseHelper.COLUMN_ITEM, item);
long insertId = database.insert(DatabaseHelper.TABLE_SALES, null,
values);
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES, allColumns,
DatabaseHelper.COLUMN_ID + " = " + insertId, null, null, null,
null);
cursor.moveToFirst();
Item rv = cursorToItem(cursor);
cursor.close();
return rv;
}
public void addItems(List<Item> items) {
for (Item i : items) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_PERSON, i.getPerson());
values.put(DatabaseHelper.COLUMN_COST, i.getAmount());
values.put(DatabaseHelper.COLUMN_ITEM, i.getItem());
database.insert(DatabaseHelper.TABLE_SALES, null, values);
}
}
public ArrayList<Item> getAllItems() {
ArrayList<Item> items = new ArrayList<Item>();
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES, allColumns,
null, null, null, null, DatabaseHelper.COLUMN_PERSON);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Item item = cursorToItem(cursor);
items.add(item);
cursor.moveToNext();
}
cursor.close();
return items;
}
public String[] getPersonValues() {
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES,
new String[] { "SUM(" + DatabaseHelper.COLUMN_COST + ") AS " + DatabaseHelper.PERSON_SUM,
DatabaseHelper.COLUMN_PERSON }, null, null,
DatabaseHelper.COLUMN_PERSON, null, null);
String[] rv = new String[cursor.getCount()];
cursor.moveToFirst();
int pos = 0;
while (!cursor.isAfterLast()) {
String person = cursor.getString(1);
String money = Item.format(cursor.getInt(0));
rv[pos++] = person + ": " + money;
cursor.moveToNext();
}
cursor.close();
return rv;
}
public Item getMaxSale() {
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES,
new String[] { "MAX(" + DatabaseHelper.COLUMN_COST + ") AS " + DatabaseHelper.MAX_SALE,
DatabaseHelper.COLUMN_PERSON }, null, null, null, null,
null);
cursor.moveToFirst();
Item rv = cursorToItem(cursor);
cursor.close();
return rv;
}
public Item getMinSale() {
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES,
new String[] { "MIN(" + DatabaseHelper.COLUMN_COST + ") AS " + DatabaseHelper.MIN_SALE,
DatabaseHelper.COLUMN_PERSON }, null, null, null, null,
null);
cursor.moveToFirst();
Item rv = cursorToItem(cursor);
cursor.close();
return rv;
}
private Item cursorToItem(Cursor cursor) {
Item item = new Item();
item.setId(cursor.getLong(0));
item.setPerson(cursor.getString(1));
item.setAmount(cursor.getInt(2));
item.setItem(cursor.getString(3));
return item;
}
}
Why not use a listfragment and loadermanager to manage the cursor object so that the list is automatically updated whenever the underlying data changes?