I am passing the value to DB Helper to query, and I have 2 errors.
One in query
DB Helper:
public Cursor opis(final String sid){
SQLiteDatabase db = this.getWritableDatabase();
final String ID = sid;
Cursor rezultat = db.rawQuery("Select opis from tablica where id = ? LIMIT 1" , new String[] {ID});
return rezultat;
}
Error is on question mark:
Second error is in my MainActivity:
private void prikaz() {
final ListView listView = (ListView) findViewById(R.id.idListView);
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDb.opis();
if(data.getCount() == 0){
Toast.makeText(this, "No data!",Toast.LENGTH_LONG).show();
}
else
{
while(data.moveToNext()){
String opis = data.getString(0);
}
}
}
Error:
for the first error use
Cursor rezultat = db.rawQuery("Select opis from tablica where id = '"+yourvalue+"' LIMIT 1" , new String[] {ID});
for the secound you should pass String value to your method opis()
Related
I need to get all of records from TABLE_NOTES, Here is my method for calling all of records:
public List<NotesFragmentCreate> getAllNotes() {
List<NotesFragmentCreate> notes = new ArrayList<NotesFragmentCreate>();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
NotesFragmentCreate n = new NotesFragmentCreate();
n.setId(c.getInt(c.getColumnIndex(KEY_ID_NOTES)));
n.setTitle(c.getString(c.getColumnIndex(KEY_TITLE)));
n.setCreated(c.getString(c.getColumnIndex(KEY_CREATED)));
n.setContent(c.getString(c.getColumnIndex(KEY_CONTENT)));
// adding to note list
notes.add(n);
} while (c.moveToNext());
}
return notes;
}
Then I create arrays in other class:
String[] title,created,content;
db = new DatabaseHelper(getActivity());
List<NotesFragmentCreate> allNotes = db.getAllNotes();
for (NotesFragmentCreate note : allNotes) {
//how can I get each of record to store in this array?
title[?] = note.getTitle();
created[?] = note.getCreated();
content[?] = note.getContent();
}
Because I want to impement those arrays in a listView
adapter = new ListNotesAdapter(getActivity(), title, created);
Its simple do as have variable inside loop shown as below.
Replace
String[] title,created,content;
List<NotesFragmentCreate> allNotes = db.getAllNotes();
for (NotesFragmentCreate note : allNotes) {
//how can I get each of record to store in this array?
title[?] = note.getTitle();
created[?] = note.getCreated();
content[?] = note.getContent();
}
with
List<NotesFragmentCreate> allNotes = db.getAllNotes();
String[] title=new String[allNotes.size()];
String[] created=new String[allNotes.size()];
String[] content=new String[allNotes.size()];
int i=0;
for (NotesFragmentCreate note : allNotes) {
//how can I get each of record to store in this array?
title[i] = note.getTitle();
created[i] = note.getCreated();
content[i] = note.getContent();
i++
}
I'm writing an app that manipulates with database consists of 3 tables. I created this database from json file using models (Worker model, specialty model) with getters and setters. Now I want to get specific info from this database. I'v already made it but my code is pretty silly. What I need is to change the architecture of my app but I don't know how exactly it should looks like.
This is the examples of my methods, and they are pretty week
This is how I add info into database. I like it, I think it's correct:
public void addWorker(Worker worker){
List<Specialty> specialty;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//fixind names
String f_name = fixName(worker.getF_name());
String l_name = fixName(worker.getL_name());
String birthday = fixDate(worker.getBirthday());
values.put(KEY_F_NAME, f_name);
values.put(KEY_L_NAME, l_name);
values.put(KEY_BIRTHDAY, birthday);
values.put(KEY_AVATR_URL, worker.getAvart_url());
specialty = worker.getSpecialty();
long worker_id = db.insert(TABLE_WORKERS,null,values);
//add unique specialty
for (Specialty spec: specialty){
createRelations(worker_id, spec.getSpecialty_id());
if (getCount(spec.getSpecialty_id()) == 0){
addSpecialty(spec);
}
}
}
And this is how I take info from database:
public String[] getFullInfo(String worker_name){
String selectQuery = "HUGE QUERY HERE "where workers.f_name =?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {worker_name});
String[] details = new String[5];
c.moveToFirst();
while (c.isAfterLast() == false){
details[0] = c.getString(c.getColumnIndex(KEY_F_NAME));
details[1] = c.getString(c.getColumnIndex(KEY_L_NAME));
details[2] = c.getString(c.getColumnIndex(KEY_BIRTHDAY));
details[3] = c.getString(c.getColumnIndex("age"));
details[4] = c.getString(c.getColumnIndex(KEY_SPEC_NAME));
c.moveToNext();
}
return details;
}
This is my another query and it has different return type:
public List<Map<String ,String>> getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
//making list of workers
List<Map<String ,String>> data = new ArrayList<Map<String,String>>();
c.moveToFirst();
while (c.isAfterLast() == false){
Map<String,String> datum = new HashMap<String,String>(2);
datum.put(KEY_F_NAME, c.getString(c.getColumnIndex(KEY_F_NAME)));
datum.put(KEY_L_NAME, c.getString(c.getColumnIndex(KEY_L_NAME)));
datum.put(KEY_BIRTHDAY, c.getString(c.getColumnIndex(KEY_BIRTHDAY)));
data.add(datum);
c.moveToNext();
}
return data;
}
and the third one, which also have different return type:
public List<String> getAllSpecs_Names(){
List<String> spec_names = new ArrayList<String>();
String selectQuery = "select * from " + TABLE_SPECIALTY;
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()){
do{
spec_names.add(c.getString(c.getColumnIndex(KEY_SPEC_NAME)));
}while (c.moveToNext());
}
return spec_names;
}
I know, that this is all wrong.
Please tell me how I should make all my queries.
It will be good if you give me the link to check how the app should look like
instead of returning a List or Map, you should better return a own CursorWrapper
so you could could look like this:
public WorkerCursor getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
return new WorkerCursor(cursor);
}
public static class WorkerCursor extends CursorWrapper {
/**
* Creates a cursor wrapper.
*
* #param cursor The underlying cursor to wrap.
*/
public WorkerCursor(Cursor cursor) {
super(cursor);
}
public Worker getWorker() {
return getWorkerAtCursor();
}
public Worker getWorker(int position) {
if (moveToPosition(position)) {
return getWorkerCursor();
} else {
return null;
}
}
private Worker getWorkerAtCursor() {
if (isBeforeFirst() || isAfterLast()) {
return null;
}
worker worker = new Worker();
worker.name = c.getString(c.getColumnIndex(KEY_F_NAME));
....
return worker;
}
}
and the same for your List, just with a other CursorWrapper
and don't forget to close the CursorWrapper, when it's no more needed, like in onDestroy of Activity and so
I am trying to query all the users data that belong to him uniquely. through FK_ID of the user in the notes table.
// Listing all notes
public Cursor listNotes() {
SQLiteDatabase db = help.getReadableDatabase();
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Count how many Notes user has
public int NoteCount() {
String countQuery = "SELECT * FROM " + help.NOTE_TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public void editNote(long id, String title, String body) {
ContentValues edit = new ContentValues();
edit.put(help.COLUMN_TITLE, title);
edit.put(help.COLUMN_BODY, body);
open();
db.update(help.NOTE_TABLE, edit, help.NOTES_ID + "=" + id, null);
close();
}
// Deleting single note
public void deleteNote(long id) {
open();
db.delete(help.NOTE_TABLE, help.NOTES_ID + "=" + id, null);
close();
}
}
I have a tab that will then return all the users data uniquely to him. This tab is a fragment.the Method populateList() will be called onCreateView
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
This is a null pointer. Am i passing the data wrong
Cursor cursor = control.listNotes();
Your listNotes method should look like :
public Cursor listNotes(long userId) {
Cursor c = getActivity().getContentResolver().query(yourTodoTableURI, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, help.COLUMN_USER_ID + " = ?", new String[]{String.valueOf(userId)} , null);
return c;
}
try this:
public List<String> getAllTask(int userID){
String query = "Select * from tablename where ID =" + userID;
cursor = db.query(); //do your code here
int id = cursor.getInt(cursor.getColumnIndex(tablename.ID));
List<String> task = new ArrayList<String>();
String query = "Select * from tableTask where ID =" + id";
cursor = db.query(); //
if (cursor != null) {
cursor.movetofirst();
// do your code here
do{
String task = cursor.get......
task.add(task);
}while(cursor.movetonext);
}
return task;
}
I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}
i have an error in my application.
I'm new in making apps for android, so i donĀ“t now what's wrong...
this is in the log:
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets
i have a SQLite database in which is this method:
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
return petList;
}
and then i'am using this method from database in other activity to fill the ListView by the names of every pet....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
PetListView = (ListView)findViewById(R.id.list);
MyDatabaseHelper db = new MyDatabaseHelper(this);
String [] items = new String[db.getPetsCount()];
List<Pet> pets = db.getAllPets();
for (int i = 0; i < db.getPetsCount(); i++) {
items[i] = pets.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, items);
PetListView.setAdapter(adapter);
}
when this activity starts the application crashes down..
Please, can you tell me what's worng? How can i fix it? Thanks a much for help.
EDIT:
getPetsCount() method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
i solved this by myself at the end by replace the getPetsCount method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
First, you should close your cursor once you have finished to use it (that may solve your issue)
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
// Close cursor when finished using it
cursor.close();
return petList;
}