Check on Text in sqlite - java

You do a favorite job, but when you click the Add to Favorites button, you do not have just one click and the text is added with each click
You can examine the text within the database, but after checking, the value returns 0 at a time and the text is added
public int get_check_List_Favorite(String nameFav) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rev = db.rawQuery("SELECT * FROM myFavoriate WHERE nameFav Like'"+
nameFav +"",null);
int count = rev.getCount();
return count;
}
code button
case R.id.btn_favorite_text:
int check = db_sqlite.get_check_List_Favorite(nameFav);
Log.i("note", String.valueOf(check));
if (check > 0){
Toast.makeText(general.this, "I've been added before",
Toast.LENGTH_SHORT).show();
}else {
db_sqlite.addFavoriate(wordClass.getmTextV1());
Toast.makeText(general.this, "done added to favorites",
Toast.LENGTH_SHORT).show();
}
break;

the get_check_List_Favorite method is a call you can pass the parameter to search item in the database ret method is
public int get_check_List_Favorite(String nameFav) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rev = db.rawQuery("SELECT * FROM myFavoriate WHERE Colomname Like '%"+nameFav+"%'",null);
int count = rev.getCount();
return count;
}

Try to change query
// modify below method in SQLite helper class
public String get_check_List_Favorite(String nameFav) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rev = db.rawQuery("select * from myFavoriate where nameFav=?",new String[]{nameFav});
if (rev.getCount() > 0 ) {
rev.moveToFirst();
return rev.getString(rev.getColumnIndex("nameFav"));
}
return null;
}
// call above method from activity that will return username
case R.id.btn_favorite_text:
String username = db_sqlite.get_check_List_Favorite(wordClass.getmTextV1()));
if (username!=null){
Log.i("note", username);
Toast.makeText(general.this, "I've been added before",
.LENGTH_SHORT).show();
}else {
db_sqlite.addFavoriate(wordClass.getmTextV1());
Toast.makeText(general.this, "done added to favorites",
Toast.LENGTH_SHORT).show();
}
break;

Related

How to sort or reorder MergeCursor for ListViewAdapter

I am developing a simple social media for my case study. I was able to retrieve the post from the people the user follows. Here's the screenshot:
As you can see, the problem is that the posts were not sorted according to date/id. Instead, it is sorted according to the people the user follows. It is because I am only merging the cursors using mergecursor. Here's a part of my code:
ListView listviewFeed = (ListView) findViewById(R.id.listviewFeed);
Cursor cursorFeed = DataAdapters.getFeed(dbHelper, strUserID);
//This code is for retrieving user's own posts
Cursor cursorFollowing = DataAdapters.getFollowing(dbHelper,strUserID);
//This code is for retrieving the followed users.
if(cursorFollowing.getCount()>0) {
for (int intCtr = 0; intCtr < cursorFollowing.getCount(); intCtr++) {
int intUseridI = cursorFollowing.getColumnIndex(Tables.FollowTable.COLUMN_USERID);
String strUseridI = cursorFollowing.getString(intUseridI);
Cursor cursorFollowingFeed = DataAdapters.getFeed(dbHelper, strUseridI);
\\This code is for retrieving the posts of the people the user follows.
if(intCtr>0)
{
mergeCursor = new MergeCursor(new Cursor[]{mergeCursor, cursorFollowingFeed});
}else {
mergeCursor = new MergeCursor(new Cursor[]{cursorFeed, cursorFollowingFeed});
}
//This code is for merging the cursors.
if (intCtr + 1 == cursorFollowing.getCount()) {
cursorFollowing.close();
} else {
cursorFollowing.moveToNext();
}
}
ListViewAdapterMeasurement adapterMeasurement = new ListViewAdapterMeasurement(this, mergeCursor);
listviewFeed.setAdapter(adapterMeasurement);
}else
{
ListViewAdapterMeasurement adapterMeasurement = new ListViewAdapterMeasurement(this, cursorFeed);
listviewFeed.setAdapter(adapterMeasurement);
}
It is all working well. I just want to order the posts by Date or by ID.
Is there any way to sort MergeCursor?
I guess there is no way to sort the MergeCursor so I tried to think of other ways.
I changed my query like this:
public static Cursor getFeed (DBHelper dbHelper, String strUserID)
{
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursorFollowing = getFollowing(dbHelper,strUserID);
String strQuery = "SELECT * FROM feed_tbl WHERE "+ Tables.FeedTable.COLUMN_USERID + "="+strUserID;
if(cursorFollowing.getCount()>0)
{
for(int intCtr=0;intCtr<cursorFollowing.getCount();intCtr++)
{
int intUseridI = cursorFollowing.getColumnIndex(Tables.FollowTable.COLUMN_USERID);
String strUseridI = cursorFollowing.getString(intUseridI);
String strConcatQuery = " OR "+ Tables.FeedTable.COLUMN_USERID + "="+strUseridI;
if (intCtr + 1 == cursorFollowing.getCount()) {
cursorFollowing.close();
} else {
cursorFollowing.moveToNext();
}
strQuery = strQuery +""+strConcatQuery;
Log.v(TAG,strQuery);
}
}
Cursor cursor = db.rawQuery(strQuery+" ORDER BY "+ Tables.FeedTable.COLUMN_ID + " DESC",null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
The result on the log tag is this:
V/FeedMe: SELECT * FROM feed_tbl WHERE feed_userid=1 OR feed_userid=2 OR feed_userid=4 OR feed_userid=5
Just to make things clear to those who have the same problem with me which is about MergeCursor sorting. THERE IS NO SUCH WAY TO SORT MERGECURSOR :)
Thankyou!

Cursor is only returning one value, not all values

I have encountered a problem in my Android application. I want to retrieve all values of a column, but I am only getting one of the values. I have tried everything, but I could still not find a solution. Here is my code in my database:
public Cursor returnAllColumns() {
Cursor cursor = mDb.query(FTS_VIRTUAL_TABLE,
new String[] {KEY_ROWID,
KEY_NAME,
KEY_CUSTOMER, PROTEIN, TOTAL_CARB}
, null, null, null, null, null);
if (cursor != null) {
cursor.moveToNext();
}
return cursor;
}
Here is my code in another class where it shows a toast with all the values.
mDbHelper = new DBAdapter(DatabaseFiller.this);
mDbHelper.open();
Cursor c = mDbHelper.returnAllColumns();
String protein = c.getString(c.getColumnIndexOrThrow("protein"));
Toast.makeText(getApplicationContext(), protein, Toast.LENGTH_SHORT).show();
All I am getting is Protein = 0. What I should be getting is 0, 0, 0, 0, 0, 0,.... I don't know what I am doing wrong here. In my ListView, I got it right. It worked perfectly there. Here is my ListView code:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
cursor = (Cursor) mListView.getItemAtPosition(position);
//mListView.setItemChecked(position, true);
// Get the state's capital from this row in the database.
String name = cursor.getString(cursor.getColumnIndexOrThrow("customer"));
String caloriescursor = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String totalfat = cursor.getString(cursor.getColumnIndexOrThrow("address"));
String satfatcursor = cursor.getString(cursor.getColumnIndexOrThrow("city"));
String state = cursor.getString(cursor.getColumnIndexOrThrow("state"));
String zipCode = cursor.getString(cursor.getColumnIndexOrThrow("zipCode"));
And that returns a Toast with a bunch of values. Any help regarding this problem would be appreciated.
In getAllColumns(), your query statement is correct. It does in fact fetch all columns. The if statement that follows simply points it to the first result. Then you are returning the cursor while it is pointed to the first result. You should take out the if statement because it doesn't do anything useful.
When trying to show the toast, you want something like this:
Cursor c = mDbHelper.returnAllColumns();
ArrayList<String> protein = new ArrayList<>();
while (c.moveToNext()) {
protein.add(c.getString(c.getColumnIndexOrThrow("protein")));
}
Toast.makeText(getApplicationContext(), TextUtils.join(", ", protein), Toast.LENGTH_SHORT).show();
You need to loop over the cursor if the cursor is returning more than one row, and build your output in the loop.
Keep calling c.moveToNext() until it returns false.
I had the same problem until I did this:
if (!cursor.moveToFirst()) {
Log.d(LOG_TAG, "=== cursor not moveToFirst() ===");
return null;
}
Log.d(LOG_TAG, "=== reading cursor of getAll() ===");
Log.d(LOG_TAG, String.valueOf(cursor));
List<Trip> trips = new ArrayList<>();
while (!cursor.isAfterLast()) {
trips.add(cursorToTrip(cursor));
cursor.moveToNext();
}
The cursor.moveToNext() will never check the first element. So I check in the course is not in the last one and then I add the object and move to the next one.
That's it! :)

Strange NullPointerException error in android when using custom suggestions provider

I am trying to make custom search suggestions in my app. I’ve started from documentation and Searchable dictionary example. However, this example isn’t so good for me so I’ve started with some tests to find out exactly how to make it, because there is not much tutorials in the Internet also.
Generally my app has right now 2 databases – one normal and second with less number of columns – FTS3. What I would like to achieve is to connect suggestions provider to this FTS3 table.
What I was trying to do was to now was, using simple function, return in suggestions whole DB (around 200 records) after typing any letter in search box. I know about limit 50 records, but I don’t think it is the problem.
This are fragments from Provider’s code. What I found out, that when you type in text, provider goes to option SEARCH_SUGGEST:
// UriMatcher stuff
private static final int SEARCH_WORDS = 0;
private static final int GET_WORD = 1;
private static final int SEARCH_SUGGEST = 2;
private static final int REFRESH_SHORTCUT = 3;
private static final UriMatcher mUriMatcher = buildUriMatcher();
/**
* Builds up a UriMatcher for search suggestion and shortcut refresh queries.
*/
private static UriMatcher buildUriMatcher() {
Log.d(TAG,"urimatcher");
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
// to get definitions...
matcher.addURI(AUTHORITY, "mydb", SEARCH_WORDS);
matcher.addURI(AUTHORITY, "mydb/#", GET_WORD);
// to get suggestions...
matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
return matcher;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch (mUriMatcher.match(uri)) {
case SEARCH_SUGGEST:
Log.d(TAG,"SEARCH_SUGGEST");
if (selectionArgs == null) {
throw new IllegalArgumentException(
"selectionArgs must be provided for the Uri: " + uri);
}
return getSuggestions(selectionArgs[0]);
case SEARCH_WORDS:
Log.d(TAG,"SEARCH_WORDS");
if (selectionArgs == null) {
throw new IllegalArgumentException(
"selectionArgs must be provided for the Uri: " + uri);
}
return search(selectionArgs[0]);
case GET_WORD:
Log.d(TAG,"GET_WORD");
return null;
default:
Log.d(TAG,"default");
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
private Cursor getSuggestions(String query) {
String[] columns = { MyDBAdapter.KEY_TITLE,MyDBAdapter.KEY_ID};
Log.d(TAG,"query1: " + query);
try{
Cursor tmp = MyDB.getAllEntriesFTS(false, columns,
null, null, null, null, MyDBAdapter.KEY_TITLE, null, query);
Log.d(TAG,"cursor: " + Integer.toString(tmp.getCount()));
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
return tmp;
}
In getSuggestions I put code that should generally work, but it doesn’t. Doesn’t work only when used here. When I used it in other activity to get cursor for listview everything was fine. Here it returns my NullPointerException.
So getting deeper I put also some Log tags in getAllEntriesFTS method and this method looks like this:
public Cursor getAllEntriesFTS(boolean distinct, String[] result_columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit, String query) {
Log.d(TAG,"query db: " + query);
String[] columns = { MyDBAdapter.KEY_TITLE, MyDBAdapter.KEY_ID};
Log.d(TAG,"columns: " + Integer.toString(result_columns.length));
Cursor allRows = null;
try{
allRows = db.query(distinct, DATABASE_TABLE_FTS, columns,
null, null, null, null, MyDBAdapter.KEY_TITLE, null);
Log.d(TAG,"OK");
}
catch(Exception e)
{
Log.d(TAG, e.toString());//it always goes there with NullPointerExceptionwhen used in provider
}
Log.d(TAG,Integer.toString(allRows.getCount()));
return allRows;
}
So, generalny speaking it should return cursor to whole DB, but instead it throws In place where it shouldn’t NullPointerException.
Can someone please tell me what am I doing wrong and how it should be done?
Thank's to JB Nizet I was able to find my mistake. I was thinking I've studied Google's example good, but I was wrong.
The problem was lack of database open before cursor call. It should look like this:
private Cursor getSuggestions(String query) {
String[] columns = { MyDBAdapter.KEY_TITLE,MyDBAdapter.KEY_ID};
Log.d(TAG,"query1: " + query);
try{
MyDB.open();
Cursor tmp = MyDB.getAllEntriesFTS(false, columns,
null, null, null, null, MyDBAdapter.KEY_TITLE, null, query);
MyDB.close();
Log.d(TAG,"cursor: " + Integer.toString(tmp.getCount()));
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
return tmp;
}
Thank you all for showing me it.

Android : SQLite check if data exist and update

I now sure what i'm doing wrong because java and SQLite for me new. So I need to make check when user is entering new data to DB if data with such "day" and "week_type" exists it need to be updated , else create new row.
public long creatEntry(int day2, int week_type2,
String desc2, String place2, String lessnum2) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues() ;
String update = "SELECT * FROM info WHERE day="+day2+" AND week_type="+week_type;
Cursor cr = ourDatabase.rawQuery(update, null);
if(cr!= null){
cv.put(day, day2);
cv.put(week_type, week_type2);
cv.put(desc, desc2);
cv.put(place, place2);
cv.put(lessnum, lessnum2);
return ourDatabase.update(DATABASE_TABLE,cv, day+ "=" +day2+ " AND "+week_type+ "=" +week_type2, null);
}
else{
cv.put(day, day2);
cv.put(week_type, week_type2);
cv.put(desc, desc2);
cv.put(place, place2);
cv.put(lessnum, lessnum2);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
}
Use replace. It'll try to insert first, and if it happens to conflict due to a key constraint, it'll delete and insert those values. In your case, these two columns must be unique. Check it out:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#replace(java.lang.String, java.lang.String, android.content.ContentValues)

display data in TextView

public List<UserDataHelper> getData() {
List<UserDataHelper> list = new ArrayList<UserDataHelper>();
String selectQuery = "SELECT * FROM " + TABLE;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
UserDataHelper quest = new UserDataHelper();
quest.setID(cursor.getInt(0));
quest.setName(cursor.getString(1));
quest.setSent(cursor.getInt(2));
quest.setRecieved(cursor.getInt(3));
quest.setTotal(cursor.getInt(4));
quest.setTimeSpent(cursor.getString(5));
list.add(quest);
} while (cursor.moveToNext());
}
return list;
}
This is for a listView but I want to fetch data individually and display it in textView. How can I achieve that? There are a lot of tutorials for listviews but not for textViews so can someone help me out please.
try this
for (UserDataHelper user:getData())
{
textView.append(user.getID()+" "+user.getName()
+" "+user.getRecieved()+" "+user.getSent()
+" "+user.getTimeSpent()+" "+user.getTotal()+"\n");
}
You could simply use the class object to set/get values, do following for string values:-
textView.setText(quest.getName());
and for the integer values make sure to use one
of the following:-
textView.setText(""+quest.getId());
or
textView.setText(String.valueOf(integer));

Categories