i need help with summing all the values in one of the columns (animalName) in my database. i have tried and referred to many other examples but quite haven't figured out how it works or is done. here is my Database class
public class DBController extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public DBController(Context applicationcontext) {
super(applicationcontext, "androidsqlite.db", null, 4);
Log.d(LOGCAT,"Created");
}
#Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE animals ( animalId INTEGER PRIMARY KEY, animalName INTEGER, animalColor TEXT, animalType TEXT)";
database.execSQL(query);
Log.d(LOGCAT,"animals Created");
}
#Override
public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
String query;
query = "DROP TABLE IF EXISTS animals";
database.execSQL(query);
onCreate(database);
}
public void insertAnimal(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("animalName", queryValues.get("animalName"));
values.put("animalColor", queryValues.get("animalColor"));
values.put("animalType", queryValues.get("animalType"));
database.insert("animals", null, values);
database.close();
}
public int updateAnimal(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("animalName", queryValues.get("animalName"));
values.put("animalColor", queryValues.get("animalColor"));
values.put("animalType", queryValues.get("animalType"));
return database.update("animals", values, "animalId" + " = ?", new String[] { queryValues.get("animalId") });
//String updateQuery = "Update words set txtWord='"+word+"' where txtWord='"+ oldWord +"'";
//Log.d(LOGCAT,updateQuery);
//database.rawQuery(updateQuery, null);
//return database.update("words", values, "txtWord = ?", new String[] { word });
}
public void deleteAnimal(String id) {
Log.d(LOGCAT,"delete");
SQLiteDatabase database = this.getWritableDatabase();
String deleteQuery = "DELETE FROM animals where animalId='"+ id +"'";
Log.d("query",deleteQuery);
database.execSQL(deleteQuery);
}
public ArrayList<HashMap<String, String>> getAllAnimals() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM animals";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("animalId", cursor.getString(0));
map.put("animalName", cursor.getString(1));
map.put("animalColor", cursor.getString(2));
map.put("animalType", cursor.getString(3));
wordList.add(map);
} while (cursor.moveToNext());
}
// return contact list
return wordList;
}
public HashMap<String, String> getAnimalInfo(String id) {
HashMap<String, String> wordList = new HashMap<String, String>();
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT * FROM animals where animalId='"+id+"'";
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
//HashMap<String, String> map = new HashMap<String, String>();
wordList.put("animalName", cursor.getString(1));
wordList.put("animalColor", cursor.getString(2));
wordList.put("animalType", cursor.getString(3));
//wordList.add(map);
} while (cursor.moveToNext());
}
return wordList;
}
public Cursor getTotal() {
SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery(
"SELECT SUM(animalName) as sum FROM animals", null);
}
}
and here is my main activity class
public class MainActivity extends ListActivity {
Cursor cursor;
Intent intent;
TextView animalId;
DBController controller = new DBController(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> animalList = controller.getAllAnimals();
if(animalList.size()!=0) {
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
animalId = (TextView) view.findViewById(R.id.animalId);
String valAnimalId = animalId.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),EditAnimal.class);
objIndent.putExtra("animalId", valAnimalId);
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter( MainActivity.this,animalList, R.layout.view_animal_entry, new String[] { "animalId","animalName","animalColor","animalType"}, new int[] {R.id.animalId, R.id.animalName, R.id.animalColor, R.id.animalType});
setListAdapter(adapter);
}
}
public void showAddForm(View view) {
Intent objIntent = new Intent(getApplicationContext(), NewAnimal.class);
startActivity(objIntent);
}
}
it would be great if anyone could help me solve this for me with a bit of explanation. thank you
Try this way
Cursor c = db.rawQuery("select sum(animalName) from animals;",null);
if(c.moveToFirst())
total = c.getInt(0);
else
total = -1;
c.close();
Summing names does not make sense. If you want to know how many there are, use COUNT instead of SUM.
Related
I am creating a contact application that works with SQLite database and I face a problem when I try to pass the id of the contact to another intent to use it in a query.
Here is my code :
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView contactsList;
DbContact dbContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsList = findViewById(R.id.contactList);
dbContact = new DbContact(this);
contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, update_contact.class);
Contact selected_contact =(Contact) contactsList.getItemAtPosition(i);
Toast.makeText(MainActivity.this, "ths position is " +selected_contact.getId(), Toast.LENGTH_SHORT).show();
/*intent.putExtra("id", selected_contact.getId());
startActivity(intent);*/
}
});
}
}
update_contact.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_contact);
int id = getIntent().getIntExtra("id",0);
db = new DbContact(this);
editName = (EditText) findViewById(R.id.editName);
editPhone = (EditText) findViewById(R.id.editPhone);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
Contact contact = db.getContactById(id);
editName.setText(contact.getName());
editPhone.setText(contact.getPhone());
}
BdContact :
public DbContact(#Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String create_table = "create table "+TABLE_CONTACTS+"("+KEY_ID+" int primary key AUTOINCREMENT, "+KEY_NAME+" varchar(30), "+KEY_PHONE+" varchar(30))";
sqLiteDatabase.execSQL(create_table);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String delete_table = "DROP TABLE IF EXISTS "+TABLE_CONTACTS;
sqLiteDatabase.execSQL(delete_table);
onCreate(sqLiteDatabase);
}
public void addContact(Contact contact){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PHONE, contact.getPhone());
db.insert(TABLE_CONTACTS, null, values);
}
public ArrayList<Contact> getAllContacts(){
ArrayList<Contact> contacts = new ArrayList<>();
String selectAll_query = "select * from "+ TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectAll_query, null);
if(cursor.moveToFirst()){
do{
int id = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME));
String phone = cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONE));
Contact contact = new Contact(id,name, phone);
contacts.add(contact);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return contacts;
}
public Contact getContactById(int id_contact){
Contact contact = null;
SQLiteDatabase db = this.getReadableDatabase();
String select_query = "select * from "+TABLE_CONTACTS+" where id = " + id_contact;
Cursor cursor = db.rawQuery(select_query, null);
if(cursor.moveToFirst()){
int id = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME));
String phone = cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONE));
contact = new Contact(id, name, phone);
}
return contact;
}
I think that the problem is in the database because I suspect the id didn't auto-incremented
Thank you guys for helping me solve this issue
Have you added the position?
listView.getItemAtPosition(position)
I have 3 classes: MainActivity, DBHelper (extended SQLiteOpenHelper) and Student class.
In DBHelper I have methods like: addNewStudent, deleteStudent, findStudent and getAllStudents.
The method "getAllStudents" return arrayList and I want to show elements of this one in the listView on the mainactivity layou but I have problem with parameter of the ArrayList.
I tried on String just to understand using ArrayAdapter:
MAIN ACTIVITY
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
editTextID = (EditText) findViewById(R.id.editTextID);
editTextName = (EditText) findViewById(R.id.editTextName);
listViewStudents = (ListView) findViewById(R.id.listViewStudents);
mDBStudents = new DBhelper(this);
// ------> this one provisional works:
final ArrayList<String> namesArray = new ArrayList<String>();
namesArray.add("Hania");
namesArray.add("Kasia");
final ArrayAdapter<String> namesAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,namesArray);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
namesArray.add(editTextName.getText().toString());
mDBStudents.addNewStudent(editTextName.getText().toString());
listViewStudents.setAdapter(namesAdapter);
// ------> this one using <object> parameter in the ArrayList doesn't work and my app is stopped. I tried with Log.d but how to do it correctly with objects...
final ArrayList<Student> studentArray = new ArrayList<Student>();
Student s1 = new Student(1, "Natalia");
studentArray.add(s1);
final ArrayAdapter<Student> studentAdapter = new ArrayAdapter<Student>(MainActivity.this, android.R.layout.simple_list_item_1, studentArray);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Student s2 = new Student(Integer.parseInt(editTextID.getText().toString()), editTextName.getText().toString());
studentArray.add(s2);
mDBStudents.addNewStudent(editTextName.getText().toString());
listViewStudents.setAdapter(studentAdapter);
I want to show elements from the ArrayList which I add when I click "addStudentButton" in the ListView. Later I want t open the new Intent when I click on one positon from the listView. Do you have any suggestions what is the best way for beginner user of android?
On some pages are info about using ArrayAdapter, Cursor etc. but they aren't so clarity for me
DBhelper class
public class DBhelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "student";
public static final String COLUMN_ID = "studentID";
public static final String COLUMN_NAME = "studentName";
//initialize the database
public DBhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT " + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public int addNewStudent(String studentName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME,studentName);
return (int) db.insert(TABLE_NAME,null, values); //???
}
public ArrayList<Student> getAllStudents() {
ArrayList<Student> result = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
result.add(
new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_NAME)
)
)
);
}
csr.close();
db.close();
return result;
}
public Student findStudent(int studentID) {
Student result = null;
String whereclause = COLUMN_ID + "=?";
String[] whereargs = new String[]{String.valueOf(studentID)};
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
result = new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_NAME)
)
);
}
csr.close();
db.close();
return result;
}
public Student deleteStudent(int studentID) {
Student result = null;
String whereclause = COLUMN_ID + "=?";
String[] whereargs = new String[]{String.valueOf(studentID)};
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME, null, whereclause, whereargs, null, null, null);
if (csr.moveToFirst()) {
result = new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)), csr.getString(csr.getColumnIndex(COLUMN_NAME)));
db.delete(TABLE_NAME, whereclause, whereargs);
}
csr.close();
db.close();
return result;
}
public boolean updateStudent(int studentID, String studentName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(COLUMN_ID, studentID);
args.put(COLUMN_NAME, studentName);
return db.update(TABLE_NAME, args, COLUMN_ID + "=" + ID, null) > 0;
}
}
Student class
public class Student {
private int studentID;
private String studentName;
public Student(int id, String studentName) { //konstruktor
this.studentID = id;
this.studentName = studentName;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
I have some sort of an issue and I'd really appreciate it, if
you could help me.
Problem: I want to take Data from a SQLite Database and display it in
a Listview or a Gridview, either way.
I watched a tutorial and tried to follow the rules and the idea behind it,
with copying the source code and changing the code piece by piece for my
own purpose. Strangely, the code I'm having issues with works in the tutorial
code, and also in another class in my project, but refuses to work in the
recent file..
So, this is the oncreate of the working file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_list);
mem_op = new Member_Operations(this);
mem_op.open();
List values = mem_op.getAllMembers();
et = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
gv = (GridView) findViewById(R.id.gv);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
gv.setAdapter(adapter);
} // oncreate
and this is the related super-class:
public class Member_Operations {
public DBHelper_Members db_helper;
private SQLiteDatabase database;
private String [] MEMBER_TABLE_COLUMNS = { db_helper.MEMBERS_COLUMN_ID,db_helper.MEMBERS_COLUMN_NAME,db_helper.MEMBERS_COLUMN_PERMISSION};
public Member_Operations(Context context)
{
db_helper = new DBHelper_Members(context);
}
public void open() throws SQLException{
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Member addMember(String name, String permission){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.MEMBERS_COLUMN_NAME, name);
contentValues.put(db_helper.MEMBERS_COLUMN_PERMISSION,permission);
long MemID = database.insert(db_helper.MEMBER_TABLE, null, contentValues);
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,db_helper.MEMBERS_COLUMN_ID + " = " +
+ MemID, null,null,null,null);
cursor.moveToFirst();
Member newComment = parseMember(cursor);
cursor.close();
return newComment;
}
public void deleteMember(Member mem){
long id = mem.getID();
SQLiteDatabase db = db_helper.getWritableDatabase();
db.delete(db_helper.MEMBER_TABLE, db_helper.MEMBERS_COLUMN_ID + " = " + id,
null);
}
public List getAllMembers(){
List members = new ArrayList();
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,null,null,null,null,null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Member member = parseMember(cursor);
members.add(member);
cursor.moveToNext();
}
cursor.close();
return members;
}
private Member parseMember(Cursor cursor){
Member member = new Member();
member.setID(cursor.getInt(0));
member.setName(cursor.getString(1));
member.setPermission(cursor.getString(2));
return member;
}
This is the one refusing to work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kal_op = new Kalender_Operations(this);
kal_op.open();
List values = kal_op.getAllDays();
ArrayAdapter<Date> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
// here i tried, unlike the first one, to add the Type(Date).
// But either way it doesn't work.
GridView gv = (GridView) findViewById(R.id.gv);
ListActivity la = new ListActivity();
la.setListAdapter(adapter);
}
And its super-class:
public class Kalender_Operations {
SQLiteDatabase database;
DBHelper db_helper;
String [] DATES_TABLE_COLUMNS = { db_helper.JANUARY_COLUMN_ID,
db_helper.JANUARY_COLUMN_DAY,db_helper.JANUARY_COLUMN_EVENT};
public Kalender_Operations(Context context)
{
db_helper = new DBHelper(context);
}
public void open() throws SQLException {
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Date addDate (String day, String event){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.JANUARY_COLUMN_DAY, day);
contentValues.put(db_helper.JANUARY_COLUMN_EVENT, event);
long DateID = database.insert(db_helper.JANUARY_TABLE,null,contentValues);
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, db_helper.JANUARY_COLUMN_ID
+ " = " + DateID,null,null,null,null);
cursor.moveToFirst();
Date newComment = parseDate(cursor);
cursor.close();
return newComment;
}
public void showDetails(int i, Context context){
Intent intent = new Intent(context, Test_Intent.class);
intent.putExtra("Position", i);
intent.putExtra("Month", db_helper.JANUARY_TABLE);
intent.putExtra("Year", db_helper.JANUARY_YEAR);
context.startActivity(intent);
}
public List getAllDays(){
List Dates = new ArrayList();
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Date date = parseDate(cursor);
Dates.add(date);
cursor.moveToNext();
}
cursor.close();
return Dates;
}
public Date parseDate(Cursor cursor){
Date date = new Date();
date.setID(cursor.getInt(0));
date.setDay(cursor.getString(1));
date.setEvent(cursor.getString(2));
return date;
}
}
Please help me. I really want to continue learning, but I spent a lot of time now trying to figure out why one works, the other one doesn't..
Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.
Here's my code getClientNames in DatabaseHelper class:
public Cursor getSitesByClientname(String id) {
String[] args={id};
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
String results = "";
/*int count = myCursor.getCount();
String[] results = new String[count + 1];
int i = 0;*/
if (myCursor != null) {
if(myCursor.getCount() > 0)
{
for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
{
results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename"));
}
}
}
return results;
}
One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.
Here's the ClientSites class where I want to display the data:
public class ClientSites extends Activity {
//public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
private Cursor ourCursor = null;
private Adapter adapter=null;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
//dbHelper.createDatabase();
dbHelper.openDataBase();
ourCursor = dbHelper.getSitesByClientname(uID);
Log.e("ALERT", uID.toString());
startManagingCursor(ourCursor);
Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
{
Intent i=new Intent(ClientSites.this, InspectionPoints.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class Adapter extends CursorAdapter {
#SuppressWarnings("deprecation")
Adapter(Cursor c) {
super(ClientSites.this, c);
}
//#Override
public void bindView(View row, Context ctxt,
Cursor c) {
Holder holder=(Holder)row.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Holder holder=new Holder(row);
row.setTag(holder);
return(row);
}
}
static class Holder {
private TextView name=null;
Holder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, DBUserAdapter r) {
name.setText(r.getName(c));
}
}
}
Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
dbHelper.openDataBase();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//ourCursor = dbHelper.getSitesByClientname(uID);
//Log.e("ALERT", uID.toString());
//startManagingCursor(ourCursor);
//Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!!
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
I Created a Listview from a database. Here is the code I used for my app
Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.
public List<Category> getAllCategorys() {
ArrayList<Category> categoryList = new ArrayList<Category>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
try{
if (cursor.moveToFirst()) {
do {
Category category = new Category();
category.setID(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
// Adding category to list
categoryList.add(category);
} while (cursor.moveToNext());
}
}finally{
cursor.close();
}
db.close();
// return category list
return categoryList;
Here is how I fill the ListView by calling the database.
int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();
category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{
category_data[i] = cn.getCategory(); // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);
EDIT: Here is something that should work for you
public List<String> getSitesByClientname(String id) {
String[] args={id};
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
try{
if (myCursor.moveToFirst()){
do{
result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
}while(myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
return result;
}
Use it like this
List<String> sites_data = dbHelper.getSitesByClientname(uID);
result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{
result_data[i] = s; // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);
If you want to return the Cursor from dbHelper you can do something like this...
public Cursor getSitesByClientname(String id) {
String[] args={id};
return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}
I'd also take some time to read the listview tutorial
I'm trying to display string on the textview. I'm succesfully able to print it on the console from database, but I'm not able to figure out how to print all the strings on different different textviews. Here is my code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText search;
Button insert;
TextView txt1, txt2, txt3, txt4, txt5;
DatabaseHandler db;
List<History> history;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
search = (EditText) findViewById(R.id.search_word);
insert = (Button) findViewById(R.id.insert);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
txt3 = (TextView) findViewById(R.id.txt3);
txt4 = (TextView) findViewById(R.id.txt4);
txt5 = (TextView) findViewById(R.id.txt5);
insert.setOnClickListener(this);
history = db.getAllHistory();
}
public void onClick(View v) {
db.addHistory(new History(search.getText().toString(), null));
Toast.makeText(getApplicationContext(),
"Inserted: " + search.getText().toString(), Toast.LENGTH_LONG)
.show();
}
#Override
protected void onStart() {
super.onStart();
List<History> history = db.getAllHistory();
for (History cn : history) {
String log = "Search Strings: " + cn.getName();
Log.d("Search Strings: ", log);
}
}
}
This is my activity in which I'm bringing my all database value on onStart() function. Now here I have to set all the data coming from database on the textview. Here is my DabaseHandler class in which I'm taking out each row.
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "historyManager";
private static final String TABLE_HISTORY = "histories";
private static final String KEY_NAME = "history";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_HISTORY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
void addHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
db.insert(TABLE_HISTORY, null, values);
db.close();
}
History getHistory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HISTORY, new String[] { KEY_NAME },
"=?", new String[] { String.valueOf(id) }, null, null, null,
null);
if (cursor != null)
cursor.moveToFirst();
History history = new History(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return history;
}
public List<History> getAllHistory() {
List<History> historyList = new ArrayList<History>();
String selectQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
History contact = new History();
contact.setName(cursor.getString(0));
historyList.add(contact);
} while (cursor.moveToNext());
}
return historyList;
}
public int updateHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
return db.update(TABLE_HISTORY, values, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
}
public void deleteHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HISTORY, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
db.close();
}
public int getHistoryCount() {
String countQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Please help in getting data printed on the textview. On the Log.d I can see all my data coming, one after another. But I'm not able to print all the data.
It's answer for "Thank You for that. Can you tell me how to set the data which I have printed in MainActivity on onStart() method (Log.d("")). If you can give me the code for that, that will be much easier for me."
try this:
List<String> listNames = new ArrayList<String>();//global variable
List<History> history = db.getAllHistory();
for (History cn : history) {
listNames.add(cn.getName());
}
or, if have in History field date try is, after easy will sort:
Map<String, Date> historyMap = new HashMap<String, Date>();
List<History> history = db.getAllHistory();
for (History cn : history) {
historyMap.put(cn.getName, cn.getDate);
}
You need make ListView in which will show your data from DB.Because you have many items datas getting from db.
I suggest to the next version:
In xml file you creat:
<ListView
android:id="#+id/list_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...>
You need create Adapter for your list with next xml resource:
<TextView
android:id="#+id/text_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
In java code:
in onCreate:
ListView list = (ListView) findViewById(R.id.list);
OurAdapter adapter = new OurAdapter(..., List<String> yourListWithName);
list.setAdapter(adapter);
if you want a more detailed description of the code tell me.
For add last item in top you need next, create spec. internal class :
class Holder implements Comparable<Holder> {
String key;
Double value;
public int compareTo(Holder another) {
return another.value.compareTo(value);
}
}
and use him how:
List<this.Holder> listSortforLastInTop = new ArrayList<this.Holder>();
and
for(...){
Holder holder = new Holder();
holder.key=...;
older.value=..;
listSortforLastInTop.add(holder);
}