//How to iterate using cursor.moveToPosition(x) when Onclick of Random and NextTORandom Button is clicked?
//here is my code for Mydatabase.java. This file is used to fetch the single row from the database.
public Cursor getData(int _id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =db.rawQuery("Select * from '"+DB_TABLE+"' where _id = ?", new String[] { String.valueOf(_id)});
if (cursor != null)
{
cursor.moveToFirst();
}
return cursor;
// here is my code for MyActivity.java
public void onClick(View v) {
cur=db.getData(position);
int firstpos=1;
int lastpos=4;
switch(v.getId())
{
case R.id.NextToRandom :
{
if (cur != null && cur.getCount()> 0 && position < cur.getCount() && position != cur.getCount()){
cur.moveToPosition(position);
textView1.setText(""+cur.getString(1));// Display Columns
position++;
cur.moveToNext();
}
if(cur.moveToPosition(lastpos))
{
cur.moveToPosition(firstpos);
textView1.setText(""+cur.getString(1));
}
/*else
{
cur.moveToPosition(position);
textView1.setText(""+cur.getString(1));
position++;
}*/
//display details code
}
break;
case R.id.random:
{
Random r = new Random();
int rnum = r.nextInt(max - min + 1) + min;
cur=db.getData(rnum);
setNewData(rnum);
}
}
}
private void setNewData (int xyz) {
}
//I want to loop through all the records by clicking Random_back_button,Random_button and Random_Next_button. How to implement this?
You can iterate over a cursor like so:
Cursor cursor = ...; // get cursor from somewhere
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext) {
// your code here
}
Cursors do provide random access, so if you need to access a particular row, call cursor.moveToPosition(int).
Official Code here ↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// ------------------------------
// android.database.DatabaseUtils
// ------------------------------
public static void dumpCursor(Cursor cursor, StringBuilder sb) {
sb.append(">>>>> Dumping cursor " + cursor + "\n");
if (cursor != null) {
int startPos = cursor.getPosition();
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
dumpCurrentRow(cursor, sb);
}
cursor.moveToPosition(startPos);
}
sb.append("<<<<<\n");
}
Related
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");
}
What am I missing in this code? It shows me only the first record from the database and does not move to the next record.
Next button:
if (v.getId() == R.id.btnNext) {
try {
pos++;
database.Open();
Houes h = new Houes();
database.Shows(h, pos);
txNo.setText("" + h.getHouse_id());
txAdd.setText("" + h.getHouse_address());
txOn.setText("" + h.getHouse_owner());
txVal.setText("" + h.getHouse_value());
txDis.setText("" + h.getHouse_discount());
database.Close();
} catch (Exception e) {
}
database class:
protected void Shows(Houes house , int p ) {
// String[] columns = {house_id, house_address, house_owner, house_value, house_discount};
Cursor c = db.rawQuery("select * from " + database_table, null);
int iRow = c.getColumnIndex(house_id);
int iAdd = c.getColumnIndex(house_address);
int iOwn = c.getColumnIndex(house_owner);
int iVal = c.getColumnIndex(house_value);
int iDis = c.getColumnIndex(house_discount);
if(p==1){
c.moveToFirst();
}else if(p>1&&c.isAfterLast()==false){
c.moveToNext();
}
house.setHouse_id(c.getInt(iRow));
house.setHouse_address(c.getString(iAdd));
house.setHouse_owner(c.getString(iOwn));
house.setHouse_value(c.getInt(iVal));
house.setHouse_discount(c.getInt(iDis));
}
Change Shows to return the cursor that it extracts an do nothing else e.g.
Cursor Shows() {
return Cursor c = db.rawQuery("select * from " + database_table, null);
}
call the shows method before and outside of the next button click listener and also display the first house values after something along the lines of :-
cursor = db.shows();
if (cursor.moveToFirst()) {
int iRow = c.getColumnIndex(house_id); //etc
} else {
//handle no houses to show
}
......
within your next button listener
if (cursor.moveToNext) {
//do you stuff here
} else {
//handle end of rows here
}
previous button listener basically the same but uses moveToPrevious.
if you need to position to a specific house then loop through the cursor after it has been returned i.e. just move the existing code from Shows.
Make sure to do cursor.close(); when you have finished accessing the cursor.
My app is taking forever to load,how can I use paging that's it would load me like 10-15 people in a page and not to take 2 minute to my app for loading??
this is my code:
thank's for the help
public class Contacts extends Util<Contact> {
public Contacts(Activity activity) {
super(activity);
}
#Override
public void init() {
list = getContactsBasic();
for (int i = 0; i < list.size(); i++) {
Contact current = list.get(i);
current.image = getContactImage(current.id);
if (current.hasPhone) {
current.phones = getContactPhones(current.id);
}
}
}
LinkedList<Contact> getContactsBasic() {
Uri contactsUri = android.provider.ContactsContract.Contacts.CONTENT_URI;
Cursor cursor = activity.getContentResolver().query(contactsUri, null, null, null, null);
LinkedList<Contact> list = new LinkedList<Contact>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));
int hasPhone = cursor.getInt(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.HAS_PHONE_NUMBER));
// add more columns here
boolean hasPhoneBoolean; //editor: or simply: boolean hasPhoneBoolean = (hasPhone == 1)
if (hasPhone == 1){
hasPhoneBoolean = true;
}
else {
hasPhoneBoolean = false;
}
Contact contact = new Contact(id, name, hasPhoneBoolean);
//Contact contact = new Contact(id, name, (hasPhone == 1) ? true : false);
list.add(contact);
}
while (cursor.moveToNext());
}
cursor.close();
}
return list;
}
LinkedList<Phone> getContactPhones(int id) {
Uri phonesUri = android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String filter = android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + String.valueOf(id);
Cursor cursor = activity.getContentResolver().query(phonesUri, null, filter, null, null);
LinkedList<Phone> list = new LinkedList<Phone>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String number = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = cursor.getInt(cursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.TYPE));
Phone phone = new Phone(number, type);
list.add(phone);
}
while (cursor.moveToNext());
}
Change
Cursor cursor = activity.getContentResolver().query(contactsUri, null, null, null, null);
to
Cursor cursor = activity.getContentResolver().query(contactsUri, null, null, null, "ASC LIMIT " + HOW_MANY_ROWS_YOU_NEED);
I'm trying to build a graph in achartengine with data from my SQLite database. Getting the data from the database works, but it does always build just one point and not a graph. What am I doing wrong?
Here is my code:
public String getValue1(long l) {
String[] columns = new String[]{ KEY_Value1, KEY_Value2 };
Cursor c = Database.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ KEY_Value1, KEY_Value2 };
Cursor c = Database.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(1);
return value2;
}
return null;
}
DB getData = new DB(this);
getData.open();
for (int i = 1; value1 == null; i++) {
Stirng value1 = getData.getValue1(i);
String value2 = getData.getValue2(i);
}
getData.close();
x = Double.parseDouble(value1);
y = Double.parseDouble(value2);
mCurrentSeries.add(x, y);
if (mChartView != null) {
mChartView.repaint();
}
}
Edit the second part to this code:
DB getData = new DB(this);
getData.open();
for (int i = 1; value1 == null; i++) {
String value1 = getData.getValue1(i);
String value2 = getData.getValue2(i);
x = Double.parseDouble(value1);
y = Double.parseDouble(value2);
mCurrentSeries.add(x, y); //*** this has to be inside the loop in order to draw more than one point ***
}
getData.close();
if (mChartView != null) {
mChartView.repaint();
}
}
I have two buttons inside of my application, one for next and one for prev. I want the next button to get the next record inside of my database and display it inside of my view, and the prev button to get the previous record and display it inside of my view. How would I call the next or previous record? I have looked for tutorials and stuff but didn't find any. I anyone has a tutorial please share with me. Thanks for any help. I wish I had some code to provide but I really don't know where to start.
I use an int to pull the record from the dbase.
From my ContactView class
static long record = 1;
public void getData() {
DBase db = new DBase(this);
db.open();
lastRecord = db.lRec();
firstRecord = db.fRec();
rRec = db.getRec(record);
db.close();
}
then my query is from my Dbase class
public String[] getRec(long record) {
record = ContactView.record;
String[] columns = new String[] { KEY_ROWID, KEY_ONE, KEY_TWO,
KEY_THREE, KEY_FOUR, KEY_FIVE, KEY_SIX };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ record, null, null, null, null);
if (c != null && c.moveToFirst()) {
String rRec = c.getString(0);
String rOne = c.getString(1);
String rTwo = c.getString(2);
String rThree = c.getString(3);
String rFour = c.getString(4);
String rFive = c.getString(5);
String rSix = c.getString(6);
String[] rData = { rRec, rOne, rTwo, rThree, rFour,
rFive, rSix };
return rData;
}
return null;
}
and the next few are from my ContactView class
my buttons
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLvPrev:
recordMinus();
display();
break;
case R.id.bSQLvNext:
recordPlus();
display();
break;
}
}
and the methods they call
public void display() {
etSQLvRec.setText(rRec[0]);
etSQLvOne.setText(rRec[1]);
etSQLvTwo.setText(rRec[2]);
etSQLvThree.setText(rRec[3]);
etSQLvFour.setText(rRec[4]);
etSQLvFive.setText(rRec[5]);
etSQLvSix.setText(rRec[6]);
}
public void recordPlus() {
record++;
}
public void recordMinus() {
record--;
}
That will get the record from the database based on the "record" variable, and the buttons increment it, or decrement it, it also skips any "empty" records.
EDIT OK, I had changed some stuff around since I lasted used my db, so use the next recordPlus() and recordMinus() code instead
public void recordPlus() {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
do {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
} while (rRec == null);
}
public void recordMinus() {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
do {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
} while (rRec == null);
}
And you'll need my fRec() and lRec() which find the first and last records in the DB
public long fRec() {
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "min(" +
KEY_ROWID
+ ")" }, null, null, null, null, null);
c.moveToFirst();
long rowID = c.getInt(0);
return rowID;
}
}
public long lRec() {
long lastRec = 0;
String query = "SELECT ROWID from Table order by ROWID DESC limit 1";
Cursor c = ourDatabase.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
lastRec = c.getLong(0);
}
return lastRec;
}