I am aware that this question has been asked multiple times before but none of the solutions have worked for me. This is my code:
public class reminderDAO extends dbManager{
public reminderDAO(Context context) {
super(context);
}
// Adding new reminder
public void addReminder(Reminder reminder) {
//dbm.gettingWritable(values);
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(getKEY_DATE(), reminder.getReminderDate());
values.put(getKEY_TITLE(), reminder.getReminderTitle());
values.put(getKEY_DESC(), reminder.getReminderDescription());
values.put(getKEY_TIME(), reminder.getReminderTime());
// Inserting Row
db.insert(getDATABASE_TABLE(), null, values);
db.close(); // Closing database connection
}
public List<Reminder> getAllReminders(ListView lv) {
ArrayList<Reminder> reminderList = new ArrayList<Reminder>();
// Select All Query
String selectQuery = "SELECT * FROM " + getDATABASE_TABLE();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
MainActivity ma = new MainActivity();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Reminder r = new Reminder();
r.setReminderDate(cursor.getString(0));
r.setReminderTitle(cursor.getString(1));
r.setReminderDescription(cursor.getString(2));
r.setReminderTime(cursor.getString(3));
// Adding reminder to list
reminderList.add(r);
} while (cursor.moveToNext());
}
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this,
android.R.layout.simple_list_item_1,
reminderList );
lv.setAdapter(arrayAdapter);
// return reminder list
return reminderList;
}
}
I've got a feeling it is to do with 'this' inside the arrayAdapter. I have tried getActivity(), this.getActivity(), reminderDAO.this.getActivity(), MainActivity.this and reminderDAO.this.
Anyone have a solution?
Create a Context variable in your class. and assign it from the constructor parameter.
private Context context;
public reminderDAO(Context context) {
this.context = context;
super(context);
}
Then use this variable to pass to the ArrayAdapter
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this.context,
android.R.layout.simple_list_item_1,
reminderList );
Related
I want to show data based on column values, is that possible?
My adapter
public Cursor getDisease() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_GEJALA, new String[]{
KEY_ID,
KEY_GEJALA,
KEY_PENYAKIT,
KEY_AREA,
KEY_KODE_PENYAKIT
},
null,
null,
null,
null,
KEY_GEJALA,
null);
}
My activity then
private void loadListView(View view) {
ListView listView = view.findViewById(R.id.list_view);
arrayList = new ArrayList<>();
Cursor c = sqliteHelper.getDisease();
if (c.moveToFirst()) {
do {
arrayList.add(c.getString(1));
} while (c.moveToNext());
}
adapter = new ListViewAdapter(getActivity(), arrayList, true);
listView.setAdapter(adapter);
}
I am expecting to show code based on category
How to get List View android studio.this is my code
public class StockSearchActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabase;
DbHelper dbHelper;
Cursor cursor;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_search);
listView = findViewById(R.id.display_listview);
dbHelper = new DbHelper(this);
Cursor result = dbHelper.getAllData();
final ArrayList<String> theList = new ArrayList<>();
//get the data to the list view
if(result.getCount() == 0 ){
Toast.makeText(StockSearchActivity.this,"Databse is empty",Toast.LENGTH_LONG).show();
}else{
while (result.moveToNext()){
theList.add(result.getString(0));
theList.add(result.getString(1));
theList.add(result.getString(2));
theList.add(result.getString(3));
theList.add(result.getString(4));
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_expandable_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}
following code is my activity code for list view.is this correct.code is not working
//getAllData
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + tbName ,null);
return result;
}
Above code has been implemented in the database class.
Set your Adapter outside while loop
//get the data to the list view
if(result.getCount() == 0 ){
Toast.makeText(StockSearchActivity.this,"Databse is empty",Toast.LENGTH_LONG).show();
}else{
while (result.moveToNext()){
theList.add(result.getString(0));
theList.add(result.getString(1));
theList.add(result.getString(2));
theList.add(result.getString(3));
theList.add(result.getString(4));
}
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_expandable_list_item_1,theList);
listView.setAdapter(listAdapter);
}
Your problem is in the below line
SQLiteDatabase db = this.getWritableDatabase();
When you are trying to fetch data from database, it should be opened in readable mode like below.
SQLiteDatabase db = this.getReadableDatabase();
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..
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.
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