I want to get a value of single column returned in the form of ArrayList<> from SQLite for retrieving data my code is :
public List<ContentDataObject> findAll() {
List<ContentDataObject> contentDataObjects = new ArrayList<ContentDataObject>();
String selectQuery = "SELECT " +
DBHelper.MOBILE_CONTENT_FULLTEXT+
" FROM " + DBHelper.MOBILE_CONTENT_TABLE_NAME;
database = dbOpenHelper.getReadableDatabase();
try {
Cursor cursor = database.rawQuery(selectQuery, null);
Log.i(TAG, "Returned " + cursor.getCount() + " rows");
if(cursor != null){
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ContentDataObject contentDataObject = check(cursor);
contentDataObjects.add(contentDataObject);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
}
} catch (Exception e) {
// TODO: handle exception
}
return contentDataObjects;
}
my check(cursor) is :
public ContentDataObject check(Cursor cursor) {
ContentDataObject contentDataObject = new ContentDataObject();
contentDataObject.setId(cursor.getLong(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_ID)));
contentDataObject.setTitle(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_TITLE)));
contentDataObject.setFulltext(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_FULLTEXT)));
contentDataObject.setState(cursor.getInt(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_STATE)));
contentDataObject.setNewValue(cursor.getInt(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_NEW)));
contentDataObject.setHeader(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_HEADER)));
contentDataObject.setColor(cursor.getInt(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_COLOR)));
contentDataObject.setNext(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_NEXT)));
contentDataObject.setPrevious(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_PREVIOUS)));
return contentDataObject;
}
in MainActivity.java I'm using this code :
ContentDataObject contentDataObject;
TextView textView;
ContentsDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myView);
dataSource = new ContentsDataSource(this);
dataSource.open();
List<ContentDataObject> contentDataObjects = dataSource.findAll();
textView.setText(""+contentDataObjects.indexOf(contentDataObject.getFulltext()));
}
but, I'm unable to get data and set to textView.
I think you don't use List<E> if you only want to get one value from SQLite so you should try this one !
change findAll() in this way :
public String findAll() {
^^^^^^
String myQuery = "SELECT " +
DBHelper.MOBILE_CONTENT_FULLTEXT+
" FROM " + DBHelper.MOBILE_CONTENT_TABLE_NAME+
" WHERE _id = 2";
Cursor cursor = database.rawQuery(myQuery, null);
String fullText = null;
^^^^^^^^^^^^^^^
if(cursor.getCount() <= 0) {
Log.w(TAG, "There is no data to display");
}
else {
fullText = "";
if(cursor.moveToFirst()) {
do {
fullText += cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_FULLTEXT)) + "\n";
} while(cursor.moveToNext());
}// end if
}
return fullText;
^^^^^^^^^^^^^^^^
}
And in onCreate() use this :
ContentsDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myView);
dataSource = new ContentsDataSource(this);
dataSource.open();
parseAndIsertData();
textView.setText(dataSource.getFullText());
^^^^^^^^^^^^^^^^^^^^^^^^^
}
I hope this Will work for you!
your contentDataObject is never initialized so your calling actually.
textView.setText(""+contentDataObjects.indexOf( NULL ));
Related
After the record iteration, the list key value is mismatching/wrongly shown ! what could be the reason.
Correct data in the database like this is saved (which is correct)
Problem: You can see in this screenshot link, record is a mismatch with columns, e.g the key dayName has wrong value showing , key MenuIcon value is shown on dayName key
the sql lite DAO
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
Full code of DAO for insertion,create table, list object . Please let me know any code you want to see, i will post
public class ExercisesDAO {
public static final String TAG = "ExercisesDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {DBHelper.COLUMN_EX_DETAILS_ID,
DBHelper.COLUMN_ROUTINE_ID,
DBHelper.COLUMN_DAY_ID,
DBHelper.COLUMN_EXERCISE_ID,
DBHelper.COLUMN_REPS,
DBHelper.COLUMN_SETS,
DBHelper.COLUMN_TIME_PERSET,
DBHelper.COLUMN_CALORIE_BURN,
DBHelper.COLUMN_RESTTIME_PERSET,
DBHelper.COLUMN_RESTTIME_POST_SET,
DBHelper.COLUMN_ORDER_ID,
DBHelper.COLUMN_EXERCISE_NAME,
DBHelper.COLUMN_TIPS,
DBHelper.COLUMN_YOUTUBE_URL,
DBHelper.COLUMN_WARNINGS,
DBHelper.COLUMN_DISPLAY_ID,
DBHelper.COLUMN_VISIBILITY,
DBHelper.COLUMN_FOR_DATE,
DBHelper.COLUMN_GIF,
DBHelper.COLUMN_DAYNAME
};
public ExercisesDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public ExerciseDetails createExerciseDetail(String routineId,String dayId,
String exerciseId, String reps,String sets, String timePerset,
String calorieBurn, String resttimePerset, String resttimeAfterex,String order,
String menuName, String tips, String youtubeUrl, String warnings, String displayId,
String visibility, String forDate, String menuIcon, String dayName) {
ExerciseDetails newCompany = null;
try {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_ROUTINE_ID, routineId);
values.put(DBHelper.COLUMN_DAY_ID, dayId);
values.put(DBHelper.COLUMN_EXERCISE_ID, exerciseId);
values.put(DBHelper.COLUMN_REPS, reps);
values.put(DBHelper.COLUMN_SETS, sets);
values.put(DBHelper.COLUMN_TIME_PERSET, timePerset);
values.put(DBHelper.COLUMN_CALORIE_BURN, calorieBurn);
values.put(DBHelper.COLUMN_RESTTIME_PERSET, resttimePerset);
values.put(DBHelper.COLUMN_RESTTIME_POST_SET, resttimeAfterex);
values.put(DBHelper.COLUMN_ORDER_ID, order);
values.put(DBHelper.COLUMN_EXERCISE_NAME, menuName);
values.put(DBHelper.COLUMN_TIPS, tips);
values.put(DBHelper.COLUMN_YOUTUBE_URL, youtubeUrl);
values.put(DBHelper.COLUMN_WARNINGS, warnings);
values.put(DBHelper.COLUMN_DISPLAY_ID, displayId);
values.put(DBHelper.COLUMN_VISIBILITY, visibility);
values.put(DBHelper.COLUMN_FOR_DATE, forDate);
values.put(DBHelper.COLUMN_GIF, menuIcon);
values.put(DBHelper.COLUMN_DAYNAME, dayName);
long insertId = mDatabase
.insert(DBHelper.TABLE_EXERCISE_DETAILS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
DBHelper.COLUMN_EX_DETAILS_ID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
newCompany = cursorToExerciseDetails(cursor);
cursor.close();
} catch (Exception e) {
Log.e("exception", "exception in CreateFollowing class - " + e);
}
return newCompany;
}
public void executeSqlOnExerciseDetail(String sql) {
mDatabase.execSQL(sql);
}
public Long getTotalCountExerciseDetail() {
return DatabaseUtils.queryNumEntries(mDatabase, DBHelper.TABLE_EXERCISE_DETAILS);
}
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
/*
* Check whether the exercise data present or not in the db before executing statement
*/
public boolean CheckIfRecordExists(String rid, String did) {
String Query = "Select * from " + DBHelper.TABLE_EXERCISE_DETAILS + " where " + DBHelper.COLUMN_ROUTINE_ID + " = " + rid + " AND " + DBHelper.COLUMN_DAY_ID + " = " + did;
Cursor cursor = mDatabase.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
protected ExerciseDetails cursorToExerciseDetails(Cursor cursor) {
try{
ExerciseDetails exerciseDetails = new ExerciseDetails();
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
exerciseDetails.setDayId(cursor.getString(2));
exerciseDetails.setExerciseId(cursor.getString(3));
exerciseDetails.setReps(cursor.getString(4));
exerciseDetails.setSets(cursor.getString(5));
exerciseDetails.setTimePerset(cursor.getString(6));
exerciseDetails.setCalorieBurn(cursor.getString(7));
exerciseDetails.setResttimePerset(cursor.getString(8));
exerciseDetails.setOrder(cursor.getString(9));
exerciseDetails.setMenuName(cursor.getString(10));
exerciseDetails.setTips(cursor.getString(11));
exerciseDetails.setYoutubeUrl(cursor.getString(12));
exerciseDetails.setWarnings(cursor.getString(13));
exerciseDetails.setDisplayId(cursor.getString(14));
exerciseDetails.setVisibility(cursor.getString(15));
exerciseDetails.setForDate(cursor.getString(16));
exerciseDetails.setMenuIcon(cursor.getString(17));
exerciseDetails.setDayName(cursor.getString(18));
return exerciseDetails;
} catch (Exception e){
System.out.println("error------------"+e);
return null;
}
}
}
FUll json value which i inserted Into sqllite
https://pastebin.com/DmAkPkXg
In cursorToExerciseDetails() instead of explicitly setting the index of a column:
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
....................................................
use getColumnIndex() with he name of the column to return the index:
exerciseDetails.setExDetailsId(cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_EX_DETAILS_ID)));
exerciseDetails.setRoutineId(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ROUTINE_ID))));
....................................................
I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}
By using assets folder, we are reading data i.e,address details based on search keyword:
Here is my code
private SQLiteDatabase db;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_search = (EditText) findViewById(R.id.et_search);
img = (ImageView) findViewById(R.id.img_search);
list = (ListView) findViewById(R.id.list_search);
db = openOrCreateDatabase("sample", Context.MODE_PRIVATE, null);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
search_keyword = et_search.getText().toString();
arr_data = new ArrayList<ListItems>();
if (isValid()) {
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
Log.d("daatt",SELECT_SQL);
try {
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
showRecords();
} catch (SQLiteException e) {
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void showRecords() {
String ugName = c.getString(c.getColumnIndex("Name"));
String ugaddress = c.getString(c.getColumnIndex("Address"));
String ugtype = c.getString(c.getColumnIndex("Type"));
ListItems items = new ListItems();
// Finish reading one raw, now we have to pass them to the POJO
items.setName(ugName);
items.setAddress(ugaddress);
items.setType(ugtype);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
arr_data.add(items);
}
ListDataAdapter adapter = new ListDataAdapter(arr_data);
list.setAdapter(adapter);
if (c != null && !c.isClosed()) {
int count = c.getCount();
c.close();
}
Log.d("ListData", "" + arr_data);
}
private boolean isValid() {
if (search_keyword.length() == 0) {
Toast.makeText(getApplicationContext(), "please enter valid key word", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
For 1st build we got successful data loaded using list adapter
But after clean project, & Rebuild project showing a no such table expection
Please guide us wr we r going wrong
Advance Thanks
As far as I can see from your print, the table you're referring to is called ListOfAddress, ain't it? your SQL is:
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
I might be wrong, but I would double check the query.
I'm getting many time repeating data from Sqlite / Android database. I want to get recode without repeating in Android cursor.
Here's my query:
public Cursor getQuizQuiestion(String cat, String level, String questionNo) {
String QUERY_SELECT_QUIESTION = "SELECT * FROM " +TABLE_QUIESTION +" WHERE "+COL_CAT+ " = '" +cat+"' AND "
+COL_LEVEL+ " = " +level+" ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(QUERY_SELECT_QUIESTION, null);
return cursor;
}
I Have Simple Example if I Used In My Project I think MayBe IT's Help You;
public ArrayList<ModelRandomList> getRandomData(String city){
ArrayList<ModelRandomList> modelRandomListArrayListLists = new ArrayList<ModelRandomList>();
String queryRandomData ="SELECT DISTINCT * FROM "+TABLE_NAME+" WHERE "+COL_CITY + "=?"+ "Order BY RANDOM()";
Cursor cursor = db.rawQuery(queryRandomData,new String[] { String.valueOf(city) });
if(cursor.getCount() != 0){
while (cursor.moveToNext()){
/*mName =cursor.getString(0);
mCity = cursor.getString(1);
Log.d(TAG,mName +" City "+mCity );*/
ModelRandomList modelRandomList = new ModelRandomList();
modelRandomList.setUserName(cursor.getString(0));
modelRandomList.setUserCity(cursor.getString(1));
modelRandomListArrayListLists.add(modelRandomList);
}
Random random = new Random();
Collections.shuffle(modelRandomListArrayListLists,random);
}
Log.d(TAG, "Get Random Totla No of Recode Found "+cursor.getCount());
return modelRandomListArrayListLists;
}
and in Your Activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private SqlLiteDataBaseHelper sqlLiteDataBaseHelper;
private Button btGetRandomData;
private ArrayList<ModelRandomList> modelRandomLists;
private Button btSingleRandomData;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelRandomLists = new ArrayList<ModelRandomList>();
sqlLiteDataBaseHelper = new SqlLiteDataBaseHelper(MainActivity.this);
try{
if(sqlLiteDataBaseHelper.checkDataBase()){
Log.e(TAG, "Data Base Already Exists");
}else {
sqlLiteDataBaseHelper.CopyDataBaseFromAsset();
}
sqlLiteDataBaseHelper.openDataBase();
try {
Log.e(TAG, "No Of Racode In DataBase " + sqlLiteDataBaseHelper.getDataCount());
}catch (Exception e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
init();
}
private void init() {
btGetRandomData = (Button)findViewById(R.id.btRandomData);
btSingleRandomData = (Button)findViewById(R.id.btSingleRandomData);
}
#Override
protected void onResume() {
super.onResume();
btGetRandomData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
modelRandomLists = sqlLiteDataBaseHelper.getRandomData("A");
for (ModelRandomList crt : modelRandomLists) {
Log.e(TAG, " " + crt.getUserName());
Log.e(TAG, " " + crt.getUserCity());
}
}
});
btSingleRandomData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
Log.d(TAG,modelRandomLists.get(position).getUserName());
position ++;
}catch (Exception e){
e.printStackTrace();
position =0;
}
}
});
}
}
You would have to keep a track of what questions have been seen before. What about this:
private List<Integer> seenQuestions = new ArrayList<>();
public Cursor getUseenQuizQuestion(String cat,String level,String questionNo) {
Cursor cursor = getQuizQuiestion(cat, level, questionNo);
while(cursor == null) { // This could be an infinite loop!!
cursor = getQuizQuiestion(cat, level, questionNo);
}
return cursor;
}
private Cursor getQuizQuiestion(String cat,String level,String questionNo){
String QUERY_SELECT_QUIESTION = "SELECT * FROM " +TABLE_QUIESTION +" WHERE "+COL_CAT+ " = '" +cat+"' AND "
+COL_LEVEL+ " = " +level+" ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(QUERY_SELECT_QUIESTION, null);
if(cursor.moveToFirst()) {
int resultId = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
if(seenQuestions.contains(resultId)) {
cursor.close();
return null;
}
seenQuestions.add(resultId);
}
return cursor;
}
^ the code sample above has many flaws and could loop infinitely.
But the point is you need to keep track of what has been returned and query again if you have seen it.
Alternatively, you could allow your DB query to return all data and then use a Random value to select one of the items.
There is no way to create unique results if you are querying over and over again.
Since you are not using the questionNo parameter and return a cursor anyway: why not just remove the limit 1 and add the distinct clause to your statement?
If you do it that way, you can use your cursor to iterate over the unique questions:
String QUERY_SELECT_QUIESTION = "SELECT DISTINCT * FROM " +TABLE_QUIESTION +" WHERE "+COL_CAT+ " = '" +cat+"' AND "
+COL_LEVEL+ " = " +level+" ORDER BY RANDOM()";
Then you can iterate over the questions until you have none or whatever your conditions are:
Cursor cursor = db.rawQuery(QUERY_SELECT_QUIESTION, null);
try {
while (cursor.moveToNext()) {
//display question or copy them to a member or whatever
}
} finally {
cursor.close();
}
Hї!
I have wrote test for my application. I need add item to database throught UI interface (using robotium) and then I want to check if item exists in database using SQLiteDatabase.
Item is added succesfully (I see new record in database after test finished), but isExistsInDb in my test class returns false. I do not understand why. Could you please help me.
Thanks!
Activity class:
public abstract class EditActivity {
// Some code .....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initButtonCancelOk();
}
protected void validateAndSave() {
try {
formValidator.validateAll();
if (formValidator.isFormValid()) {
DatabaseOpenHelper doh = new DatabaseOpenHelper(this);
Dao d = new Dao(doh);
d.add(fetchObjectFromUi());
finish(); // destroy this activity
} else {
ToastImage.makeImageText(context,
R.drawable.warning,
formValidator.getMessages(),
Toast.LENGTH_SHORT
).show();
}
} catch (Exception e) {
Toast.makeText(context, " Error during validate form ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
private void initButtonCancelOk() {
btnOk = (Button) findViewById(R.id.btn_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateAndSave();
}
});
}
}
Test class:
public class AddItemSmokeTest extends extends ActivityInstrumentationTestCase2<EditActivity> {
protected Activity activity;
protected Solo solo;
public AddItemSmokeTest() {
super("com.myapp", EditActivity.class);
Intent i = createIntent(2);
setActivityIntent(i);
activity = getActivity();
solo = new Solo(getInstrumentation(), activity);
solo.sleep(1000); // interval between tests
}
protected Intent createIntent(long transType) {
Intent i = new Intent();
i.putExtra(INTENT_VALUE_MODE_NAME, MODE_INSERT_TRANSACTION);
i.putExtra(INTENT_VALUE_TYPE_ID_NAME, transType);
return i;
}
#Override
protected void tearDown() throws Exception {
}
protected void setIncomExpenseData(AbsTransIncomeExpenseTestData testData) {
solo.pressSpinnerItem(CATEGORY_SPN_INDEX, testData.getCategorySpinnerPos());
solo.pressSpinnerItem(ACCOUNT_SPN_INDEX, testData.getAccountSpinnerPos());
solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_sum), testData.getSum());
solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_comment), testData.getComment());
}
#Smoke
public void testAddIncomeTransaction() throws Exception {
initForType(TransactionType.INCOME);
AbsTransIncomeExpenseTestData testData = new IncomeTestData();
setIncomExpenseData(testData);
solo.clickOnButton(OK);
//solo.getActivityMonitor();
assertTrue(
"Item" + testData.getComment() + " was not added ",
isExistsInDb(activity, Transactions.TABLE_NAME, Transactions.DESCRIPTION, testData.getComment())
);
}
protected static boolean isExistsInDb(Context context, String tableName, String commentFieldName, String comment) {
DatabaseOpenHelper doh = new DatabaseOpenHelper(context);
SQLiteDatabase db = doh.getDatabaseReadable();
Cursor cursor = null;
try {
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = \"" + comment + "\"";
cursor = db.rawQuery(query, null);
cursor.moveToFirst();
if (cursor.getInt(0) > 1) {
return true;
}
return false;
} finally {
if (cursor != null) {
cursor.close();
}
db.close();
doh.close();
}
}
}
Update:
If I run test the second time it is passed because in database exists item added by previous test.
I recommend to use use parametrized statement, your approach is danger and not much clear.
Also much better is use getCount() method.
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
int count = 0;
if (cursor.getCount() > 0) {
cursor.moveToFirst();
count = cursor.getInt(0);
}
if (count > 0) {
return true;
}
else {
return false;
}
in where clasue use 'string' instead of "string".....
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";