I'm trying to create something like favorite thing in my app
I have made activity with restaurant which can be set as favorite, I've made imagebutton for making restaurant favorite and it's working, cause I have second activity where list is getting info from database and everything is ok. Titles match, adresses match cities too, so database should match too.
I have problem with changing OnClickListener, I want to use info from database to check if String called "database_name" is matching with any string from database.
There is code for it :
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selection = {FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE};
favoriteButton = (ImageButton) findViewById(R.id.favoriteRestaurant);
Cursor cursor = db.query(FeedReaderContract.FeedEntry.TABLE_NAME, selection,
null, null, null, null, null);
if(cursor.getCount() != 0) {
cursor.moveToFirst();
do {
if(cursor.getString(0).toLowerCase() == database_name.toLowerCase()){
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
isFavorite = 1;
}
} while (cursor.moveToNext());
}
It's changing background of this favorite button to filled heart, at least it's supposed to do so. In default it's not filled.
Then I'm changing onClickListener, code for it looks like this :
if(isFavorite == 0) {
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isntFavorite();
}
});
} else {
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFavorite();
}
});
}
isFavorite look like this :
private void isFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoriteu));
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE + " LIKE ?";
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selectionArgs = new String[] { database_name };
db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isntFavorite();
}
});
}
And code for isntFavorite looks like this:
private void isntFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, restaurantName);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ADRESS, restaurantAdress);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CITY, restaurantCity);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE, database_name);
long newRowId;
newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,
null, values);
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFavorite();
}
});
}
The thing is that it's always changing onClickListener to isntFavorite and it's not changing image background to filled heart, even if there is matching data in database. I was trying to change matching title from database to title from activity, and I was sure that they're matching cause there was in list title with the same String as title from activity where I was trying to match them.
You don't need to change OnclickListener just create a boolean to save the state:
final boolean state = isFavorite == 0;
favoriteButton.setOnClickListener(new View.OnClickListener() {
boolean mState = state;
#Override
public void onClick(View v) {
if(mState)isntFavorite();
else isFavorite();
mState=!mState;
}
});
private void isFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoriteu));
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE + " LIKE ?";
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selectionArgs = new String[] { database_name };
db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
}
private void isntFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, restaurantName);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ADRESS, restaurantAdress);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CITY, restaurantCity);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE, database_name);
long newRowId;
newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,
null, values);
}
Related
i want to retrieve id from database where name = saqib into the EditText(textbox) in android, i have tried different ways but can't achieve my desired output instead of that the given output will be shown every time. output
onButtonClick:
final EditText i=(EditText)findViewById(R.id.id_etxt);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res= mydatabase.fet();
i.setText(res.toString());
}
});
Database.java class
public Cursor fet(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select ID from record where Name=?",new String[] {"saqib"});
return res;
}
Cursor res = mydatabase.fet();
if (res.getCount() > 0) {
res.moveToFirst();
i.setText(res.getString(0));
} else {
throw new SQLiteException("e");
}
Currently you set the whole Cursor as String in EditText, which is not right way to set ID.
You have to extract the ID from Cursor like below to use it in EditText:
public void onClick(View v) {
Cursor res = mydatabase.fet();
if(res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(res.getColumnIndex("ID")));
i.setText(id);
}
}
I have a method in my activity class which should print a random role to the player (stores in an SQLite database). I am getting a success message but it is not being carried out. I only have 1 record in my SQLite database so far and will be adding a while loop after to populate each row.
This is my my activity class:
public class StartGame extends AppCompatActivity implements View.OnClickListener {
DatabaseHelper myDb;
Button btnRoles;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startgame);
myDb = new DatabaseHelper(this);
btnRoles = (Button) findViewById(R.id.btnAssignRoles);
assignRoles();
}
public String RandomNumber() {
List < String > roles = Arrays.asList("Mafia", "Mafia", "Angel", "Detective", "Civilian", "Civilian", "Civilian");
Collections.shuffle(roles);
return roles.get(0);
}
public void assignRoles() {
btnRoles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
boolean isUpdated = myDb.updateRole(RandomNumber().toString());
if (isUpdated == true)
Toast.makeText(StartGame.this, "Roles assigned, keep them secret!", Toast.LENGTH_LONG).show();
else
Toast.makeText(StartGame.this, "UNSUCCESSFUL!", Toast.LENGTH_LONG).show();
}
}
}
);
}
And this is the method in my Database Helper class:
public boolean updateRole(String role){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_ROLE, role);
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
return true;
}
What am I doing wrong?
You got an error in this line:
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
You are updating all the rows in the table where Role = {role} to have the column Role the value {role}. So obviously this will have no effect.
You need to have some thing like id and use that in your where statement, some thing like this:
db.update(TABLE_NAME, contentValues, "id =?", new String[] {id});
I'm absolute beginner.
I have a listview filled with sqlite table, I have two questions:
1- How can I sort this listview by last modified item ?
2- How can I make a button on my first page to open last modified item without going to listview !?
Here are my codes:
Its listview -
public class MainActivity extends ListActivity {
// Declare Variables
public static final String ROW_ID = "row_id";
private static final String TITLE = "title";
private ListView noteListView;
private CursorAdapter noteAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stopService(new Intent(MainActivity.this, MyService.class));
// Locate ListView
noteListView = getListView();
// Prepare ListView Item Click Listener
noteListView.setOnItemClickListener(viewNoteListener);
// Map all the titles into the ViewTitleNotes TextView
String[] from = new String[]{ TITLE };
int[] to = new int[]{ R.id.ViewTitleNotes };
// Create a SimpleCursorAdapter
noteAdapter = new SimpleCursorAdapter(MainActivity.this,
R.layout.list_zekr, null, from, to);
// Set the Adapter into SimpleCursorAdapter
setListAdapter(noteAdapter);
}
// Capture ListView item click
OnItemClickListener viewNoteListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// Open ViewNote activity
Intent viewnote = new Intent(MainActivity.this, CounterActivity.class);
viewnote.putExtra(ROW_ID, arg3);
startActivity(viewnote);
}
};
#Override
protected void onResume() {
super.onResume();
// Execute GetNotes Asynctask on return to MainActivity
new GetNotes().execute((Object[]) null);
}
#Override
protected void onStop() {
Cursor cursor = noteAdapter.getCursor();
// Deactivates the Cursor
if (cursor != null)
cursor.deactivate();
noteAdapter.changeCursor(null);
super.onStop();
}
// Create an options menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Menu Title
menu.add("ذکر جدید")
.setOnMenuItemClickListener(this.AddNewNoteClickListener)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return super.onCreateOptionsMenu(menu);
}
// Capture menu item click
OnMenuItemClickListener AddNewNoteClickListener = new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Open AddEditNotes activity
Intent addnote = new Intent(MainActivity.this, AddEditNotes.class);
startActivity(addnote);
return false;
}
};
// GetNotes AsyncTask
public class GetNotes extends AsyncTask<Object, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(MainActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
// Open the database
dbConnector.open();
return dbConnector.ListAllNotes();
}
#Override
protected void onPostExecute(Cursor result) {
noteAdapter.changeCursor(result);
// Close Database
dbConnector.close();
}
}
}
its my DatabaseConnector :
public class DatabaseConnector {
// Declare Variables
private static final String DB_NAME = "database";
private static final String TABLE_NAME = "tablenotes";
private static final String TITLE = "title";
private static final String ID = "_id";
private static final String NOTE = "note";
private static final String COUNTS = "counts";
private static final String LIMITS = "limits";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase database;
private DatabaseHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseHelper(context, DB_NAME, null, DATABASE_VERSION);
}
// Open Database function
public void open() throws SQLException {
// Allow database to be in writable mode
database = dbOpenHelper.getWritableDatabase();
}
// Close Database function
public void close() {
if (database != null)
database.close();
}
// Create Database function
public void InsertNote(String title, String note, String counts, String limits) {
ContentValues newCon = new ContentValues();
newCon.put(TITLE, title);
newCon.put(NOTE, note);
newCon.put(COUNTS, counts);
newCon.put(LIMITS, limits);
open();
database.insert(TABLE_NAME, null, newCon);
close();
}
// Update Database function
public void UpdateNote(long id, String title, String note, String counts, String limits) {
ContentValues editCon = new ContentValues();
editCon.put(TITLE, title);
editCon.put(NOTE, note);
editCon.put(COUNTS, counts);
editCon.put(LIMITS, limits);
open();
database.update(TABLE_NAME, editCon, ID + "=" + id, null);
close();
}
// Delete Database function
public void DeleteNote(long id) {
open();
database.delete(TABLE_NAME, ID + "=" + id, null);
close();
}
// List all data function
public Cursor ListAllNotes() {
return database.query(TABLE_NAME, new String[]{ ID, TITLE }, null,
null, null, null, TITLE);
}
// Capture single data by ID
public Cursor GetOneNote(long id) {
return database.query(TABLE_NAME, null, ID + "=" + id, null, null,
null, null);
}
}
thanks in advance.
UPDATE !
Ok, I Created a Column in my table with name of "time"
and I can insert the time as INTEGER to it like this: 20160516100740
So now every Row of table has a time like that, NOW WHAT CAN I DO ?
Update !
Ok, I wrote this inside my list activity (MainActivity.java)
but its not working : (
public Cursor listAllSortedNotes() {
String selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY time DESC";
return database.rawQuery(selectQuery, null);
You need to add a field in the database which should be a date string (Sample: yyyy-MM-dd HH:mm:ss). And when you update the data, update it with current date and time. Then you can use select query to get the recent update data by using
SELECT *
FROM Table
ORDER BY datetime (dateColumn) DESC
In your case you can do something like this.
public Cursor listAllSortedNotes() {
String selectQuery = "SELECT * FROM "+ TABLE_NAME + " ORDER BY datetime(dateColumn) DESC";
return database.rawQuery(selectQuery, null);
}
I’m struggling to write a method that deletes a row from the SQLiteDatabase. I have a list of songs in a gridview where when a user clicks one of the items from the list the app will take them to my SongDetailFragment activity which contains more information about the song and a star button where if a song in in the database the star button is “switched on”, conversely if the item is NOT in the database the star button is “switched-off”
When a user click the star button I'm able to add a song successfully in the database and my star button is “switched-on”. Now I want to press the same button again and call deleteFromDB() to delete the song that was added to the database. So I have the following code in my onClick:
public void onClick(View v)
{
if (mIsFavourite) {
deleteFromDB();
}
else {
insertData();
mIsFavourite = true;
}
The problem is deleteFromDB() method is not working correctly as I can see that the song is not deleting from the database. I’m not sure what is the correct syntax to fix it.
Here is my method:
private void deleteFromDB() {
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.SongEntry.CONTENT_URI,
SongContract.SongEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
//switch off button
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
Here is my delete method snippet from my ContentProvider class:
#Override
public int delete(Uri uri, String selection, String[] selectionArgs){
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int numDeleted;
switch(match){
case SONG:
numDeleted = db.delete(
SongContract.SongEntry.TABLE_NAME, selection, selectionArgs);
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
SongContract.SongEntry.TABLE_NAME + "'");
break;
case SONG_WITH_ID:
numDeleted = db.delete(SongContract.SongEntry.TABLE_NAME,
SongContract.SongEntry._ID + " = ?",
new String[]{String.valueOf(ContentUris.parseId(uri))});
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
SongContract.SongEntry.TABLE_NAME + "'");
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
return numDeleted;
}
Here is my SongDetailFragment:
public class SongDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private Song song;
private static final int CURSOR_LOADER_ID = 0;
ImageButton imgViewFavButton;
Boolean mIsFavourite = false;
// private final Context mContext;
public SongDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.song_fragment_detail, container, false);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra("song")) {
song = intent.getParcelableExtra("song");
//display title
((TextView) rootView.findViewById(R.id.detail_title_textview))
.setText(song.getTitle());
((TextView)rootView.findViewById(R.id.detail_description_textview))
.setText(song.getDescription());
((TextView)rootView.findViewById(R.id.song_releasedate_textview))
.setText(song.getReleaseDate());
double dRating = song.getVoteAverage();
String sRating = String.valueOf(dRating);
((TextView)rootView.findViewById(R.id.song_rating_textview))
.setText(sRating + "/10 ");
//show song poster
ImageView imageView = (ImageView) rootView.findViewById(R.id.song_detail_poster_imageview);
Picasso.with(getActivity()).load(song.getPoster()).into(imageView);
}
imgViewFavButton = (ImageButton) rootView.findViewById(R.id.imgFavBtn);
checkFavourites();
imgViewFavButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (mIsFavourite) {
deleteFromDB();
}
else {
insertData();
mIsFavourite = true;
}
}
});
return rootView;
}
// insert data into database
public void insertData(){
ContentValues songValues = new ContentValues();
songValues.put(SongContract.SongEntry.COLUMN_ID, song.getsong_id());
songValues.put(SongContract.SongEntry.COLUMN_IMAGE, song.getPoster());
songValues.put(SongContract.SongEntry.COLUMN_TITLE, song.getTitle());
songValues.put(SongContract.SongEntry.COLUMN_OVERVIEW, song.getDescription());
songValues.put(SongContract.SongEntry.COLUMN_RELEASEDATE, song.getReleaseDate());
songValues.put(SongContract.SongEntry.COLUMN_RATING, song.getVoteAverage().toString());
//Insert our ContentValues
getActivity().getContentResolver().insert(SongContract.SongEntry.CONTENT_URI,
songValues);
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
}
private void deleteFromDB() {
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.SongEntry.CONTENT_URI,
SongContract.SongEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
private void checkFavourites() {
Cursor c =
getActivity().getContentResolver().query(SongContract.SongEntry.CONTENT_URI,
null,
SongContract.SongEntry.COLUMN_ID + " = ?",
new String[]{song.getsong_id()},
null);
if (c != null) {
c.moveToFirst();
int index = c.getColumnIndex(SongContract.SongEntry.COLUMN_ID);
if (c.getCount() > 0 && c.getString(index).equals(song.getsong_id())) {
mIsFavourite = true;
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
}
else{
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
c.close();
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args){
return new CursorLoader(getActivity(),
SongContract.songEntry.CONTENT_URI,
null,
null,
null,
null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
}
// Set the cursor in our CursorAdapter once the Cursor is loaded
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
}
// reset CursorAdapter on Loader Reset
#Override
public void onLoaderReset(Loader<Cursor> loader){
}
}
Notice this line right here:
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.songEntry.CONTENT_URI,
SongContract.songEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
You set songValues to an empty ContentValues object, and later call getAsString() which will return null since it doesn't contain any key for song.getTitle().
Just change your array to have the song title, you don't need ContentValues here:
new String[]{song.getTitle()});
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