Get ArrayList<String> from SQLite - java

I'm saving my ArrayList in SQLite. Save codes:
public void HistoryADD(ArrayList<String> full, String owner){
int size = full.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
cv.put(FULL, full.get(i));
cv.put(OWNER, owner);
db.insert(TABLE_NAME, null, cv);
}
System.out.println("added:" + full);
db.close();
}catch (Exception e){
System.out.println("Failed to add" + full);
}
}
And IT's working. I want to get this ArrayLists from SQLite. List Code:
public ArrayList<String> History_list(String owner) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> history_list = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " WHERE owner='"+owner+"'",
new String[] {});
cursor.close();
return history_list;
}
But list code not working. What's wrong in this codes?
Thanks.

You need do something like that:
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
//Here you have to add the item in your array list
}
} finally {
cursor.close();
}

public ArrayList<String> History_list(String owner) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> history_list = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " WHERE owner"+"=?",new String[] {owner});
while (cursor.moveToNext()){
int owner_value= cursor.getColumnIndex(owner);
if (owner_value>0) history_list.add(cursor.getString(owner));
}
cursor.close();
return history_list;
}

Related

How to to insert and retrieve data in SQLite?

I have written an app where i have to insert its data into sqlite database and show it on one activity. But my code is showing "No record Found" even if i have inserted it.
I have tried using different options like moving cursor first to the first record and then using loop iterate over the record.
Inserting data into database
private void saveToDB() {
SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ChildMonitoringAppDBHelper.CHILD_NAME, name.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_AGE, age.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_DOB, dob.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_HEIGHT, height.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_WEIGHT, weight.getText().toString());
database.insert(ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null, values);
database.close();
}
Retrieving data from database
public ArrayList<Child> readFromDB()
{
ArrayList<Child> List = new ArrayList<>();
SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getReadableDatabase();
Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), cursor.getString(cursor.getColumnIndex("CHILD_AGE")), cursor.getString(cursor.getColumnIndex("CHILD_DOB")), cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
List.add(child);
cursor.moveToNext();
}
cursor.close();
return List;
}
It should display the record entered but it is making the toast "No Record found".
Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
if (cursor.moveToFirst())
{
do {
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), cursor.getString(cursor.getColumnIndex("CHILD_AGE")), cursor.getString(cursor.getColumnIndex("CHILD_DOB")), cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
List.add(child);
} while (cursor.moveToNext());
}
cursor.close();
return List;
Can you try this code and see it if it works for you?
public ArrayList<Child> readFromDB()
{
List list = new ArrayList<Child>();
Cursor cursor = database.rawQuery("select * from " +
ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
{
do
{
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")),
cursor.getString(cursor.getColumnIndex("CHILD_AGE")),
cursor.getString(cursor.getColumnIndex("CHILD_DOB")),
cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")),
cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
list.add(child);
}
while (cursor.moveToNext());
}
cursor.close();
// return list of inserted values
return list;
}

Returning SQLite query and returning as text

I have a query (getMinScore) which takes the min value from my table, I need to take this and display it in a text field but in it's current state it displays
High Score: android.database.SQLiteCursor#.......
I don't know what this means, how can I get the string value from this?
I am calling the query from my GameView class as in the second block of code. Really appreciate any help!
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "scores.db";
public static final String TABLE_NAME = "scores_table";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, SCORE INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_SCORE, score);
long result = db.insert(TABLE_NAME, null, contentValues);
System.out.println("Data inserted" + score);
if(result == -1) {
return false;
}
else {
return true;
}
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Cursor getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
return res;
}
public boolean updateData(String id, String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_SCORE, score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}
}
GameView.java
String minScore = mydb.getMinScore().toString();
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(40);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
canvas.drawText("High score: " + mydb.getMinScore(), 10, 1280, tp);
A Cursor is an object that gives you access to the results of a database query by iterating over the rows. You can't just print out the cursor, you need to check if there is a next row and then pull the value out from it.
You could change your getMinScore method to return the minScore value instead of returning the cursor:
public int getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if(res.moveToNext()) {
// return the integer from the first column
return res.getInt(0);
} else {
// there were no results
return -1;
}
}
Have a read of the documentation to understand the cursor methods.
You have to get your value from the returning Cursor object. In your case you can use
int score = res.getInt(res.getColumnIndex("SCORE"));
Be sure to check the returning cursor is not NULL by checking cursor count > ZERO.
Change your method
public Cursor getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
return res;
}
To
public int getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if (res.getCount() > 0) {
return res.getInt(res.getColumnIndex("SCORE"));
} else {
return -1; // Some defualt value when no data is retrieved
}
}
you Should always close Cursor to prevent memory leak
so
public int getMinScore() {
int result = -1;
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if (res.moveToFirst()) {
result = res.getInt(0);
}
if (!res.isClosed()){
res.close();
}
return result;
}
}
i think it better to user method open and close instead of calling getWritableDatabase() every time
public void open() {
bdd = dbHelper.getWritableDatabase();
}
public void close() {
bdd.close();
}

Android SQLite Table Creation Error

I have my code to create SQLite database, the code create database but does not create any table. I went through some of the similar errors that others had before, I couldn't find any error. Could anyone help me.
Here is my code
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "swahilComm.db";
public static final String COUNTRY_TABLE = "countries";
public static final String COUNTRY_ID = "id";
public static final String COUNTRY_NAME = "country";
public static final String PROVINCE_TABLE = "province";
public static final String PROVINCE_ID = "id";
public static final String PROVINCE_NAME = "province";
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operation", "Database Created...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROVINCE);
db.execSQL(CREATE_COUNTRY_TABLE);
Log.d("Database Operation", "Tables Created...");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone
db.execSQL("DROP TABLE IF EXISTS " + PROVINCE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + COUNTRY_TABLE);
// Create tables again
onCreate(db);
}
//Delete all data in the table
public void DeleteCountry() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(COUNTRY_TABLE, null, null);
db.close(); // Closing database connection
}
//Delete all data in the Province table
public void DeleteProvice() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(PROVINCE_TABLE, null, null);
db.close(); // Closing database connection
}
//Insert country records
public int insertCountry(Country country) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_ID, country.getId());
values.put(COUNTRY_NAME, country.getCountry());
// Inserting Row
long country_Id = db.insert(COUNTRY_TABLE, null, values);
db.close(); // Closing database connection
return (int) country_Id;
}
//Insert province records
public int insertProvince(Province province) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PROVINCE_ID, province.getId());
values.put(PROVINCE_NAME, province.getProvince());
// Inserting Row
long province_Id = db.insert(PROVINCE_NAME, null, values);
db.close(); // Closing database connection
return (int) province_Id;
}
//Retrieve all records and populate into List<Country>
//This method allow you to retrieve more fields/information into List.
public List<Country> getAllCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<Country> countryList = new ArrayList<Country>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Country country = new Country();
country.setId(cursor.getString(cursor.getColumnIndex(COUNTRY_ID)));
country.setCountry(cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
countryList.add(country);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<Province>
//This method allow you to retrieve more fields/information into List.
public List<Province> getAll() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<Province> provinceList = new ArrayList<Province>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setId(cursor.getString(cursor.getColumnIndex(PROVINCE_ID)));
province.setProvince(cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
provinceList.add(province);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
//Retrieve all records and populate into List<String>
public List<String> getAllStringCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<String> countryList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
countryList.add(i,cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<String>
public List<String> getAll_Simple() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<String> provinceList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
provinceList.add(i,cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
}
This is the the Activity Class
public class Register extends AppCompatActivity {
DBHelper repo = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
countries = getResources().getStringArray(R.array.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, countries);
autoCompleteTextView.setAdapter(adapter);
insertDummyData();
loadProvince_Simple();
}
// This class insert data
private void insertDummyData(){
repo.DeleteProvice();
int i = 1;
String[] provinces = {"Prince Edward Island", "Quebec", "Saskatchewan", "Yukon","Northwest Territories", "Ontario", "Nunavut", "Nova Scotia", "Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland and Labrador"};
for(int j=0; j < provinces.length; j++) {
Province province = new Province();
province.setId(Integer.toString(i));
province.setProvince(provinces[j]);
repo.insertProvince(province);
i++;
}
}
//This is the arrayadapter binding method as you can see
private void loadProvince_Simple(){
ArrayAdapter<String> spinnerAdapter;
DBHelper db = new DBHelper(getApplicationContext());
List<String> provinces = db.getAll_Simple();
spinnerAdapter = new ArrayAdapter<String>(Register.this,
android.R.layout.simple_spinner_item, provinces);
prov_spinner.setAdapter(spinnerAdapter);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
Read my comments below:
// TRY TO REMOVE THE SPACE BETWEEN "TEXT" TO THE "(" IN THE LAST LINE OF BOTH STRINGS
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
// YOU WROTE "INTEGET"
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";

Return count of completed and pending tasks

I am saving tasks in SQlite database. These tasks has a status.
Task table has a status column where 0 is for pending tasks and 1 is for completed tasks.
So for this I have created a query to get completed and pending tasks with respect to the status of task.
Issue is I am not getting proper count of tasks. If I have one task with status as pending i.e 0 then also it returns 1 for both the queries i.e for completed as well as pending.
I have created a task helper and created two different queries to get count of tasks. Later I am adding this count to the MPAndroidchart entry.
EDIT : task table helper:
public class TaskTableHelper extends SQLiteOpenHelper {
private static final String TASK_TABLE = "taskTable";
private static final String KEY_TASK_TITLE = "taskTitle";
private static final String KEY_TASK_ID = "taskId";
private static final String KEY_TASK_ALERT_DATE = "taskAlertDate";
private static final String KEY_TASK_ALERT_TIME = "taskAlertTime";
private static final String KEY_DUE_DATE = "dueDate";
private static final String KEY_DUE_TIME = "dueTime";
private static final String KEY_TASK_LIST ="taskList";
private static final String KEY_TASK_STATUS = "taskStatus";
private static final String KEY_TASK_PRIORITY = "taskPriority";
private static int count=0;
public TaskTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TASK_TABLE);
// createTable(db);
// onCreate(db);
}
public void addTask(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK_TITLE, task.getTitle());
values.put(KEY_TASK_PRIORITY, task.getTaskPriority());
values.put(KEY_TASK_ALERT_DATE, task.getAlertDate());
values.put(KEY_TASK_ALERT_TIME, task.getAlertTime());
values.put(KEY_DUE_TIME, task.getDueTime());
values.put(KEY_DUE_DATE, task.getDueDate());
values.put(KEY_TASK_LIST, task.getList());
values.put(KEY_TASK_STATUS, task.getStatus());
db.insert(TASK_TABLE, null, values);
db.close();
}
public Task getTask(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Task task = new Task();
Cursor cursor = db.query(TASK_TABLE, new String[]{KEY_TASK_ID,
KEY_TASK_TITLE, KEY_TASK_PRIORITY, KEY_TASK_ALERT_DATE,KEY_TASK_ALERT_TIME, KEY_DUE_DATE, KEY_DUE_TIME,
KEY_TASK_LIST,KEY_TASK_STATUS}, KEY_TASK_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
//cursor.moveToFirst();
if( cursor != null && cursor.moveToFirst() ) {
task = new Task(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)),cursor.getString(3),
cursor.getString(4), cursor.getString(5), cursor.getString(6),Integer.parseInt(cursor.getString(7)),
Integer.parseInt(cursor.getString(8)));
}
return task;
}
public ArrayList<Task> getAllTask() {
ArrayList<Task> conList = new ArrayList<Task>();
String selectQuery = "SELECT * FROM " + TASK_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setId(Integer.parseInt(cursor.getString(0)));
task.setTitle(cursor.getString(1));
task.setTaskPriority(Integer.parseInt(cursor.getString(2)));
task.setAlertDate(cursor.getString(3));
task.setAlertTime(cursor.getString(4));
task.setDueDate(cursor.getString(5));
task.setDueTime(cursor.getString(6));
task.setList(Integer.parseInt(cursor.getString(7)));
task.setStatus(Integer.parseInt(cursor.getString(8)));
conList.add(task);
} while (cursor.moveToNext());
}
return conList;
}
public ArrayList<Task> getAllTask(int listId) {
ArrayList<Task> conList = new ArrayList<Task>();
String selectQuery = "SELECT * FROM " + TASK_TABLE + " WHERE " + KEY_TASK_LIST + " == " + listId;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setId(Integer.parseInt(cursor.getString(0)));
task.setTitle(cursor.getString(1));
task.setTaskPriority(Integer.parseInt(cursor.getString(2)));
task.setAlertDate(cursor.getString(3));
task.setAlertTime(cursor.getString(4));
task.setDueDate(cursor.getString(5));
task.setDueTime(cursor.getString(6));
task.setList(Integer.parseInt(cursor.getString(7)));
task.setStatus(Integer.parseInt(cursor.getString(8)));
conList.add(task);
} while (cursor.moveToNext());
}
return conList;
}
public int getCompletedTasks() {
ArrayList<Task> conList = new ArrayList<Task>();
String selectQuery = "SELECT * FROM " + TASK_TABLE + " WHERE " + KEY_TASK_STATUS + " = " + " 1 ";
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCount= db.rawQuery(selectQuery,null);
if (mCount.moveToFirst()) {
do {
Task task = new Task();
count = mCount.getInt(0);
} while (mCount.moveToNext());
}
Log.d("query",selectQuery);
Log.d("count",String.valueOf(count));
mCount.close();
return count;
}
public int getPendingTasks() {
ArrayList<Task> conList = new ArrayList<Task>();
String selectQuery = "SELECT * FROM " + TASK_TABLE + " WHERE " + KEY_TASK_STATUS + " = " + " 0 ";
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCount= db.rawQuery(selectQuery,null);
if (mCount.moveToFirst()) {
do {
Task task = new Task();
count = mCount.getInt(0);
} while (mCount.moveToNext());
}
Log.d("query",selectQuery);
Log.d("count",String.valueOf(count));
mCount.close();
return count;
}
Main activity:
private void setGraph() {
mBarChart = (HorizontalBarChart) findViewById(R.id.chart);
mBarChart.setScaleEnabled(false);
ArrayList<BarDataSet> dataSets = null;
ArrayList<Task> completedTasksList = new ArrayList<>();
ArrayList<Task> pendingTasksList = new ArrayList<>();
ArrayList<Integer> completedTask = new ArrayList<>();
ArrayList<BarEntry> taskEntries = new ArrayList<>();
int pendingTasks = mDb.getPendingTasks();
int completedTasks = mDb.getCompletedTasks();
taskEntries.add(new BarEntry(completedTasks,1));
taskEntries.add(new BarEntry(pendingTasks,0));
mBarChart.animateXY(2000, 2000);
ArrayList<String> xAxis = new ArrayList<>();
xAxis.add("Pending");
xAxis.add("Completed");
BarDataSet completed = new BarDataSet(taskEntries, "Entries");
}
What's going wrong here?
Thank you.
count = mCount.getInt(0);
is wrong because you are reading the first field in your raw witch is probably the id field.
use this mCount.getCount();
I suggest using a compiled statement which is a faster way to count:
public long getCompletedTasks() {
SQLiteDatabase db = getWritableDatabase();
long count = -1;
try {
SQLiteStatement statement = db.compileStatement(
"select count(*) from table_name where status = 1");
count = statement.simpleQueryForLong();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (statement != null) {
statement.close();
}
}
return count;
}
Also, if you know you use this method a lot, you can cache the statement object and reuse it.

Android sqlite insert data SQLiteException

#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
// providers data
// db.execSQL("insert into "
// + TABLE_PROVIDERS
// + " (_id, provider_id, parent_id, title, image, sh_n, enable, visible, image_bg, type, is_group, hide_in_search, limit_min, limit_max, off_on_line, invoice_search) "
// + "VALUES (1,600,101,'Источники оплаты','',1,1,0,'','',1,1,0,0,0,0)");
ContentValues cv = new ContentValues();
cv.put("_id", 1);
cv.put("provider_id", 600);
cv.put("parent_id", 101);
cv.put("title", "Bla");
cv.put("image", "bla");
cv.put("sh_n", 1);
cv.put("enable", 1);
cv.put("visible", 1);
cv.put("image_bg", "");
cv.put("type", "");
cv.put("is_group", 1);
cv.put("hide_in_search", 1);
cv.put("limit_min", 10);
cv.put("limit_max", 10000);
cv.put("off_on_line", 1);
cv.put("invoice_search", 1);
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
}
Now I'm doing as was suggested, inserting row by row:
import java.util.*;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
public class ProviderDataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
public ProviderDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public List<Provider> getProvidersByParentId(long parentId) {
List<Provider> providersList = new ArrayList<Provider>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_PROVIDERS, new String[] { "provider_id", "title", "image" }, " parent_id=" + parentId,
null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Provider provider = cursorToProvider(cursor);
providersList.add(provider);
cursor.moveToNext();
}
cursor.close();
System.out.println("getProvidersByParentId");
return providersList;
}
private Provider cursorToProvider(Cursor cursor) {
Provider provider = new Provider();
provider.setId(cursor.getInt(1));
provider.setTitle(cursor.getString(3));
provider.setImg(cursor.getString(4));
return provider;
}
}
It doesn't work. It seems like the row wasn`t inserted and the array returnd by getProvidersByParentId method is empty. Parent_id as argument is 101.
Your insert statement is wrong. In SQLite, you cant insert multiple records by separating them with comma, in fact you need to prepare separate insert commands for that. But if your SQLite version is 3.7.11 then its possible.
Read this.
You can do it with a for loop like this
// add a button click event like
String[] arr1 = new String[n];
String[] arr2 = new String[n];
String[] arr3 = new String[n];
addButton.setOnClickListener
(
new View.OnClickListener()
{
#Override public void onClick(View v) {
for(int i=1;1<4;i++){
try
{
// ask the database manager to add a row given the two strings
//db object of database manager class
db.addValues
(
arr1[i] ,
arr2[i] ,
arr3[i] ,
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
);
// function of insertion
public void addValues(String Col1, String Col2,
String col3)
{
ContentValues values = new ContentValues();
values.put(Columns1, Col1);
values.put(Columns2, Col2);
values.put(Columns3, Col3);
try{
db.insert(Course_Info_Table, null, values);
}
catch(Exception e)
{
}
}
use ContentValues to insert data into table like this.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_id", 1);
cv.put("provider_id", 600);
cv.put("parent_id", 0);
cv.put("title", "Источники оплаты");
cv.put("image", "");
cv.put("sh_n", 1);
cv.put("enable", 1);
cv.put("visible", 0);
cv.put("image_bg", "");
cv.put("type", "");
cv.put("is_group", 1);
cv.put("hide_in_search", 1);
cv.put("limit_min", 0);
cv.put("limit_max", 0);
cv.put("off_on_line", 0);
cv.put("invoice_search", 0);
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
db.close();
for multiple records call this methods multiple times.
public void insertMydata(int _id, int provider_id, int parent_id /*....add more parameters as you required */){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_id", _id);
cv.put("provider_id", provider_id);
cv.put("parent_id", parent_id);
/*
......
.....
put more code here for other columns
......
*/
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
db.close();
}

Categories

Resources