I've encountered an error with creating and loading my database for my program. I get an error of "no such column: responsible: , while compiling:
SELECT id, name, responsible, priority
FROM tasks "
Can someone point out what I've done wrong. Thanks
public class TasksSQLiteOpenHelper extends SQLiteOpenHelper {
public static final int VERSION = 1;
public static final String DB_NAME = "tasks_db.sqlite";
public static final String TASKS_TABLE = "tasks";
public static final String TASK_ID = "id";
public static final String TASK_NAME = "name";
public static final String TASK_COMPLETE = "complete";
public static final String TASK_RESPONSIBLE = "responsible";
public static final String TASK_PRIORITY = "priority";
public TasksSQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dropAndCreate(db);
}
protected void dropAndCreate(SQLiteDatabase db) {
db.execSQL("drop table if exists " + TASKS_TABLE + ";");
createTables(db);
}
protected void createTables(SQLiteDatabase db) {
db.execSQL(
"create table " + TASKS_TABLE +" (" +
TASK_ID + " integer primary key autoincrement not null," +
TASK_NAME + " text," +
TASK_COMPLETE + " text," +
TASK_RESPONSIBLE + " text" +
TASK_PRIORITY + " integer" +
");"
);
}
}
-
public class TaskManagerApplication extends Application {
private SQLiteDatabase database;
private ArrayList<Task> currentTasks;
#Override
public void onCreate() {
super.onCreate();
TasksSQLiteOpenHelper helper = new TasksSQLiteOpenHelper(this);
database = helper.getWritableDatabase();
if (null == currentTasks) {
loadTasks();
}
}
private void loadTasks() {
currentTasks = new ArrayList<Task>();
Cursor tasksCursor = database.query(TASKS_TABLE, new String[] {
TASK_ID,
TASK_NAME,
TASK_RESPONSIBLE,
TASK_PRIORITY,
TASK_COMPLETE}, null, null, null, null, String.format("%s,%s", TASK_COMPLETE, TASK_NAME));
tasksCursor.moveToFirst();
Task t;
if (! tasksCursor.isAfterLast()) {
do {
int id = tasksCursor.getInt(0);
String name = tasksCursor.getString(1);
String priority = tasksCursor.getString(2);
String responsible = tasksCursor.getString(3);
String boolValue = tasksCursor.getString(4);
boolean complete = Boolean.parseBoolean(boolValue);
t = new Task(name, priority, responsible);
t.setId(id);
t.setComplete(complete);
currentTasks.add(t);
} while (tasksCursor.moveToNext());
}
tasksCursor.close();
}
}
You have a typo in your CREATE TABLE;
db.execSQL(
"create table " + TASKS_TABLE +" (" +
TASK_ID + " integer primary key autoincrement not null," +
TASK_NAME + " text," +
TASK_COMPLETE + " text," +
TASK_RESPONSIBLE + " text" + // <--- missing a comma
TASK_PRIORITY + " integer" +
");"
);
You have a minor typing error in your code. Corrected version :
db.execSQL(
"create table " + TASKS_TABLE +" (" +
TASK_ID + " integer primary key autoincrement not null," +
TASK_NAME + " text," +
TASK_COMPLETE + " text," +
TASK_RESPONSIBLE + " text," +
TASK_PRIORITY + " integer" +
");"
);
Related
so I'm developing this app which uses SQLite database and displays it in a TableLayout in android studio. Now I want a button to export the data in the TableLayout to an Excel sheet. I'm using this library to do it: https://github.com/androidmads/SQLite2XL
and my database doesn't have a name for it. This is my DBHelper.java:-
package com.kbjg.frissco.eattendence;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import androidx.annotation.Nullable;
import java.util.PrimitiveIterator;
public class DBHelper extends SQLiteOpenHelper {
private static final int VERSION = 2;
//class table
public static final String CLASS_TABLE_NAME = "CLASS_TABLE";
public static final String C_ID = "_CID";
public static final String CLASS_NAME_KEY = "CLASS_NAME";
public static final String SUBJECT_NAME_KEY = "SUBJECT_NAME";
private static final String CREATE_CLASS_TABLE =
"CREATE TABLE " + CLASS_TABLE_NAME + "( " +
C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
CLASS_NAME_KEY + " TEXT NOT NULL, " +
SUBJECT_NAME_KEY + " TEXT NOT NULL, " +
"UNIQUE (" + CLASS_NAME_KEY + "," + SUBJECT_NAME_KEY + ")" +
");";
private static final String DROP_CLASS_TABLE = "DROP TABLE IF EXISTS " + CLASS_TABLE_NAME;
private static final String SELECT_CLASS_TABLE = "SELECT * FROM " + CLASS_TABLE_NAME;
//student table
private static final String STUDENT_TABLE_NAME = "STUDENT_TABLE";
public static final String S_ID = "_SID";
public static final String STUDENT_NAME_KEY = "STUDENT_NAME";
public static final String STUDENT_ROLL_KEY = "ROLL";
private static final String CREATE_STUDENT_TABLE =
"CREATE TABLE " + STUDENT_TABLE_NAME +
"( " +
S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
C_ID + " INTEGER NOT NULL, " +
STUDENT_NAME_KEY + " TEXT NOT NULL, " +
STUDENT_ROLL_KEY + " INTEGER, " +
" FOREIGN KEY ( " + C_ID + ") REFERENCES " + CLASS_TABLE_NAME + "(" + C_ID + ")" +
");";
private static final String DROP_STUDENT_TABLE = "DROP TABLE IF EXISTS " + STUDENT_TABLE_NAME;
private static final String SELECT_STUDENT_TABLE = "SELECT * FROM " + STUDENT_TABLE_NAME;
//STATUS TABLE
private static final String STATUS_TABLE_NAME = "STATUS_TABLE";
public static final String STATUS_ID = "_STATUS_ID";
public static final String DATE_KEY = "STATUS_DATE";
public static final String STATUS_KEY = "STATUS";
private static final String CREATE_STATUS_TABLE =
"CREATE TABLE " + STATUS_TABLE_NAME +
"(" +
STATUS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
S_ID + " INTEGER NOT NULL, " +
C_ID + " INTEGER NOT NULL, " +
DATE_KEY + " DATE NOT NULL, " +
STATUS_KEY + " TEXT NOT NULL, " +
" UNIQUE (" + S_ID + "," + DATE_KEY + ")," +
" FOREIGN KEY (" + S_ID + ") REFERENCES " + STUDENT_TABLE_NAME + "( " + S_ID + ")," +
" FOREIGN KEY (" + C_ID + ") REFERENCES " + CLASS_TABLE_NAME + "( " + C_ID + ")" +
");";
private static final String DROP_STATUS_TABLE = "DROP TABLE IF EXISTS " + STATUS_TABLE_NAME;
private static final String SELECT_STATUS_TABLE = "SELECT * FROM " + STATUS_TABLE_NAME;
public DBHelper(#Nullable Context context) {
super(context, "Attendance.db", null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CLASS_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STATUS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
long addClass(String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.insert(CLASS_TABLE_NAME,null,values);
}
Cursor getClassTable(){
SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery(SELECT_CLASS_TABLE,null);
}
int deleteClass(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.delete(CLASS_TABLE_NAME,C_ID+"=?",new String[]{String.valueOf(cid)});
}
long updateClass(long cid,String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.update(CLASS_TABLE_NAME,values,C_ID+"=?",new String[]{String.valueOf(cid)});
}
long addStudent(long cid,int roll,String name){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(C_ID,cid);
values.put(STUDENT_ROLL_KEY,roll);
values.put(STUDENT_NAME_KEY,name);
return database.insert(STUDENT_TABLE_NAME,null,values);
}
Cursor getStudentTable(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.query(STUDENT_TABLE_NAME,null,C_ID+"=?",new String[]{String.valueOf(cid)},null,null,STUDENT_ROLL_KEY);
}
int deleteStudent(long sid){
SQLiteDatabase database = this.getReadableDatabase();
return database.delete(STUDENT_TABLE_NAME,S_ID+"=?",new String[]{String.valueOf(sid)});
}
long updateStudent(long sid,String name){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STUDENT_NAME_KEY,name);
return database.update(STUDENT_TABLE_NAME,values,S_ID+"=?",new String[]{String.valueOf(sid)});
}
long addStatus(long sid,long cid, String date, String status){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(S_ID,sid);
values.put(C_ID,cid);
values.put(DATE_KEY,date);
values.put(STATUS_KEY,status);
return database.insert(STATUS_TABLE_NAME,null,values);
}
long updateStatus(long sid,String date,String status){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STATUS_KEY,status);
String whereClause = DATE_KEY +"='"+date+"' AND "+S_ID+"="+sid;
return database.update(STATUS_TABLE_NAME,values,whereClause,null);
}
#SuppressLint("Range")
String getStatus(long sid, String date){
String status=null;
SQLiteDatabase database = this.getReadableDatabase();
String whereClause = DATE_KEY +"='"+date+"' AND "+S_ID+"="+sid;
Cursor cursor = database.query(STATUS_TABLE_NAME,null,whereClause,null,null,null,null);
if(cursor.moveToFirst()) {
status = cursor.getString(cursor.getColumnIndex(STATUS_KEY));
}
return status;
}
Cursor getDistinctMonths(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.query(STATUS_TABLE_NAME,new String[]{DATE_KEY},C_ID+"="+cid,null,"substr("+DATE_KEY+",4,7)",null,null);//23.01.2022
}
}
and this is the code I used to generate the Excel sheet:-
csv_maker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/Project Brown/";
File file = new File(directory_path);
if (!file.exists()) {
file.mkdirs();
}
// Export SQLite DB as EXCEL FILE
SQLiteToExcel sqliteToExcel = new SQLiteToExcel(getApplicationContext(), DBHelper.CLASS_NAME_KEY);
sqliteToExcel.exportAllTables("users.xls", new SQLiteToExcel.ExportListener() {
#Override
public void onStart() {
}
#Override
public void onCompleted(String filePath) {
Toast.makeText(SheetActivity.this, "Excel Exported", Toast.LENGTH_SHORT).show();;
}
#Override
public void onError(Exception e) {
}
});
}
});
Actually what happening is when I click the button a directory is created but the is not generated. Kindly help me. Thanks in Advance.
I searched everywhere but i didnt found any info or tutorial or blogs regarding sqlite with MVVM. how do i create viewmodel for my sqlite methods? i have tried various ways to access it, but gives me error
following is my code for sqlite helper class
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
static final String DATABASE_NAME = "kuncorosqlite.db";
public static final String TABLE_SQLite = "sqlite";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ADDRESS = "address";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_MOVIE_TABLE = "CREATE TABLE " + TABLE_SQLite + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY autoincrement, " +
COLUMN_NAME + " TEXT NOT NULL, " +
COLUMN_ADDRESS + " TEXT NOT NULL" +
" )";
db.execSQL(SQL_CREATE_MOVIE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SQLite);
onCreate(db);
}
public ArrayList<HashMap<String, String>> getAllData() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM " + TABLE_SQLite;
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put(COLUMN_ID, cursor.getString(0));
map.put(COLUMN_NAME, cursor.getString(1));
map.put(COLUMN_ADDRESS, cursor.getString(2));
wordList.add(map);
} while (cursor.moveToNext());
}
Log.e("select sqlite ", "" + wordList);
database.close();
return wordList;
}
public void insert(String name, String address) {
SQLiteDatabase database = this.getWritableDatabase();
String queryValues = "INSERT INTO " + TABLE_SQLite + " (name, address) " +
"VALUES ('" + name + "', '" + address + "')";
Log.e("insert sqlite ", "" + queryValues);
database.execSQL(queryValues);
database.close();
}
public void update(int id, String name, String address) {
SQLiteDatabase database = this.getWritableDatabase();
String updateQuery = "UPDATE " + TABLE_SQLite + " SET "
+ COLUMN_NAME + "='" + name + "', "
+ COLUMN_ADDRESS + "='" + address + "'"
+ " WHERE " + COLUMN_ID + "=" + "'" + id + "'";
Log.e("update sqlite ", updateQuery);
database.execSQL(updateQuery);
database.close();
}
public void delete(int id) {
SQLiteDatabase database = this.getWritableDatabase();
String updateQuery = "DELETE FROM " + TABLE_SQLite + " WHERE " + COLUMN_ID + "=" + "'" + id + "'";
Log.e("update sqlite ", updateQuery);
database.execSQL(updateQuery);
database.close();
}
}
viewmodel so far till now what ihave tried :-
public class Viewmodell extends AndroidViewModel {
private DbHelper repository ;
MutableLiveData<ArrayList<HashMap<String, String>>> allNotesLivedata;
public Viewmodell(#NonNull Application application) {
super(application);
repository = new DbHelper(application);
allNotesLivedata = repository.getAllData();
}
void insert(String name,String Address) {
repository.insert(name,Address);
}
void update(int id, String name, String address) {
repository.update(id,name,address);
}
void delete(int id) {
repository.delete(id);
}
public LiveData<ArrayList<HashMap<String, String>>> getAllNotes() {
return allNotesLivedata;
}
}
please dont suggest me to use room because it is not my requirement
The error just means that you are not submitting the compatible values :
In your code , when creating MutableLiveData , you have assigned it
ArrayList<HashMap<String,String>>
but when setting value to the MutableLiveData you are just passing a HashMap . So what you need to do is instead of passing HashMap directly ,you need to create an ArrayList and then to that arrayList you need to pass your HashMap and then set the ArrayList to the MutableLiveData .
You can do it somewhat like this .Below code is for illustration purpose
//Create an arrayList
ArrayList<HashMap> listofMaps = new ArrayList();
//then add all your hashmaps to your list
listofMaps.add(map);
//and then set it to the MutableLiveData
wordList.postValue(listOfMaps);
Or instead of the above process , the second way to solve this issue is , you just need to create the MutableLiveData of the Type : HashMap<String,String>
wordList = new MutableLiveData<HashMap<String,String>>();
I have 2 table Employee and order table, I'm trying to implement those tables into the same databasehelper class, but is gives me several errors, should i create a another databasehelper class, or can i implement these to into one
tables are looks like this
`public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "shopinstyle.db";
private static final String DB_TABLE = "Employee";
private static final String ORDER_TABLE = "Order";
//Employee
//columns
private static final String ID = "ID";
private static final String FNAME = "FNAME";
private static final String LNAME = "LNAME";
private static final String PNUMBER = "PNUMBER";
private static final String EMAIL = "EMAIL";
private static final String NIC = "NIC";
//Order
//columns
private static final String ord_ID = "ord_ID";
private static final String ord_Name = "ord_Name";
private static final String ord_Qty = "ord_Qty";
private static final String ord_Price = "ord_Price";
private static final String ord_Location = "ord_Location";
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FNAME + " TEXT, " +
LNAME + " TEXT, " +
PNUMBER + " TEXT, " +
EMAIL + " TEXT, " +
NIC + " TEXT" + ")";
private static final String CREATE_TABLE_ORDER = "CREATE TABLE " + ORDER_TABLE + " (" +
ord_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ord_Name + " TEXT, " +
ord_Qty + " TEXT, " +
ord_Price + " TEXT, " +
ord_Location + " TEXT " + ")";
public DatabaseHelper(Context context) {
super(context, DB_NAME,ORDER_TABLE, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);
sqLiteDatabase.execSQL(CREATE_TABLE_ORDER);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + ORDER_TABLE);
onCreate(sqLiteDatabase);
}`
there is a error in this line
public DatabaseHelper(Context context) {
super(context, DB_NAME,ORDER_TABLE, null, 1);
}
The 3d argument in the cal of super() inside the constructor of the DatabaseHelper class is factory which you can pass as null and not a table's name:
super(context, DB_NAME,null, 1);
I am trying to update the value of a particular column in my table. I already have a ContentProvder set up. I am receiving an error and I don't know how to fix it. I have searched for help on-line and none of them seem to update based on the unique-id. Here is my code..
#Override
public int update (Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = NewsContract.sURI_MATCHER.match(uri);
SQLiteDatabase db = dictionaryHelper.getWritableDatabase();
int rowsUpdated = 0;
String id = null;
switch (uriType)
{case DictionaryContract.RECENT:
rowsUpdated = db.update(DictionaryContract.DictionaryDataContract.RECENT_TABLE_NAME,
values,
selection,
selectionArgs);
break;
case DictionaryContract.RECENT_ID:
id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = db.update(DictionaryContract.DictionaryDataContract.RECENT_TABLE_NAME,
values,
DictionaryContract.DictionaryDataContract._ID + "=" + id,
null);
} else {
rowsUpdated = db.update(DictionaryContract.DictionaryDataContract.RECENT_TABLE_NAME,
values,
DictionaryContract.DictionaryDataContract._ID + "=" + id
+ " and "
+ selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
And this is how I am calling the update method of the ContentProvider:
private boolean UpdateRecentTable()
{
cursor.moveToLast();
Long id = cursor.getLong(cursor.getColumnIndex(DictionaryContract.DictionaryDataContract._ID));
Log.i("Update", " " + id);
String filter = DictionaryContract.DictionaryDataContract._ID + "=" + id;
ContentValues args = new ContentValues();
args.put(DictionaryContract.DictionaryDataContract.REC_FAVORITED, 1);
dResolver.update(DictionaryContract.CONTENT_URI_RECENT, args, filter, null);
return true;
}
Error:
03-21 04:05:36.823 18326-18673/com.example.clinton.light E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process: com.example.clinton.light, PID: 18326
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalArgumentException: Unknown URIcontent://com.example.clinton.light.provider.dictionary/recents
at com.example.clinton.light.database.DictionaryContentProvider.update(DictionaryContentProvider.java:216)
at android.content.ContentProvider$Transport.update(ContentProvider.java:355)
at android.content.ContentResolver.update(ContentResolver.java:1362)
at com.example.clinton.light.dictionary_main.StoreFavWord.UpdateRecentTable(StoreFavWord.java:72)
at com.example.clinton.light.dictionary_main.StoreFavWord.doInBackground(StoreFavWord.java:41)
at com.example.clinton.light.dictionary_main.StoreFavWord.doInBackground(StoreFavWord.java:18)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
03-21 04:05:37.271 18326-18352/com.example.clinton.light E/Surface: getSlotFromBufferLocked: unknown buffer: 0xe0c79230
DataContract
ublic class DictionaryContract {
public DictionaryContract(){}
public static final int TODAY = 100;
public static final int TODAY_ID = 115;
public static final int FAVORITE = 120;
public static final int FAVORITE_ID = 125;
public static final int RECENT = 130;
public static final int RECENT_ID = 135;
private static final String AUTHORITY = "com.example.clinton.light.provider.dictionary";
public static final String TODAY_BASE_PATH = "today";
public static final String FAVORITE_BASE_PATH = "favorites";
public static final String RECENT_BASE_PATH = "recents";
public static final UriMatcher sURI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURI_MATCHER.addURI(AUTHORITY, TODAY_BASE_PATH, TODAY);
sURI_MATCHER.addURI(AUTHORITY, TODAY_BASE_PATH + "/#", TODAY_ID);
sURI_MATCHER.addURI(AUTHORITY, FAVORITE_BASE_PATH, FAVORITE);
sURI_MATCHER.addURI(AUTHORITY, FAVORITE_BASE_PATH + "/#", FAVORITE_ID);
sURI_MATCHER.addURI(AUTHORITY, RECENT_BASE_PATH, RECENT);
sURI_MATCHER.addURI(AUTHORITY, RECENT_BASE_PATH + "/#", RECENT_ID);
}
public static final Uri CONTENT_URI_TODAY = Uri.parse("content://" + AUTHORITY + "/" + TODAY_BASE_PATH);
public static final Uri CONTENT_URI_FAVORITES = Uri.parse("content://" + AUTHORITY + "/" + FAVORITE_BASE_PATH);
public static final Uri CONTENT_URI_RECENT = Uri.parse("content://" + AUTHORITY + "/" + RECENT_BASE_PATH);
public static abstract class DictionaryDataContract implements BaseColumns
{
public static final String TODAY_TABLE_NAME = "todaytable";
public static final String TODAY_DATE = "worddate";
public static final String WORD = "wordname";
public static final String DEFINITION = "worddefinition";
public static final String SPEECH = "wordspeech";
public static final String ROOT = "wordroot";
public static final String EXAMPLE = "wordexample";
private static final String CREATE_TODAY_TABLE = "create table "+
TODAY_TABLE_NAME +
"(" +
_ID +
" integer primary key autoincrement, " +
TODAY_DATE +
" text not null, " +
WORD +
" text not null, " +
DEFINITION +
" text not null, " +
EXAMPLE +
" text not null, " +
SPEECH +
" text not null, " +
ROOT +
" text not null);";
public static final String FAVORITE_TABLE_NAME = "favoritetable";
public static final String FAV_WORD = "wordname";
public static final String FAV_DEFINITION = "worddefinition";
public static final String FAV_DEFINITION2 = "worddefinition2";
public static final String FAV_SPEECH = "wordspeech";
public static final String FAV_SPEECH2 = "wordspeech2";
public static final String FAV_RELATED = "wordrelated";
public static final String FAV_EXAMPLE = "wordexample";
public static final String RECENT_TABLE_NAME = "recentetable";
public static final String REC_WORD = "wordname";
public static final String REC_DEFINITION = "worddefinition";
public static final String REC_DEFINITION2 = "worddefinition2";
public static final String REC_SPEECH = "wordspeech";
public static final String REC_SPEECH2 = "wordspeech2";
public static final String REC_RELATED = "wordrelated";
public static final String REC_EXAMPLE = "wordexample";
public static final String REC_FAVORITED = "favorited";
private static final String CREATE_FAVORITE_TABLE = "create table "+
FAVORITE_TABLE_NAME +
"(" +
_ID +
" integer primary key autoincrement, " +
FAV_WORD +
" text not null, " +
FAV_DEFINITION +
" text not null, " +
FAV_DEFINITION2 +
" text not null, " +
FAV_EXAMPLE +
" text not null, " +
FAV_SPEECH +
" text not null, " +
FAV_SPEECH2 +
" text not null, " +
FAV_RELATED +
" text not null);";
private static final String CREATE_RECENT_TABLE = "create table "+
RECENT_TABLE_NAME +
"(" +
_ID +
" integer primary key autoincrement, " +
REC_WORD +
" text not null, " +
REC_DEFINITION +
" text not null, " +
REC_DEFINITION2 +
" text not null, " +
REC_EXAMPLE +
" text not null, " +
REC_SPEECH +
" text not null, " +
REC_SPEECH2 +
" text not null, " +
REC_FAVORITED +
" int not null, " +
REC_RELATED +
" text not null);";
public static void onCreate (SQLiteDatabase db) {
db.execSQL(CREATE_TODAY_TABLE);
db.execSQL(CREATE_FAVORITE_TABLE);
db.execSQL(CREATE_RECENT_TABLE);
}
public static void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TODAY_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FAVORITE_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + RECENT_TABLE_NAME);
onCreate(db);
}
}
}
I'm trying to get some information from my database. I'm a beginner in android.
I have a database's create class, called "Database", and a database access class, called "Database_Acesso". They look like that:
Database.java:
package workshopee.ct.ufrn.br.ssmonitor;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database extends SQLiteOpenHelper{
private static final int versao_db = 1;
private static final String nome_db = "ssmonitor_db";
private static final String table1 = "phone";
private static final String id = "_id";
private static final String longitude = "longitude";
private static final String latitude = "latitude";
private static final String forca_torres = "qtdtorres";
private static final String forca_dbm = "dbm";
private static final String mcc = "mcc";
private static final String mnc = "mnc";
private static final String phone_type = "phone_type";
private static final String operadora = "operadora";
private static final String network_type = "networkType";
private static final String cid = "cid";
private static final String lac = "lac";
public Database(Context context) {
super(context, nome_db, null, versao_db);
}
#Override
public void onCreate(SQLiteDatabase db) {
String criarTabela = "CREATE TABLE " + table1 + "("
+ id + " INTEGER PRIMARY KEY AUTOINCREMENT," + longitude + " REAL,"
+ latitude + " REAL," + forca_torres + " INTEGER," + forca_dbm + " REAL," + mcc + " INTEGER,"
+ mnc + " INTEGER," + phone_type + " TEXT," + operadora + " TEXT," + network_type + " INTEGER," + cid + " INTEGER,"
+ lac + " INTEGER )";
db.execSQL(criarTabela);
}
#Override
public void onUpgrade(SQLiteDatabase db, int versao_ant, int versao_nv) {
Log.w(Database.class.getName(),
"Atualizando o banco de dados da versão " + versao_ant + " para "
+ versao_nv + ", isso apagará os dados antigos.");
db.execSQL("DROP TABLE IF EXISTS " + table1 + ";");
onCreate(db);
}
public void clear (SQLiteDatabase db) {
Log.w(Database.class.getName(),
"Apagando informações salvas anteriormente.");
db.execSQL("DROP TABLE IF EXISTS " + table1 + ";");
onCreate(db);
}
}
Database_Acesso.java:
package workshopee.ct.ufrn.br.ssmonitor;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class Database_Acesso {
private SQLiteDatabase db;
public Database_Acesso(Context context) {
Database aux_db = new Database(context);
db = aux_db.getWritableDatabase();
}
public void inserir_phone (Phone ph) {
ContentValues valores = new ContentValues();
valores.put("longitude",ph.getLongitude());
valores.put("latitude", ph.getLatitude());
valores.put("qtdtorres", ph.getTorres());
valores.put("dbm", ph.getDbm());
valores.put("mcc", ph.getMcc());
valores.put("mnc", ph.getMnc());
valores.put("phone_type", ph.getPhoneType());
valores.put("operadora", ph.getOperadora());
valores.put("cid",ph.getCid());
valores.put("lac",ph.getLac());
db.insert("phone", null, valores);
}
public List<Phone> buscar_phone () {
List<Phone> lista = new ArrayList<Phone>();
String[] colunas = new String[]{"_id", "longitude", "latitude", "qtdtorres", "dbm",
"mcc", "mnc", "phone_type", "operadora", "networkType", "cid", "lac"};
Cursor cursor = db.query("phone", colunas, null, null, null, null,"_id ASC");
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
do {
Phone p = new Phone();
p.setId(cursor.getLong(0));
p.setLongitude(cursor.getDouble(1));
p.setLatitude(cursor.getDouble(2));
p.setTorres(cursor.getInt(3));
p.setDbm(cursor.getInt(4));
p.setMcc(cursor.getInt(5));
p.setMnc(cursor.getInt(6));
p.setPhoneType(cursor.getString(7));
p.setOperadora(cursor.getString(8));
p.setNetWorkType(cursor.getString(9));
p.setCid(cursor.getInt(10));
p.setLac(cursor.getInt(11));
lista.add(p);
} while (!cursor.isLast());
return lista;
}
}
Here is the part of my MainActivity that inserts data:
database_acesso.inserir_phone(cell);
Where database_acesso is an instance of Database_acesso and cell is an instance of Phone.
And here is how I'm trying to get information:
TextView list_text_view = (TextView) rootView.findViewById(R.id.list_text_view);
List list = main.database_acesso.buscar_phone();
list_text_view.append(" - " + list.size());
I'm using fragments, so "main" is a instance on MainActivity.
When I try to execute it, I get the following error:
java.lang.OutOfMemoryError: [memory exhausted]
at dalvik.system.NativeStart.main(Native Method)
It is the full stack trace.
Any ideia for solving that?
Thx.
You never call cursor.moveToNext() in your do { ... } while () loop, so you create new Phone objects continuously until you run out of memory.
An arguably better way of writing the loop would instead be:
Cursor cursor = db.query("phone", colunas, null, null, null, null,"_id ASC");
while (cursor.moveToNext())
{
// Do stuff
}
...since moveToNext() returns a boolean indicating if it has reached the end. It also saves the overhead of the call to getCount().