Edittext only adding first item to arraylist<string> - android

I'm at a lose with this one. Trying to take edittext from a list view and put them into an arraylist to use on another activity.
public class editpage extends ListActivity {
public static String editString;
private dbadapter mydbhelper;
public static ArrayList<String> editTextList = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_list);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
public void fillData() {
Cursor e = mydbhelper.getUserWord();
startManagingCursor(e);
String[] from = new String[] {dbadapter.KEY_USERWORD,};
int[] to = new int[] {R.id.textType,};
SimpleCursorAdapter editadapter =
new SimpleCursorAdapter(this, R.layout.edit_row, e, from, to);
ListView list = getListView();
View footer = getLayoutInflater().inflate(R.layout.footer_layout, list, false);
list.addFooterView(footer);
setListAdapter(editadapter);
}
public void onClick(View footer){
final MediaPlayer editClickSound = MediaPlayer.create(this, R.raw.button50);
final EditText editText = (EditText) findViewById(R.id.editText);
for (int i = 0; i < getCount(); i++){
editTextList.add(editText.getText().toString());
}
editClickSound.start();
startActivity(new Intent("wanted.pro.madlibs.OUTPUT"));
};
//can't get my getcount to work dynamically. I want it to be based off how many items are shown in next code showing my cursor but can't get to work atm unless I set statically to prevent errors and move to next activity
private int getCount() {
// TODO Auto-generated method stub
return 10;
}
Cursor to filter data pulled from database
public Cursor getUserWord()
{
return myDataBase.query(USER_WORD_TABLE, new String[] {
KEY_ID,
KEY_CATEGORY,
KEY_SOURCE, KEY_TITLE, KEY_USERWORD
},
KEY_CATEGORY+ "=" + categories.categoryClick + " AND " + KEY_SOURCE+ "="
+source.sourceClick + " AND " + KEY_TITLE+ "=" + title.titleClick,
null, null, null, KEY_ID);
Cursor to filter data from database to show in listview
public Cursor getUserWord()
{
return myDataBase.query(USER_WORD_TABLE, new String[] {
KEY_ID,
KEY_CATEGORY,
KEY_SOURCE, KEY_TITLE, KEY_USERWORD
},
KEY_CATEGORY+ "=" + categories.categoryClick + " AND " + KEY_SOURCE+ "="
+source.sourceClick + " AND " + KEY_TITLE+ "=" + title.titleClick,
null, null, null, KEY_ID);
}
My next activity will be showing the edittext merged with a string from my database. I take this string and replace edit01, edit02 etc with the users input from edittext fields on previous activity
public class output extends ListActivity {
private dbadapter mydbhelper;
#Override
public void onCreate(Bundle savedInstantState){
super.onCreate(savedInstantState);
setContentView(R.layout.outview);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
private final Runnable mTask = new Runnable(){
public void run(){
TextView textView = (TextView)findViewById(R.id.outputText);
String story = textView.getText().toString();
CharSequence modifitedText1 = Replacer.replace(story,
"edit01", Html.fromHtml("<font color=\"red\">"+ editpage.editTextList.get(0) +"</font>"));
CharSequence modifitedText2 = Replacer.replace(modifitedText1,
"edit02", Html.fromHtml("<font color=\"red\">"+ editpage.editTextList.get(1) +"</font>"));
textView.setText(modifitedText2);
}
};
private final Handler mHandler = new Handler();
private void fillData() {
Cursor st = mydbhelper.getStory();
startManagingCursor(st);
String[] from = new String[] {dbadapter.KEY_TITLESTORY};
int[] to = new int[] {R.id.outputText};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, R.layout.out_row, st, from, to);
setListAdapter(adapter);
}
#Override
protected void onResume() {
mydbhelper.open();
mHandler.postDelayed(mTask, 10);
super.onResume();
}
#Override
protected void onPause() {
mydbhelper.close();
super.onPause();
}
}
The furthest I can get this to work is with one item. I will be having anywhere from 4-10 edittexts on the first activity I show here. But no matter what I've tried it will only display the text entered into the first edittext field. In it's current state it will fill edit01 & edit02 in the string from database with what was put in first edittext in previous activity.

Well was finally able to get this to work without changing to much. I had to fight with it and try a bunch of things. Figured I would share the answer in case someone tries something like this. It came down to changing (R.id.editText) to have its own unique id.
private void editId(){
if(findViewById(R.id.editText) == null){
}else{
for(int editI= 0; editI<getCount(); editI++){
EditText editText = (EditText) findViewById(R.id.editText);
editText.setId(editI);
m_edit.add(editI, editText);
}}
}
and calling editId() in my onclick for my footer button
I had to change my runnable to work dynamically but that is another issue.

Related

How to search the data in listview by more than one thing?

Right now, my app filters the data in a listview when somethings is entered into the editText, but it can only filter by one thing at a time. I want it to be able to filter by more than value. For example, if someone types in "chicken" it should filter the recipes by the word 'chicken'. But, if someone then types in "dinner", I want it to filter the recipes by both "chicken" and "dinner." Eventually, I want to make it so those values appear as checkboxes above the listview so they can be easily removed.
I can't figure out how to do this. I played around with loops at first but didn't really get anywhere.
public class SearchActivity extends NavDrawerActivity {
private DBHandler dbHelper;
private SimpleCursorAdapter dataAdapter;
ArrayList<String> filters = new ArrayList<String>();
//String[] filters;
FrameLayout frameLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main_activity3);
frameLayout = (FrameLayout) findViewById(R.id.activity_frame);
// inflate the custom activity layout
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View activityView = layoutInflater.inflate(R.layout.activity_main_activity3, null, false);
// add the custom layout of this activity to frame layout.
frameLayout.addView(activityView);
dbHelper = new DBHandler(this, null, null, 1);
//dbHelper.open();
//Clean all data
dbHelper.deleteAllRecipes();
//Add some data
dbHelper.insertSomeRecipes();
//Generate ListView from SQLite Database
displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void displayListView() {
final Cursor cursor = dbHelper.fetchAllRecipes();
// The desired columns to be bound
String[] columns = new String[]{
//DBHandler.COLUMN_CODE,
DBHandler.COLUMN_NAME,
DBHandler.COLUMN_TYPE,
DBHandler.COLUMN_INGRED
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
//R.id.code,
R.id.name,
R.id.type,
R.id.ingredient,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.recipeinfo,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String recipeName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
Intent n = new Intent(getApplicationContext(), RecipeActivity.class);
//n.putExtra("position", position);
n.putExtra("recipeName", recipeName);
startActivity(n);
}
});
//final GridView gridView = (GridView)findViewById(R.id.gridView);
final TextView tv = (TextView)findViewById(R.id.textView14);
final EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.setImeActionLabel("Filter",1);
myFilter.setPrivateImeOptions("actionUnspecified");
myFilter.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == 1 || id == EditorInfo.IME_NULL) {
String filter = textView.getText().toString();
dataAdapter.getFilter().filter(filter);
filters.add(filter);
tv.append(filter);
myFilter.setText("");
}
return false;
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchRecipesByName(constraint.toString());
}
});
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Then you start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, RecipeActivity.class);
intent.putExtra("position", position);
// Or / And
intent.putExtra("id", id);
startActivity(intent);
}
}
fetchRecipesByName in DBHandler
public Cursor fetchRecipesByName(String inputText) throws SQLException {
SQLiteDatabase mDb = this.getWritableDatabase();
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {COLUMN_ROWID,
COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED, COLUMN_IMGPATH},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {COLUMN_ROWID,
COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED, COLUMN_IMGPATH},
COLUMN_NAME + " like '%" + inputText + "%'" + " or " +
COLUMN_TYPE + " like '%" + inputText + "%'" + " or " +
COLUMN_INGRED + " like '%" + inputText + "%'",
null, null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
What is the implementation of dbHelper.fetchReccipesByName()? I think, as of now, it queries the table only by one thing. You should change its logic and implement your complex need in this method (obviously, it should be an SQL query execution).
As a best practice, you should call listView.setFilterText() instead of dataAdapter.getFilter().filter(), because this method is supposed to run in secondary thread for the reason that DB queries are time consuming. If you call listView.setFilterText(), the framework will take care of threading and calls filter.filter() in secondary thread.
And finally, since you are searching by more than one keyword, but setFilterText() accepts only one CharSequence param, you should encode somehow many keywords into single String (say comma separated). And while querying you could decode the constraint to get the keywords.

display data from sqlite according to value

i need your help, i did display data in a list view but the problem is that i
want the data to be according to a specific value, that means if the id = 1, only the rows
concerned will be displayed, if you have any suggestions i would be very thankful :
here the code of :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
String[] databaseColumnNames = new String[] { DBAdapter.col_region, };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
And my DBAdapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id, col_region,
}, null, null, null,
null, null);
}
list.setAdapter(myCursordapter);
} }
As you may check in query documentation, function accepts a selection and selectionArgs parameters, corresponding to SQL WHERE clause.
So, to make a query limited to a specific id, just use:
db.query(MENAGE, new String[] { _id, col_region}, "id = ?", new String[] {_id}, null, null, null);

display data from sqlite

i have a problem in showing data coming from database sqlite, i looked for a solution
here i did found plenty but i couldn't make it work, the error i get is : Error occured:
java.lang.IllegalArgumentException: column '_id' does not exist !!
my code is :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
private ArrayList<String> arr;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
Button suivant = (Button)findViewById(R.id.com_quest);
suivant.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent l = new Intent(MainActivity.this,ActivityUn.class);
startActivity(l);
}
});
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
Log.i("MyApp", "Total users: " + cursor.getCount());
Toast.makeText(getApplicationContext(),
"Number of rows: " + cursor.getCount(), Toast.LENGTH_LONG)
.show();
String[] databaseColumnNames = new String[] { DBAdapter._id };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(myCursordapter);
} }
and in dbadapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id
}, null, null, null,
null, null);
}
All CursorAdapters require that the Cursor includes a column called _id. Your Cursor contains just one column called Num_du_Questionnaire.

Android Search function using a string from an EditText

The Search function in my Android app works. I'm using onSearchRequested(); to invoke the Search function. Now what I'd like to do is not use onSearchRequested(); and pass a string from an EditText to the search method and display the results in a List. Here's my search as it's working when onSearchRequested is called:
SearchPage Activity:
DBHelper = new DBAdapter(this);
DBHelper.open();
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
//--- END onSearchRequested
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_YEAR,
DBAdapter.KEY_MAKE, DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rYearTV, R.id.rMakeTV,
R.id.rModelTV };
final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
DBAdapter Activity:
//--- GET RECORDS FOR SEARCH
public Cursor searchDB(String query) {
String[] parts = query.split(" ");
String queryString = "";
for(int i = 0; i < parts.length; i++) {
queryString += KEY_YEAR + " LIKE '%" + parts[i] + "%' OR ";
queryString += KEY_MAKE + " LIKE '%" + parts[i] + "%' OR ";
queryString += KEY_MODEL + " LIKE '%" + parts[i] + "%'";
if(i != (parts.length - 1)) {
queryString += " OR ";
}
}
return db.query(true, DB_TABLE,
new String[] { KEY_ROWID, KEY_SDATE, KEY_YEAR, KEY_MAKE, KEY_MODEL },
queryString, null, null, null, null, null);
}
//--- END Get Records for Search
I'd like to pass a String into the search function String searchData = searchEditText.getText().toString(); and have the search function go to work on the passed string by pressing a "Search" button. Can someone help get me started?
You should have EditText like that in your layout:
<EditText
android:id="#+id/search_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="search"
android:imeOptions="actionSearch"
android:inputType="text" />
And in your Activity's onCreate:
EditText searchQuery = (EditText) findViewById(R.id.search_query);
searchQuery.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
String searchData = searchQuery.getText().toString();
showResults(searchData); //passing string to search in your database to your method
return true;
}
return false;
}
});
setOnEditorActionListener is used to perform search when user presses search button on keayboard. You can read more about imeActions here.
According to your code call showResults(searchData); to make search and display results in a list.
EDIT:
According to your code call it in SearchPage Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView and other your features
DBHelper = new DBAdapter(this);
DBHelper.open();
EditText searchQuery = (EditText) findViewById(R.id.search_query);
Button yourButton = (Button) findViewById(R.id.yourButtonId);
yourButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String searchData = searchQuery.getText().toString();
showResults(searchQuery);
}
});
}
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_YEAR,
DBAdapter.KEY_MAKE, DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rYearTV, R.id.rMakeTV,
R.id.rModelTV };
final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
}

Android: I have to display content from the database in the listview, in which latest data comes on top

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

Categories

Resources