Listview for SQL lite - android

I was following a school tutorial for sql lite, and the output was a list of buttons. Is it possible to output this to a ListView instead?
I've tried googling and youtube but somehow the tutorial I was following seems to have more files?
Confused newbie here!
Thanks in advance!
This code appears in the onCreate(Bundle savedInstanceState)
private void ShowExistingIdeas() {
Idea[] ideas = new Ideas(this).getAllIdeas();
if(ideas != null && ideas.length > 0)
{
for(int index = 0; index < ideas.length; index++)
{
Button ideaButton = new Button(this);
ideaButton.setText(ideas[index].getTitle());
final int id = ideas[index].getId();
ideaButton.setTag(id);
ideaButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(OverviewActivity.this,
EditIdeaActivity.class);
i.putExtra("id", id);
startActivityForResult(i, 0);
}
});
//!!! The bit I'm trying to change. the xml with LinearLayout1 is completely empty****
((LinearLayout) findViewById(R.id.LinearLayout1)).
addView(ideaButton);
}
}
}
For your reference - the Ideas file
public class Ideas {
private Idea[] ideas;
private Context context;
public Ideas(Context context) {
this.context = context;
}
public Idea[] getAllIdeas() {
return getIdeasWithKeyword(null);
}
public Idea[] getIdeasWithKeyword(String keyword) {
ideas = null;
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
String where = null;
String[] whereArgs = null;
if (keyword != null) {
where = DbHelper.COL_TITLE + " LIKE '%?%' OR " + DbHelper.COL_DESC
+ " LIKE '%?%'";
whereArgs = new String[] { keyword };
}
Cursor c = db.query(DbHelper.TABLE_IDEAS, DbHelper.COLUMNS, where,
whereArgs, null, null, null);
if (c != null && c.moveToFirst()) {
ideas = new Idea[c.getCount()];
boolean hasMore = true;
for (int index = 0; hasMore; hasMore = c.moveToNext(), index++) {
int id = c.getInt(c.getColumnIndex(DbHelper.COL_ID));
String title = c
.getString(c.getColumnIndex(DbHelper.COL_TITLE));
String description = c.getString(c
.getColumnIndex(DbHelper.COL_DESC));
int priority = c
.getInt(c.getColumnIndex(DbHelper.COL_PRIORITY));
ideas[index] = new Idea(id, title, description, priority);
}
}
if (db != null && db.isOpen())
db.close();
return ideas;
}
public Idea getIdea(int id) {
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
Cursor c = db.query(DbHelper.TABLE_IDEAS, DbHelper.COLUMNS, "_id = "
+ id, null, null, null, null);
Idea idea = null;
if (c != null && c.moveToFirst()) {
String title = c.getString(c.getColumnIndex(DbHelper.COL_TITLE));
String description = c.getString(c
.getColumnIndex(DbHelper.COL_DESC));
int priority = c.getInt(c.getColumnIndex(DbHelper.COL_PRIORITY));
idea = new Idea(id, title, description, priority);
}
if (db != null && db.isOpen())
db.close();
return idea;
}
public void addIdea(Idea idea) {
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DbHelper.COL_TITLE, idea.getTitle());
values.put(DbHelper.COL_DESC, idea.getDescription());
values.put(DbHelper.COL_PRIORITY, idea.getPriority());
db.insert(DbHelper.TABLE_IDEAS, null, values);
if (db != null && db.isOpen())
db.close();
}
public void deleteIdea(int ideaId) {
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
db.delete(DbHelper.TABLE_IDEAS, DbHelper.COL_ID + "=" + ideaId, null);
if (db != null && db.isOpen())
db.close();
}
}

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

update row by id, cannote resolve sqlite update method

I need to update a row of my database, but I get an error with SQLiteDatabase update method not resolved.
I think this is because of the custom class I had to create:
public class DBAccess {
public static String LOG_TAG = "DBAccess";
private SQLiteDatabase database;
private DBHelper dbHelper;
public DBAccess(Context context) {
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Integer saveVehicle (Vehicle v){
Integer id = null;
if(this.database.isOpen() && !this.database.isReadOnly()){
String queryInsert = DBHelper.QueryAccessoAlDato.INSERT_VEHICLE;
try{
this.database.execSQL(queryInsert, new Object[]{v.getManufacturer(), v.getModel(), v.getPlate(),
v.getKmAmount(), v.getPrezzoGiorno(), v.getPrezzoSettimana(), v.getPrezzoMese(), v.getFuel(),
v.getGruppoMacchina()});
}catch (SQLException e){
Log.e(LOG_TAG, "Si รจ verificato un errore in inserimento " + e.getMessage());
e.printStackTrace();
return null;
}
Then this is the OnClick method of the main activity:
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "Marca: "+this.etManufacturer.getText());
Log.d(LOG_TAG, "Modello: "+this.etModel.getText());
Log.d(LOG_TAG, "Targa: "+this.etPlate.getText());
Log.d(LOG_TAG, "Kilometraggio: "+this.etKmAmount.getText());
Log.d(LOG_TAG, "PrezzoGiorno: "+this.etPrezzoGiorno.getText());
Log.d(LOG_TAG, "PrezzoSettimana: "+this.etPrezzoSettimana.getText());
Log.d(LOG_TAG, "PrezzoMese: "+this.etPrezzoMese.getText());
Log.d(LOG_TAG, "Fuel: "+this.etFuel.getText());
Log.d(LOG_TAG, "Gruppo Macchina: "+this.etGruppoMacchina.getText());
if(!(this.etManufacturer.getText().length() == 0) &&
!(this.etModel.getText().length() == 0) &&
!(this.etPlate.getText().length() == 0) &&
!(this.etKmAmount.getText().length() == 0) &&
!(this.etPrezzoGiorno.getText().length() == 0) &&
!(this.etPrezzoSettimana.getText().length() == 0) &&
!(this.etPrezzoMese.getText().length() == 0) &&
!(this.etFuel.getText().length() == 0) &&
!(this.etGruppoMacchina.getText().length() == 0)
){
Vehicle myVehicle = null;
String manufacturer = this.etManufacturer.getText().toString();
String model = this.etModel.getText().toString();
String plate = this.etPlate.getText().toString();
long KmAmount = Long.parseLong(this.etKmAmount.getText().toString());
int prezzoGiorno = Integer.parseInt(etPrezzoGiorno.getText().toString());
int prezzoSettimana = Integer.parseInt(etPrezzoSettimana.getText().toString());
int prezzoMese = Integer.parseInt(etPrezzoMese.getText().toString());
String fuel = this.etFuel.getText().toString();
String gruppoMacchina = this.etGruppoMacchina.getText().toString();
myVehicle = new Vehicle (manufacturer, model, plate, KmAmount, prezzoGiorno,
prezzoSettimana, prezzoMese,fuel, gruppoMacchina);
Log.d(LOG_TAG, "Hai aggiunto " + myVehicle + "con id" + vehicleID);
DBAccess dba = new DBAccess(this.getApplicationContext());
dba.open();
Log.d(LOG_TAG, "Avvio lettura da db");
if (this.getIntent().hasExtra(Const.ID_VEHICLE)) {
//http://stackoverflow.com/questions/9798473/sqlite-in-android-how-to-update-a-specific-row
ContentValues values= new ContentValues();
values.put(DBHelper.VEHICLE_MANUFACTORER_COLUMN, manufacturer);
values.put(DBHelper.VEHICLE_MODEL_COLUMN, model);
//values.put(DBHelper.KEY_PEDLOCATION, ped_location);
// values.put(DBHelper.KEY_PEDEMAIL, ped_emailid);
// etc etc
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=" + vehicleID, null);
finish();
}else{
dba.saveVehicle(myVehicle);
Log.d(LOG_TAG, "Ho salvato" + myVehicle);
dba.close();
finish();
So i get the error at line :
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=" + vehicleID, null);
How can I resolve this? Thank you!
First your DBAccess class should extend SQLiteOpenHelper class.
The Update method declaration is as below, the last parameter should be a String array,
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Change your code to as shown below:
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=?", new String[]{String.valueOf(vehicleID));

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

Select query in android?

public Cursor getsomething()
{
this.open();
Cursor c = database.rawQuery("SELECT content_id FROM " +
DatabaseHandler.Table_Name2 +
" where playlist_id==100813", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String path = c.getString(c.getColumnIndex("content_id"));
MainActivity.t1.append("\n");
MainActivity.t1.append(path);
}while (c.moveToNext());
}
}
this.close();
return null;
}
I am using the above code to get the values but it is showing all the values from he content_id column. What am I doing wrong?
this.open();
ContentValues values2 = new ContentValues();
String csvFilename = "/mnt/sdcard/playlist.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String Rowst[] = null;
while((Rowst = csvReader.readNext()) != null) {
st1 = Rowst[0];
st2= Rowst[1];
st3= Rowst[2];
st4= Rowst[3];
st5= Rowst[4];
st6 = Rowst[5];
st7 = Rowst[6];
st8 = Rowst[7];
st9 = Rowst[8];
st10 = Rowst[9];
st11 = Rowst[10];
st12 = Rowst[11];
st13 = Rowst[12];
st14 = Rowst[13];
st15 = Rowst[14];
st16 = Rowst[15];
st17 = Rowst[16];
st18 = Rowst[17];
st19 = Rowst[18];
values2.put(DatabaseHandler.play1,st1);
values2.put(DatabaseHandler.play2,st2);
values2.put(DatabaseHandler.play3,st3);
values2.put(DatabaseHandler.play4,st4);
values2.put(DatabaseHandler.play5,st5);
values2.put(DatabaseHandler.play6,st6);
values2.put(DatabaseHandler.play7,st7);
values2.put(DatabaseHandler.play8,st8);
values2.put(DatabaseHandler.play9,st9);
values2.put(DatabaseHandler.play10,st10);
values2.put(DatabaseHandler.play11,st11);
values2.put(DatabaseHandler.play12,st12);
values2.put(DatabaseHandler.play13,st13);
values2.put(DatabaseHandler.play14,st14);
values2.put(DatabaseHandler.play15,st15);
values2.put(DatabaseHandler.play16,st16);
values2.put(DatabaseHandler.play17,st17);
values2.put(DatabaseHandler.play18,st18);
values2.put(DatabaseHandler.play19,st19);
database.insert(DatabaseHandler.Table_Name2, null, values2);
}
csvReader.close();
this.close();
this is my code to insert data in the this table,i am trying to read a csvfile on the sdcard and entering its data into table am i doing something wrong i have posted this also if it helps
public Cursor getsomething()
{
this.open();
Cursor c = db.query(DatabaseHandler.Table_Name2, null, "playlist_id=100813", null, null, null, null);
if (c.getCount() > 0)
{
if (c.moveToFirst())
{
do {
String path = c.getString(c.getColumnIndex("content_id"));
MainActivity.t1.append("\n");
MainActivity.t1.append(path);
}while (c.moveToNext());
}
}
this.close();
return null;
}

Getting the next record into view from database

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

Categories

Resources