Getting the next record into view from database - android

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;
}

Related

Display each row from Database on a new line in a TextView

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");
}

Get single record from Inner Joins SQLite

I am new to android programming. I am having a little issue on how to retrieve a single record while using Inner joins. From research I know how to do it with one table e.g
public Shop getShop(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SHOPS, new String[] { KEY_ID,
KEY_NAME, KEY_SH_ADDR }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Shop contact = new Shop(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return shop
return contact;
}
But I am at a loss when I have to consider three different tables. I have been able to retrieve all records, currently my code to retreive a single record is below. I have been able to replace ? with a corresponding id and it works but I obviously do not want to have that static.
getTeam method
//Getting Single Team
public List < Team > getTeam() {
List < Team > teamList = new ArrayList < Team > ();
// Select All Query
String selectQuery = "SELECT teams.id, teams.team_name, teams.image, teams_vs_leagues.points, leagues.league_name " +
"FROM teams_vs_leagues " +
"INNER JOIN teams " +
"ON teams_vs_leagues.team_id = teams.id " +
"INNER JOIN leagues " +
"ON teams_vs_leagues.league_id = leagues.id " +
"WHERE teams.id = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Team team = new Team();
team.setId(Integer.parseInt(cursor.getString(0)));
team.setTeamName(cursor.getString(1));
team.setPath(cursor.getString(2));
team.setPoints(Integer.parseInt(cursor.getString(3)));
team.setLeagueName(cursor.getString(4));
// Adding team to list
teamList.add(team);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return team list
return teamList;
}
Team class
public class Team {
String team_name, path, league_name;
int id, league_id, points;
public Team(int keyId, String team_name, String path,
int points, String league_name) {
this.id = keyId;
this.team_name = team_name;
this.path = path;
this.points = points;
this.league_name = league_name;
}
public Team() {}
public Team(int keyId) {
this.id = keyId;
}
public int getId() {
return id;
}
public void setId(int keyId) {
this.id = keyId;
}
public int getLeagueId() {
return league_id;
}
public String getTeamName() {
return team_name;
}
public String getLeagueName() {
return league_name;
}
public void setLeagueName(String league_name) {
this.league_name = league_name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public void setTeamName(String team_name) {
this.team_name = team_name;
}
public void setLeague_id(int league_id) {
this.league_id = league_id;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
Since you are using placeholder
"WHERE teams.id = ?";
in your query , you need to pass selection arguments in rawQuery() so that during the execution of your query , the placeholder will be replaced by the actual value.
Cursor cursor = db.rawQuery(selectQuery, new String[]{id});//"id" is the value which you want to pass in place of "?". You can hardcode it or you can pass it all the way to getTeam()
Check this .

Can't set a paging contact list in android

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);

android : How to iterate using cursor.moveToPosition(x)?

//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");
}

Android - SQLite Column does not exist from certain page

I'm messing around with some SQLite databases for an Android app. I have a 'player' table with several players, and a one-to-many 'skill' table which has each player's skill points, like Shooting and Rebounding.
I have one activity in the app for actually filling out textboxes and inserting a player into the database. When the user hits the 'Add Player' button, a row is inserted into the 'player' table and a row is inserted into the 'skills' table which has a foreign key that references the 'player' table. After these inserts, I did a query to check if I could read the 'Shooting' value from the 'skills' table and put it in a Toast notification. That worked fine, and the code I used is here:
SQLiteDatabase db2 = dbHelper.getReadableDatabase();
String[] projection = { "shooting" };
String sortOrder = "shooting" + " DESC";
Cursor c = db2.query(
"skills", // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
c.moveToFirst();
int shooting = c.getInt(c.getColumnIndexOrThrow("shooting"));
Toast.makeText(this, "" + shooting, Toast.LENGTH_SHORT).show();
After I saw that this was working, I commented it out and put in an Intent to make the app switch to the 'Roster' activity after the player and skills are inserted. On the 'Roster' activity, I want to get each player's 'Shooting' skill. When I use the exact same code from above (which works from the other activity) I get an error which says:
06-16 15:59:42.602: E/AndroidRuntime(31537): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.silverray.messaround/com.silverray.messaround.Roster}: java.lang.IllegalArgumentException: column 'shooting' does not exist
I can't figure out why it's saying the 'shooting' column doesn't exist when I know I included it in my SQL Create statement, and I was even able to read this exact same column with the same code from another activity.
Thanks for reading. Any ideas?
EDIT: This is the full code for the Roster activity:
public class Roster extends Activity {
int teamID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_roster);
// CHECK ROSTER
DatabaseContract dbContract = new DatabaseContract();
DatabaseContract.DbHelper dbHelper = dbContract.new DbHelper(this);
SQLiteDatabase dbCheck = dbHelper.getReadableDatabase();
Intent intent = getIntent();
int ID = intent.getIntExtra("ID", 1);
teamID = ID;
String stringID = String.valueOf(ID);
String[] projection = { "_id, playerFirstName, playerLastName, playerPosition" };
String sortOrder = "playerFirstName" + " ASC";
Cursor c = dbCheck.query(
"player",
projection,
null,
null,
null,
null,
sortOrder
);
c.moveToFirst();
int rowsAffected = c.getCount();
if (rowsAffected < 1) {
TextView rosterList = (TextView) findViewById(R.id.txtListRoster);
rosterList.setText("Your team doesn't have any players!");
c.close();
dbCheck.close();
} else {
String players = "";
for (int l = 0; l < rowsAffected; l++) {
String playerName = c.getString(c.getColumnIndexOrThrow("playerFirstName"));
String playerLastName = c.getString(c.getColumnIndexOrThrow("playerLastName"));
String position = c.getString(c.getColumnIndexOrThrow("playerPosition"));
int playerID = c.getInt(c.getColumnIndexOrThrow("_id"));
String player_ID = String.valueOf(playerID);
String pos = "";
if (position.equals("Point Guard")) {
pos = "PG";
} else if (position.equals("Shooting Guard")) {
pos = "SG";
} else if (position.equals("Small Forward")) {
pos = "SF";
} else if (position.equals("Power Forward")) {
pos = "PF";
} else if (position.equals("Center")) {
pos = "C";
}
SQLiteDatabase db2 = dbHelper.getReadableDatabase();
String[] projection2 = { "shooting" };
String sortOrder2 = "shooting" + " DESC";
Cursor c2 = db2.query(
"skills",
projection2,
null,
null,
null,
null,
sortOrder2
);
c2.moveToFirst();
//** Everything works until this line:
int shooting = c2.getInt(c.getColumnIndexOrThrow("shooting"));
players += playerName + " " + playerLastName + " (" + pos + ") Shooting: ";
if (l != (rowsAffected - 1)) {
players += "\n";
}
TextView rosterList = (TextView) findViewById(R.id.txtListRoster);
rosterList.setText(players);
if (l != (rowsAffected - 1)) {
c.moveToNext();
}
c2.close();
}
c.close();
dbCheck.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.roster, menu);
return true;
}
public void addPlayer(View view) {
Intent goToAddPlayer = new Intent(this, AddPlayer.class);
goToAddPlayer.putExtra("ID", teamID);
this.startActivity(goToAddPlayer);
this.finish();
return;
}
}
int shooting = c2.getInt(c.getColumnIndexOrThrow("shooting"));
should be
int shooting = c2.getInt(c2.getColumnIndexOrThrow("shooting"));
You are now working on 2nd query but trying to get column index from 1st.

Categories

Resources