Display sqlite data on listview - android

I have to show saved sqlite data on a listview. But only one column's data is enough to show.Here is my codes. I want to get "tarih" column's data.
public class TarihDataSource {
private SQLiteDatabase database;
private DatabaseOlusturma dbOlustur;
private String []allColumns = {"tarih","gunluknotu","resim"};
public TarihDataSource(Context context) {
dbOlustur = new DatabaseOlusturma(context);
}
public void open() throws SQLException {
database = dbOlustur.getReadableDatabase();
}
public void close() {
dbOlustur.close();
}
public List<TarihListHelper> getAllTarih() {
List<TarihListHelper> tarihlistesi = new ArrayList<TarihListHelper>();
Cursor cursor = database.query("gunluker", allColumns, null, null,
null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
TarihListHelper comment = cursorToComment(cursor);
tarihlistesi.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return tarihlistesi;
}
private TarihListHelper cursorToComment(Cursor cursor) {
TarihListHelper comment = new TarihListHelper();
comment.setTarih(cursor.getString(1));
return comment;
}
}
What is the wrong in this codes?

This code should help you.
public List<TarihListHelper> getAllTarih()
{
List<TarihListHelper> tarihlistesi = new ArrayList<TarihListHelper>();
Cursor cursor = database.query(DB_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext())
{
TarihListHelper tarihlistesi= cursorToComment(cursor);
tarihlistesi.add(comment);
}
cursor.close();
return tarihlistesi;
}
Where columns is the String[] which contains the names of all the columns in your database table.
This way you will get all the columns, then you can select from which column do want to read data.
Hope this helps.

You simply need an Adapter to your list. In your case i think that a SimpleCursorAdapter is the best.
Check this official page and this example.

public class TarihDataSource {
private SQLiteDatabase database;
private DatabaseOlusturma dbOlustur;
private final Context context;
private String []allColumns = {"tarih","gunluknotu","resim"};
public TarihDataSource(Context _context) {
context = _context;
dbOlustur = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
public void open() throws SQLException {
database = dbOlustur.getReadableDatabase();
}
public void close() {
dbOlustur.close();
}
public List<TarihListHelper> getAllTarih() {
List<TarihListHelper> tarihlistesi = new ArrayList<TarihListHelper>();
Cursor cursor = database.query("gunluker", allColumns, null, null,
null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
TarihListHelper comment = cursorToComment(cursor);
tarihlistesi.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return tarihlistesi;
}
private TarihListHelper cursorToComment(Cursor cursor) {
TarihListHelper comment = new TarihListHelper();
comment.setTarih(cursor.getString(1));
return comment;
}
}
Try this.

Related

How to retrieve whole Row of data in Sqlite

I want to retrieve a whole row at a time in sqlite database. All of them are strings. I wrote a method.
If anyone could check the error of this.
Thanks
public ArrayList<Integer> queueAll_row(){
String[] columns = new String[]{Key_row_ID,Key_Customer_name,Key_customer_nic,Key_roof,Key_floor,Key_walls,Key_toilets,Key_No_Rooms,Key_electricity,Key_drinkingWater,Key_status,Key_ownership
,Key_hvBankAcc,Key_loansOfOtherBnks,Key_current_No_Emp,Key_new_Emp,Key_income_source1,Key_income_source2,Key_income_source3};
Cursor cursor = ourDb.query(DB_Table, columns,
null, null, null, null, null);
ArrayList<Integer> values = new ArrayList<Integer>();
cursor.moveToFirst();
while (cursor.moveToNext()) {
values.add(cursor.getInt(0));
}
return values;
}
Please try this, I hope its help you.
public ArrayList<ProjectModel> getprojectName() {
ArrayList<ProjectModel> values = new ArrayList<ProjectModel>();
String query = "SELECT * from project";
cursor = sqLiteDatabase.rawQuery(query, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
values.add(new ProjectModel(cursor.getString(cursor
.getColumnIndex("project_id")), cursor
.getString(cursor.getColumnIndex("project_name"))));
} while (cursor.moveToNext());
}
}
return values;
}
model class
public class ProjectModel {
private String project_id;
private String project_name;
public ProjectModel(String project_id, String project_name) {
super();
this.project_id = project_id;
this.project_name = project_name;
}
public String getProject_id() {
return project_id;
}
public String getProject_name() {
return project_name;
}
You may run a raw query also to get whole row from a table in database..
you may try this code.. hope it will work for you.
public ArrayList<Integer> queueAll_row() {
String query = "select * from " + DB_Table;
Cursor cursor = ourDb.rawQuery(query, null);
ArrayList<Integer> values = new ArrayList<Integer>();
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (cursor.moveToNext()) {
values.add(cursor.getInt(0));
}
}
return values;
}
Steps:-
1.To store all value from single row you have to use model class
2.add following code
public ArrayList queueAllRow(){
String query = "select * from "+DB_Table;
Cursor cursor = ourDb.rawQuery(query, null);
ArrayList<ModelClass> values = new ArrayList<ModelClass>();
if(cursor.moveToFirst()){
do {
ModelClass ob1=new ModelClass();
ob1.setvalue(cursor.getString(cursor.getColumnIndex("COL_NAME")));
//set the values to other data members, same like above
values.add(ob1);
} while (cursor.moveToNext());
}
return values;
}

To add the content in to the database

how to solved that error how to get the array list Result sets of queries are returned in Cursor objects. There are some common methods that you will use with cursors
public class DBAdapter {
Context c;
CluecatalogOpenHelper helper;
SQLiteDatabase db;
int flag=0;
public DBAdapter(Context ctx) {
super();
this.c = ctx;
helper=new CluecatalogOpenHelper(ctx);
}
public void openDB(){
db=helper.getWritableDatabase();
}
public void closeDB(){
db.close();
}
public void addRow(String name, byte[] data1) {
openDB();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("object",data1);
db.insert("topsearch", null, values);
closeDB();
}
public void deleteRow(String name)
{
try {
db.execSQL("delete from topsearch where name = (?)",new String[]{""+name});
} catch (SQLException e) {
e.printStackTrace();
}
}
public Cursor showData(){
try{
Cursor c = db.query("topsearch", new String[]{"name","object"}, null, null,null, null,null);
return c;
}catch(Exception e) {
e.printStackTrace();
return null;
}}}
how to solved that error
I'm not sure exactly what you're asking, but if you're asking how do you pull out the results out of a Cursor object and into a List you would do it like this:
List list = new ArrayList();
Cursor c = db.query("topsearch", new String[]{"name","object"}, null, null,null, null,null);
while(c.moveToNext())
{
//populate your return object from the cursor here
//i'm just making this part up
Obj obj = new Obj();
obj.setName(c.getString(0)); //0 being the column index
list.add(obj);
}
return list;

how do i fetch a record from SQL

sorry im kind of a beginner,
I have a simple app that stores data on one page and fetches it on another. i keep getting an error when i try and fetch the data, stating that no such column could be found. please help
this is my code from where i enter the data,
EnterDetails.java
#Override
public void onClick(View arg0) {
EditText holdersala = (EditText) findViewById(R.id.rawsalary);
EditText wantspercentage = (EditText) findViewById(R.id.wantspercent);
EditText needspercentage = (EditText) findViewById(R.id.needspercent);
String holdersalary = holdersala.getText().toString();
final int salary = Integer.parseInt(holdersalary);
String holderwantsp = wantspercentage.getText().toString();
final int wantsp = Integer.parseInt(holderwantsp);
String holderneedsp = needspercentage.getText().toString();
final int needsp = Integer.parseInt(holderneedsp);
if(wantsp + needsp <= 100){
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
databaseAdapter.createRecordS(salary);
databaseAdapter.createRecordW(wantsp);
databaseAdapter.createRecordN(needsp);
databaseAdapter.close();
startActivity(new Intent(EnterDetails.this, Summary.class));
} else {
}
Toast toast = Toast.makeText(EnterDetails.this, "incorrect data", 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
code from where i fetch the data
TextView bn = (TextView) findViewById(R.id.budget_need);
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
bn.setText(databaseAdapter.fetchRecordS(1));
databaseAdapter.close();
and code from my databaseAdapter.java
public class DatabaseAdapter {
private Context context;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
this.context = context;
}
public DatabaseAdapter open() throws SQLException {
dbHelper = new DatabaseOpenHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createRecordS(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("salafig", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordN(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("needsper", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordW(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("wantsper", interger);
return database.insert("maindata", null, contentValue);
}
public int fetchRecordS(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "salafig"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}
public int fetchRecordW(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "wantsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}public int fetchRecordN(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "needsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
hope it makes sense thanks if advance for any help.
Look at HEREto check the correct syntax of the SQLiteDatabase query method.
The forth parameter of the method is the selection condition, it s supposed to be something like:
"salafig = "+ rowId"
instead of this :
"salafig"+ rowId"

Android: java.lang.IllegalStateException and SQLiteDatabase.queryWithFactory()

I published my app 2 months ago and sometimes, I am geting some reports about bugs.
Here is the error report:
java.lang.RuntimeException: Unable to start activity ComponentInfo{mdpi.android/mdpi.android.User_Registration_Country_Choosing}: java.lang.IllegalStateException: database not open
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: database not open
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1232)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1191)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1273)
at mdpi.android.database.LocalDatabase.getAllCountrys(LocalDatabase.java:310)
at mdpi.android.User_Registration_Country_Choosing.onCreate(User_Registration_Country_Choosing.java:81)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
... 11 more
The strange thing is that when I am testing the app, I am newer getting this error...
Do you have an ideo what can be the problem???
Thank you.
Here is th code of User_Registration_country_Choosing
public class User_Registration_Country_Choosing extends Activity implements TextWatcher {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choosecountry);
// Disable the Strict mode
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Country = (EditText) findViewById(R.id.CountryName);
Country.requestFocus();
Bundle b = this.getIntent().getExtras();
user = new User_Database(0, null, null, null, null, null, null, null, null, null);
registrationConfirmPassword = b.getString("registrationConfirmPassword");
user = b.getParcelable("user");
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
try{
inputManager.showSoftInput(Country, InputMethodManager.SHOW_IMPLICIT);
}
catch (Exception e)
{}
Country.addTextChangedListener(this);
String ChooseCountry = "'%%'";
List<Country> values = LocalDatabase.getAllCountrys(ChooseCountry);
ListView lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter<Country>(
this,R.layout.country_list_black_text,R.id.list_content, values));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
TextView textView = (TextView) view.findViewById(R.id.list_content);
final String choosencountry = textView.getText().toString();
Toast.makeText(mContext, "You choosed: "+choosencountry, Toast.LENGTH_LONG).show();
user.setcountry(choosencountry);
KeyboardDown();
new Handler().postDelayed(new Runnable() {
public void run() {
Intent myIntent = new Intent(view.getContext(), UserRegistration.class);
Bundle b = new Bundle();
b.putParcelable("user", user);
b.putString("registrationConfirmPassword", registrationConfirmPassword);
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
KeyboardDown();
finish();
}
}, 3500);
}
});
}
public void afterTextChanged(Editable arg0) {}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { }
public void onTextChanged(CharSequence s, int start, int before, int count) {
EditText Country;
Country = (EditText) findViewById(R.id.CountryName);
String country = Country.getText().toString();
String ChooseCountry = "'"+country+"%'";
List<Country> values = LocalDatabase.getAllCountrys(ChooseCountry);
ListView lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter<Country>(
this,R.layout.country_list_black_text,R.id.list_content, values));
}
public void KeyboardDown(){
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
try{
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
catch (Exception e)
{}
}
}
And here is the code of LocalDatabase.java
package mdpi.android.database;
public class LocalDatabase {
public LocalDatabase(Context context){
databasetables = new DatabaseTables(context, NAME_Database, null, VERSION_BDD);
}
public void open(){
Database = databasetables.getWritableDatabase();
}
public void close(){
Database.close();
}
public SQLiteDatabase getBDD(){
return Database;
}
public static long insertUser(User_Database user){
ContentValues values = new ContentValues();
values.put("ID", user.getuserId());
values.put("email", user.getemail());
values.put("password", user.getpassword());
values.put("first_name", user.getfirstname());
values.put("last_name", user.getlastname());
values.put("street", user.getstreet());
values.put("postal_code", user.getpostalcode());
values.put("city", user.getcity());
values.put("country", user.getcountry());
values.put("alert_frequency", user.getalertfrequency());
return Database.insert("user", null, values);
}
public static long insertSubmission(Submissions_Database submission){
ContentValues values = new ContentValues();
values.put("ID", submission.getID());
values.put("hash", submission.getHashKey());
values.put("journalId", submission.getJournalID());
values.put("title", submission.getTitle());
values.put("subtitle", submission.getSubTitle());
values.put("date", submission.getDate());
values.put("status", submission.getStatus());
values.put("journal_title", submission.getJournalTitle());
return Database.insert("submission", null, values);
}
public static long insertSubmissionLog(SubmissionLog_Database submissionLog){
ContentValues values = new ContentValues();
values.put("title", submissionLog.getTitle());
values.put("hash", submissionLog.getHashKey());
values.put("date", submissionLog.getDate());
return Database.insert("submissionlog", null, values);
}
public static long insertSubscriptionsFromTheServer(Subscription_Database subscriptions){
ContentValues values = new ContentValues();
values.put("journalId", subscriptions.getJournalID());
return Database.insert("subscriptions", null, values);
}
public static long insertSubscriptionsFromtTheJournalList(int journalId){
ContentValues values = new ContentValues();
values.put("journalId", journalId);
return Database.insert("subscriptions", null, values);
}
public static long insertCountry(Country country){
ContentValues values = new ContentValues();
values.put("id", country.getid());
values.put("name", country.toString());
return Database.insert("country", null, values);
}
public static long insertJournal(Journal_Database journals){
ContentValues values = new ContentValues();
values.put("journalId", journals.getJournalID());
values.put("nameFull", journals.getNameFull());
values.put("nameShort", journals.getNameShort());
values.put("nameSystem", journals.getNameSystem());
values.put("about", journals.getAbout());
values.put("nameIso4", journals.getNameIso4());
values.put("namePubmed", journals.getNamePubmed());
values.put("namePubmedShort", journals.getNamePubmedShort());
values.put("ISSNElectronic", journals.getISSNElectronic());
values.put("coden", journals.getCoden());
values.put("APCChf", journals.getAPCChf());
values.put("APCCny", journals.getAPCCny());
values.put("APCEngChf", journals.getAPCEngChf());
values.put("APCEngCny", journals.getAPCEngCny());
values.put("APCFormatChf", journals.getAPCFormatChf());
values.put("SCITracked", journals.getSCITracked());
values.put("impactFactor", journals.getImpactFactor());
values.put("ImpactFactor5years", journals.getImpactFactor5years());
values.put("ImpactFactorYear", journals.getImpactFactorYear());
values.put("EstablishedYear", journals.getEstablishedYear());
values.put("ShortDescription", journals.getShortDescription());
values.put("AcceptedPapers", journals.getAcceptedPapers());
values.put("StyleHeaderLight", journals.getStyleHeaderLight());
values.put("StyleHeaderDark", journals.getStyleHeaderLight());
values.put("CurrentIssue", journals.getCurrentIssue());
values.put("FurthcomingIssue", journals.getForthcomingIssue());
values.put("ContactEmail", journals.getContactEmail());
values.put("ContactID", journals.getContactID());
values.put("Pubfrequency", journals.getPubfrequency());
values.put("PublicFlag", journals.getPublicFlag());
values.put("ReviewRequestTime", journals.getReviewRequestTime());
values.put("DOIAbbreviation", journals.getDOIAbbreviation());
return Database.insert("journals", null, values);
}
public static void delateSubscribedJournal(int journalId){
Database.execSQL("DELETE FROM subscriptions WHERE journalId ="+journalId);
}
public static void deleteSubmissionLog(){
Database.execSQL("DELETE FROM submissionlog");
}
public static void deleteSubscriptions(){
Database.execSQL("DELETE FROM subscriptions");
}
public static void deleteUser(){
Database.execSQL("DELETE FROM user");
}
public static void deleteUserSubmissions(){
Database.execSQL("DELETE FROM submission");
}
public static void deleteHistory(){
Database.execSQL("DELETE FROM history");
}
public static void deleteJournals()
{
Database.execSQL("DELETE FROM journals");
}
public static void deleteEditorialBoard()
{
Database.execSQL("DELETE FROM editorialboard");
}
public static void deleteHighlights_News()
{
Database.execSQL("DELETE FROM highlights_news");
}
public static void deleteHighlights_NewSpecialIssues()
{
Database.execSQL("DELETE FROM highlights_new_special_issues");
}
public static List<Country> getAllCountrys(String ChooseCountry) {
List<Country> countrys = new ArrayList<Country>();
Cursor cursor = Database.query("country",
CountryColName,"name like " + ChooseCountry, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Country country = cursorToCountry(cursor);
countrys.add(country);
cursor.moveToNext();
}
cursor.close();
return countrys;
}
public static String getChoosenCountryName(String countryIdString) {
if (countryIdString!=null)
{
int countryIdInt=Integer.decode(countryIdString);
Cursor cursor = Database.query("country",
CountryColName,"id like " + countryIdInt, null, null, null, null);
cursor.moveToFirst();
String countryName = null;
while (!cursor.isAfterLast()) {
countryName = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return countryName;
}
return "";
}
public static int getChoosenCountryId(String countryName) {
Cursor cursor = Database.query("country",
CountryColId,"name like "+"'"+countryName+"'", null, null, null, null);
cursor.moveToFirst();
int countryId = 0;
while (!cursor.isAfterLast()) {
countryId = cursor.getInt(0);
cursor.moveToNext();
}
cursor.close();
return countryId;
}
private static Country cursorToCountry(Cursor cursor) {
Country country = new Country(0,null);
country.setname(cursor.getString(0));
return country;
}
public static long updateJournal(int journalId, String updateRow,String value){
ContentValues values = new ContentValues();
values.put(updateRow,value);
return Database.update("journals", values, "journalId="+ journalId, null);
}
public static int CheckCountryPresence() {
final SQLiteStatement stmt =
Database.compileStatement("SELECT COUNT(*) FROM COUNTRY");
return (int) stmt.simpleQueryForLong();
}
public static int CheckOfficesPresence() {
final SQLiteStatement stmt =
Database.compileStatement("SELECT COUNT(*) FROM OFFICES");
return (int) stmt.simpleQueryForLong();
}
private static User_Database cursorToUser(Cursor cursor) {
User_Database user = new User_Database(0, null, null, null, null, null, null, null, null, null);
user.setuserId(cursor.getInt(0));
user.setemail(cursor.getString(1));
user.setpassword(cursor.getString(2));
user.setfirstname(cursor.getString(3));
user.setlastname(cursor.getString(4));
user.setstreet(cursor.getString(5));
user.setpostalcode(cursor.getString(6));
user.setcity(cursor.getString(7));
user.setcountry(cursor.getString(8));
user.setalertfrequency(cursor.getString(9));
return user;
}
public static User_Database getUserInformations() {
User_Database user = new User_Database(0, null, null, null, null, null, null, null, null, null);
Cursor cursor = Database.query("user",
UserCol_All,"", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
user = cursorToUser(cursor);
cursor.moveToNext();
}
cursor.close();
return user;
}
public static ArrayList<Submissions_Database> getAllSubmissions() {
ArrayList<Submissions_Database> submissions = new ArrayList<Submissions_Database>();
Cursor cursor = Database.query("submission",
SubmissionCOL_All,"", null, null, null, "date DESC");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Submissions_Database submission = cursorToSubmissions(cursor);
submissions.add(submission);
cursor.moveToNext();
}
cursor.close();
return submissions;
}
public static Submissions_Database getSelectedSubmission(String hashKey) {
Cursor cursor = Database.query("submission",
SubmissionCOL_All,"hash like "+"'"+hashKey+"'", null, null, null, null);
Submissions_Database submission = new Submissions_Database(0, null, 0, null, null, null, 0, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
submission = cursorToSubmissions(cursor);
cursor.moveToNext();
}
cursor.close();
return submission;
}
public static ArrayList<Submissions_Database> getAllSearchedSubmissions(String submissionName) {
ArrayList<Submissions_Database> submissions = new ArrayList<Submissions_Database>();
Cursor cursor = Database.query("submission",
SubmissionCOL_All,
"title like '%"+submissionName+"%'"
+" OR subtitle like '%"+submissionName+"%'"
+" OR id like '%"+submissionName+"%'",
null, null, null, "date DESC", "10");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Submissions_Database submission = cursorToSubmissions(cursor);
submissions.add(submission);
cursor.moveToNext();
}
cursor.close();
return submissions;
}
private static Submissions_Database cursorToSubmissions(Cursor cursor) {
Submissions_Database submission = new Submissions_Database(0, null, 0, null, null, null, 0, null);
submission.setJournalTitle(cursor.getString(0));
String SubmissionJournalDate = "Unknown";
SubmissionJournalDate = cursor.getString(1);
if (SubmissionJournalDate ==null)
{
submission.setDate("Unknown");
}
else
{
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try
{
Date date = fmt.parse(SubmissionJournalDate);
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
submission.setDate(fmtOut.format(date));
}
catch(ParseException pe)
{
submission.setDate("Unknown");
}
}
submission.setTitle(cursor.getString(2));
submission.setID(cursor.getInt(3));
submission.setHashKey(cursor.getString(4));
submission.setStatus(cursor.getInt(5));
return submission;
}
public static int getSubmissionsSize() {
try{
final SQLiteStatement stmt = Database
.compileStatement("SELECT MAX(rowid) FROM submission");
return (int) stmt.simpleQueryForLong();
}
catch (Exception e) {
return 0;
}
}
public static ArrayList<Journal_Database> getAllPublicJournalNames() {
ArrayList<Journal_Database> journals = new ArrayList<Journal_Database>();
Cursor cursor = Database.query("journals",
JournalsCOL_All,"publicFlag like 1", null, null, null, "nameSystem");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Journal_Database journalObject = cursorToJournals(cursor);
journals.add(journalObject);
cursor.moveToNext();
}
cursor.close();
return journals;
}
public static ArrayList<Journal_Database> getAllSearchedJournals(String journalName, String limit ) {
ArrayList<Journal_Database> journals = new ArrayList<Journal_Database>();
Cursor cursor = Database.query("journals",
JournalsCOL_All,
"nameSystem like '%"+journalName+"%' AND PublicFlag = 1"
+" OR nameFull like '%"+journalName+"%' AND PublicFlag = 1"
+" OR nameShort like '%"+journalName+"%' AND PublicFlag = 1"
, null, null, null, "nameSystem", limit );
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Journal_Database journalObject = cursorToJournals(cursor);
journals.add(journalObject);
cursor.moveToNext();
}
cursor.close();
return journals;
}
private static Subscription_Database cursorToSubscriptions(Cursor cursor) {
Subscription_Database subscription = new Subscription_Database(0);
subscription.setJournalID(cursor.getInt(0));
return subscription;
}
public static boolean JournalPresence() {
final SQLiteStatement stmt =
Database.compileStatement("SELECT COUNT(*) FROM JOURNALS");
if (stmt.simpleQueryForLong()==0){
return false;
}
else{
return true;
}
}
public static String getJournalNameShort(int journalId){
Cursor cursor2 = Database.query("journals",
JournalCOL_NameShort,"journalId like "+"'"+journalId+"'", null, null, null, null);
cursor2.moveToFirst();
String Title = "";
while (!cursor2.isAfterLast()) {
Title = cursor2.getString(0);
cursor2.moveToNext();
}
cursor2.close();
return Title;
}
public static String getJournalEditorialBoard(int journalId){
Cursor cursor2 = Database.query("editorialboard",
EditorialBoard_All,"journalId like "+"'"+journalId+"'", null, null, null, null);
cursor2.moveToFirst();
String EditorialBoard = "";
while (!cursor2.isAfterLast()) {
EditorialBoard = cursor2.getString(2)+cursor2.getString(0)+cursor2.getString(1);
cursor2.moveToNext();
}
cursor2.close();
return EditorialBoard;
}
public static ArrayList<Subscription_Database> getAllSubscribedJournals() {
ArrayList<Subscription_Database> journals = new ArrayList<Subscription_Database>();
Cursor cursor = Database.query("subscriptions",
SubscriptionCOL_JournalId,"", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Subscription_Database subscription = cursorToSubscriptions(cursor);
journals.add(subscription);
cursor.moveToNext();
}
cursor.close();
return journals;
}
public static int getHistoryLastSuccessfullUpdate(){
Cursor cursor2 = Database.query("history",
HistoryCOL_LastSuccessfullUpdate,"", null, null, null, null);
cursor2.moveToFirst();
int lastSuccessfullUpdate = 0;
lastSuccessfullUpdate = cursor2.getInt(0);
cursor2.close();
return lastSuccessfullUpdate;
}
public static int CheckMDPIPresence()
{
final SQLiteStatement stmt =
Database.compileStatement("SELECT COUNT(*) FROM mdpi");
return (int) stmt.simpleQueryForLong();
}
public static String getJournalAimsAndScope(String journalNameShort)
{
Cursor cursor2 = Database.query("journals",
JournalCOL_Abaut,"nameSystem ="+"'"+journalNameShort+"'", null, null, null, null);
cursor2.moveToFirst();
String aimsAndScope = null;
aimsAndScope = cursor2.getString(0);
cursor2.close();
return aimsAndScope;
}
public static int getJournalIdFromNameShort(String journalNameShort)
{
Cursor cursor2 = Database.query("journals",
JournalCOL_Id,"nameShort ="+"'"+journalNameShort+"'", null, null, null, null);
cursor2.moveToFirst();
int journalId = 0;
while (!cursor2.isAfterLast()) {
journalId = cursor2.getInt(0);
cursor2.moveToNext();
}
cursor2.close();
return journalId;
}
public static String getJournalNameShortFromNameSystem(String journalNameSystem)
{
Cursor cursor2 = Database.query("journals",
JournalCOL_NameShort,"nameSystem ="+"'"+journalNameSystem+"'", null, null, null, null);
cursor2.moveToFirst();
String journalNameShort = null;
while (!cursor2.isAfterLast()) {
journalNameShort = cursor2.getString(0);
cursor2.moveToNext();
}
cursor2.close();
return journalNameShort;
}
public static int getJournalIdFromNameSystem(String journalNameShort)
{
Cursor cursor2 = Database.query("journals",
JournalCOL_Id,"nameSystem ="+"'"+journalNameShort+"'", null, null, null, null);
cursor2.moveToFirst();
int journalId = 0;
while (!cursor2.isAfterLast()) {
journalId = cursor2.getInt(0);
cursor2.moveToNext();
}
cursor2.close();
return journalId;
}
public static boolean editorialBoardExistsAllready(int journalId) {
final SQLiteStatement stmt =
Database.compileStatement("SELECT COUNT(*) FROM editorialboard WHERE journalId ="+journalId);
long count= stmt.simpleQueryForLong();
if (count==1)
return true;
else
return false;
}
public static String getEditorialboardValue(int journalId, String row) {
String[] editorialBoardValue = {row};
Cursor cursor = Database.query("editorialboard",
editorialBoardValue, "journalId ="+journalId, null, null, null,null);
cursor.moveToFirst();
String result = "";
result = cursor.getString(0);
cursor.close();
return result;
}
public static String getJournalISSNfromJournalId(int journalId){
Cursor cursor2 = Database.query("journals",
JournalCOL_ISSNelectronic,"journalId like "+journalId, null, null, null, null);
cursor2.moveToFirst();
String ISSNElectronic = null;
while (!cursor2.isAfterLast()) {
ISSNElectronic = cursor2.getString(0);
cursor2.moveToNext();
}
cursor2.close();
return ISSNElectronic;
}
public static String getMDPIAbaut() {
Cursor cursor = Database.query("mdpi",
MDPIColAbaut,"", null, null, null, null);
cursor.moveToFirst();
String abaut = null;
while (!cursor.isAfterLast()) {
abaut = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return abaut;
}
public static String getMDPIOpenAccess() {
Cursor cursor = Database.query("mdpi",
MDPIColOpenAccess,"", null, null, null, null);
cursor.moveToFirst();
String openAccess = null;
while (!cursor.isAfterLast()) {
openAccess = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return openAccess;
}
public static ArrayList<String> getOfficesHTML() {
Cursor cursor = Database.query("offices",
OfficesColHTML,"", null, null, null, null);
cursor.moveToFirst();
ArrayList<String> officesHTML = new ArrayList<String>();
while (!cursor.isAfterLast()) {
officesHTML.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return officesHTML;
}
public static ArrayList<String> getPublicJournalsNameSystem() {
Cursor cursor = Database.query("journals",
JournalCOL_NameSystem,"publicFlag like 1", null, null, null, "nameSystem");
cursor.moveToFirst();
ArrayList<String> publicJournalsNameSystem = new ArrayList<String>();
while (!cursor.isAfterLast()) {
publicJournalsNameSystem.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return publicJournalsNameSystem;
}
public static ArrayList<String> getPublicSearchedJournalsNameSystem(String journalName) {
Cursor cursor = Database.query("journals",
JournalCOL_NameSystem,"publicFlag like 1 AND nameSystem like "+journalName, null, null, null, "nameSystem");
cursor.moveToFirst();
ArrayList<String> publicJournalsNameSystem = new ArrayList<String>();
while (!cursor.isAfterLast()) {
publicJournalsNameSystem.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return publicJournalsNameSystem;
}
public static ArrayList<String> getPublicJournalsNameShort() {
Cursor cursor = Database.query("journals",
JournalCOL_NameShort,"publicFlag like 1", null, null, null, "nameShort");
cursor.moveToFirst();
ArrayList<String> publicJournalsNameShort = new ArrayList<String>();
while (!cursor.isAfterLast()) {
publicJournalsNameShort.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return publicJournalsNameShort;
}
public static String getHistoryLastSelectedJournalNameSystem(){
Cursor cursor2 = Database.query("history",
HistoryCOL_LastSelectedJournal,"", null, null, null, null);
cursor2.moveToFirst();
String lastSelectedJournal = null;
lastSelectedJournal = cursor2.getString(0);
cursor2.close();
return lastSelectedJournal;
}
public static Journal_Database getHistoryLastSelectedJournal(String lastSelectedJournalNameSystem){
Cursor cursor = Database.query("journals",
JournalsCOL_All,"nameSystem like "+"'"+lastSelectedJournalNameSystem+"'", null, null, null, null);
cursor.moveToFirst();
Journal_Database lastSelectedJournal = cursorToJournals(cursor);
cursor.moveToNext();
cursor.close();
return lastSelectedJournal;
}
private static Journal_Database cursorToJournals(Cursor cursor) {
Journal_Database journal = new Journal_Database(0, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 0, null, null);
journal.setJournalID(cursor.getInt(0));
journal.setNameFull(cursor.getString(1));
journal.setNameShort(cursor.getString(2));
journal.setNameSystem(cursor.getString(3));
journal.setAbout(cursor.getString(4));
journal.setNameIso4(cursor.getString(5));
journal.setNamePubmed(cursor.getString(6));
journal.setNamePubmedShort(cursor.getString(7));
journal.setISSNElectronic(cursor.getString(8));
journal.setCoden(cursor.getString(9));
journal.setAPCChf(cursor.getString(10));
journal.setAPCCny(cursor.getString(11));
journal.setAPCEngChf(cursor.getString(12));
journal.setAPCEngCny(cursor.getString(13));
journal.setAPCFormatChf(cursor.getString(14));
journal.setSCITracked(cursor.getString(15));
journal.setImpactFactor(cursor.getString(16));
journal.setImpactFactor5years(cursor.getString(17));
journal.setImpactFactorYear(cursor.getString(18));
journal.setEstablishedYear(cursor.getString(19));
journal.setShortDescription(cursor.getString(20));
journal.setAcceptedPapers(cursor.getString(21));
journal.setStyleHeaderLight(cursor.getString(22));
journal.setStyleHeaderDark(cursor.getString(23));
journal.setForthcomingIssue(cursor.getString(24));
journal.setContactEmail(cursor.getString(25));
journal.setContactID(cursor.getString(26));
journal.setPubfrequency(cursor.getString(27));
journal.setPublicFlag(cursor.getInt(28));
journal.setReviewRequestTime(cursor.getString(29));
journal.setDOIAbbreviation(cursor.getString(30));
return journal;
}
}
You need to change the pattern for accessing the database.
Most importantly make a database helper if you don't have it. The main reson for this is having concurrent access to the database for writing. SQLite can'be access for writing from 2 places at the same time. The Database helper takes care of this.
Here is a code sample of a DBHelper that might help you. note that this is for using the ORMLite library database helper but its pretty much the same as a regular helper.
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "database.db";
private static final int DATABASE_VERSION = 6;
private static final AtomicInteger usageCounter = new AtomicInteger(0);
// we do this so there is only one helper
private static DatabaseHelper helper = null;
/**
* Use the {#link #DatabaseHelper(Context, String)}
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
}
#Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
}
#Override
public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource,
}
/**
* Get the helper, possibly constructing it if necessary. For each call to this method, there
* should be 1 and only 1 call to {#link #close()}.
*/
public static synchronized DatabaseHelper getHelper(Context context) {
if (helper == null) {
initHelper(context);
}
usageCounter.incrementAndGet();
return helper;
}
private static void initHelper(Context context) {
helper = new DatabaseHelper(context);
usageCounter.set(0);
}
/**
* Close the database connections and clear any cached DAOs. For each call to
* {#link #getHelper(Context)}, there should be 1 and only 1 call to this method. If there were
* 3 calls to {#link #getHelper(Context)} then on the 3rd call to this method, the helper and
* the underlying database connections will be closed.
*/
#Override
public void close() {
if (usageCounter.decrementAndGet() <= 0) {
super.close();
helper = null;
}
}
}
So this shows how to have a single open database instance and access it.
Each time you want to make some DB operation call the getHelper(context) method and after you are done you must call close. note that for each getHelper method you need to call close.
So a common way of using this would be to get a reference in onCreate of an activity and close it in onDestroy(maybe make an abstract base activity to group this functionality).
Also keep in mind to use it separately in code that might live even after the activity is shut down such as async tasks.
The issue is you forgot to call open() .
You have never called open() function in LocalDatabase

Addressing "Releasing statement in a finalizer. Please ensure that you explicitly call close() on your cursor"

I have two DB clsses, one copies the db file from assets to the phone.
the Second is where I have been putting my DB calls but in the log I am getting an awrful lot error about I should close the cursor. This I am getting confused about as all my calls have a cursor.close() on the end.
Code of second:
public class DatabaseTools extends Common {
private Context context;
private SQLiteDatabase db;
private DatabaseHelper dbHelper;
private Cursor cursor;
public DatabaseTools(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
}
// MARKS
public ArrayList<String> getNames(String value) {
Names = new ArrayList<String>();
selectStatement = new String[] { DB_COMMON_COL_NAME };
fromStatement = DB_COMMON_COL_VALUE + " = '" + value + "'";
cursor = db.query(
DB_DISTANCE_TABLE_NAME,
selectStatement,
fromStatement,
null,
null,
null,
null);
int distanceIndex = cursor.getColumnIndex(DB_COMMON_COL_NAME);
if (cursor.moveToFirst()) {
do {
distanceNames.add(cursor.getString(distanceIndex));
} while (cursor.moveToNext());
}
cursor.close();
return names;
}
Try the following modification to ensure you close your cursor. Also you're getting database instance in your constructor. That's not good. You should get database instance right before you work with the database, and call close() on the database, as soon as you're finished. I would suggest moving db = dbHelper.getWritableDatabase() inside the getNames(String value) method, than calling db.close() when you're done - also in finally block.
public ArrayList<String> getNames(String value) {
Names = new ArrayList<String>();
selectStatement = new String[] { DB_COMMON_COL_NAME };
fromStatement = DB_COMMON_COL_VALUE + " = '" + value + "'";
cursor = db.query(
DB_DISTANCE_TABLE_NAME,
selectStatement,
fromStatement,
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
try {
int distanceIndex = cursor.getColumnIndexOrThrow(DB_COMMON_COL_NAME);
while(cursor.moveToNext()) {
distanceNames.add(cursor.getString(distanceIndex));
}
} finally {
if (!cursor.isClosed()) {
cursor.close();
}
}
return names;
}

Categories

Resources