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

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

Related

android.content.Context.getContentResolver()' on a null object reference

I can't seem work out why I am getting a null pointer on this?
This is my AsyncTask that I call to grab the data. It passes it to a JSON Parser and an array of Objects is returned. This is then passed to my DBHelper where it was passing to my database through a ContentResolver....
public class getFilms extends AsyncTask<String, Void, Void> {
public int LIMIT_FILMS = 10;
String KEY = "apikey";
String LIMIT = "limit";
private static final String URL = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?";
private static final String API_KEY = "******************";
ArrayList<HashMap<String, String>> filmArrayList = new ArrayList<HashMap<String, String>>();
Context mContext;
#Override
protected Void doInBackground(String... params) {
Uri RottenUrl = Uri.parse(URL).buildUpon()
.appendQueryParameter(KEY, API_KEY)
.appendQueryParameter(LIMIT, Integer.toString(LIMIT_FILMS))
.build();
JSONParser jParser = new JSONParser();
Film[] json = jParser.getJSONFromUrl(RottenUrl.toString());
sortData(json);
return null;
}
public void sortData(Film[] jsonlist) {
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
dbHelper.deleteAll();
for (int i = 0; i < jsonlist.length; i++) {
dbHelper.contentAddFilm(jsonlist[i]);
}
}
}
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private ContentResolver myCR;
public DatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, FilmDataContract.DATABASE_NAME, factory, FilmDataContract.DATABASE_VERSION);
myCR = context.getContentResolver();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(FilmDataContract.FilmEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(FilmDataContract.FilmEntry.DELETE_TABLE);
onCreate(db);
}
public void addFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(FilmDataContract.TABLE_NAME,
null,
values);
db.close();
}
public Film getFilm(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(FilmDataContract.TABLE_NAME,
FilmDataContract.FilmEntry.COLUMNS,
"_id = ?",
new String[]{String.valueOf(id)},
null,
null,
null,
null);
if (cursor != null)
cursor.moveToFirst();
Film film = new Film();
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
return film;
}
public List<Film> getAllFilms() {
List<Film> films = new LinkedList<Film>();
String query = "SELECT * FROM " + FilmDataContract.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Film film = null;
if (cursor.moveToFirst()) {
do {
film = new Film();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
films.add(film);
} while (cursor.moveToNext());
}
return films;
}
public int updateFilm(Film film) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
int i = db.update(FilmDataContract.FilmEntry.TABLE_NAME,
values,
"_id+ = ?",
new String[]{String.valueOf(film.getId())});
db.close();
return i;
}
public int getFilmsCount() {
String countQuery = "SELECT * FROM " + FilmDataContract.FilmEntry.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void deleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(FilmDataContract.FilmEntry.TABLE_NAME, null, null);
}
public boolean contentDelete(String filmName) {
boolean result = false;
String selection = "title = \"" + filmName + "\"";
int rowsDeleted = myCR.delete(FilmProvider.CONTENT_URI,
selection, null);
if (rowsDeleted > 0)
result = true;
return result;
}
public Film contentFindFilm(String filmName) {
String[] projection = FilmDataContract.FilmEntry.COLUMNS;
String selection = "title = \"" + filmName + "\"";
Cursor cursor = myCR.query(FilmProvider.CONTENT_URI,
projection, selection, null,
null);
Film film = new Film();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
cursor.close();
} else {
film = null;
}
return film;
}
public void contentAddFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
myCR.insert(FilmProvider.CONTENT_URI, values);
}
This is my stack trace... Seems to be happening when I am passing the context.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
at com.purewowstudio.topmovies.data.DatabaseHelper.<init>(DatabaseHelper.java:25)
at com.purewowstudio.topmovies.util.getFilms.sortData(getFilms.java:48)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:43)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:16)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
mContext is null, because you never assign a value to it.

Display sqlite data on listview

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.

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"

update two tables on click inside a listview and passing parameters for the update

Goodyear to everyone.
well, this is the question, i would like to understand the logic of the listview, and how to retrieve informations on the item clicked in it.
i have done and customized a bunch of tutorials to do this app, and now i'm trying to figure out what i'm doing in this ugly and dirty code.
i have a activity where it lists a series of questions, after you select a category, selecting a question, brings you to the next activity, where some answers are listed and the user could select one. I would like to list ONLY those questions that the user has to answer, instead of all, so i've added a new column to the categories table called "fatta" - "done" in english that i would like to change to 1 when the user clicks the answer of that question.
so the idea was to pass the id of the question, so in the activity where i list al the answers, i could update both the answers and the questions tables, to set to 1 the "done field".
but something goes wrong. here's the code:
The Activity:
public class sondaggioActivity extends ListActivity{
private static final String strdomanda = null;
private pollDataSource datasource;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maindomanda);
long domanda = getIntent().getExtras().getLong("domanda");
TextView text = (TextView) findViewById(R.id.domanda);
String strdomanda = Long.toString(domanda);
// text.setText(strcategory);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getTestoRisposte(strdomanda);
// data? if (values.moveToFirst())
// System.out.println(values.getString(values.getColumnIndex("sondid")));
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_RISPOSTA // Contract class constant containing the word column name
};
int[] mWordListItems = { R.id.categoria_label };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
//values.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
datasource.setRispostaSelezionata(Long.toString(id));
datasource.setDomandaFatta(strdomanda);
datasource.close();
finish();
}
}
as you can see here at the end there is the onListItemClick where i use the strdomanda that i have defined at the top as private static final String strdomanda = null; the datasource is like this:
public class pollDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };
private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_CATID,MySQLiteHelper.COLUMN_WEBID,MySQLiteHelper.COLUMN_FATTA, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID,MySQLiteHelper.COLUMN_WEBID, MySQLiteHelper.COLUMN_RISPOSTA,
MySQLiteHelper.COLUMN_SELEZIONATA };
public pollDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
public void deleteCategoria(categorie categoria) {
long id = categoria.getId();
System.out.println("Categoria cancellata, id: " + id);
database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public sondaggi createSondaggio(String domanda, int catid, int webid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
values.put(MySQLiteHelper.COLUMN_WEBID, webid);
values.put(MySQLiteHelper.COLUMN_FATTA, "0");
long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
sondaggi newSondaggio = cursorToSondaggi(cursor);
cursor.close();
return newSondaggio;
}
public void deleteSondaggio(sondaggi sondaggio) {
long id = sondaggio.getId();
System.out.println("Sondaggio cancellato, id: " + id);
database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public Cursor getAllCategorie() {
List<categorie> categorie = new ArrayList<categorie>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
categorie categoria = cursorToCategorie(cursor);
categorie.add(categoria);
cursor.moveToNext();
}
// Make sure to close the cursor
// cursor.close();
return cursor;
}
public Cursor getDomanda(String id) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_ID + "=?",
new String[] { id }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
private categorie cursorToCategorie(Cursor cursor) {
categorie categorie = new categorie();
categorie.setId(cursor.getLong(0));
categorie.setPreferita(cursor.getLong(1));
categorie.setNome(cursor.getString(2));
return categorie;
}
private sondaggi cursorToSondaggi(Cursor cursor) {
sondaggi sondaggi = new sondaggi();
sondaggi.setId(cursor.getLong(0));
sondaggi.setDomanda(cursor.getString(1));
sondaggi.setCatid(cursor.getLong(2));
sondaggi.setwebid(cursor.getLong(3));
return sondaggi;
}
public Cursor getAllDomandeCategoria(String catid) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_CATID + "=?",
new String[] { catid }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
public Cursor getTestoRisposte(String strdomanda) {
List<testo_risposte> domande = new ArrayList<testo_risposte>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_TESTORISPOSTE,
allRisposteColumns,
MySQLiteHelper.COLUMN_SONDID + "=?",
new String[] { strdomanda }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
testo_risposte sondaggio = cursorToTestoRisposte(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
private testo_risposte cursorToTestoRisposte(Cursor cursor) {
testo_risposte testo_risposte = new testo_risposte();
testo_risposte.setId(cursor.getLong(0));
testo_risposte.setCatid(cursor.getLong(1));
testo_risposte.setWebid(cursor.getLong(4));
testo_risposte.Setselezionata(cursor.getLong(2));
testo_risposte.setDomanda(cursor.getString(3));
return testo_risposte;
}
public void setRispostaSelezionata(String id) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_SELEZIONATA, "1");
database.update(MySQLiteHelper.TABLE_TESTORISPOSTE,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { id });
}
public void setDomandaFatta(String strdomanda) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_FATTA, "1");
database.update(MySQLiteHelper.TABLE_SONDAGGI,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { strdomanda });
}
}
but as i run the activity, only the first updadate gone good, the other one, the one with which i would like to "deactivate" the question... does nothing... i suppose that the way i pass the strdomanda is not the good way. Any help? Advice? thanks in advance.
SOLVED:
i have mistaken this line:
private static String strdomanda = null;
I have deleted the Final property and i have deleted the other declaration of the same variable...
now it works.

How to find the maximum value of the column in sqlite database

public Cursor getBiggestInTheColumn()
{
return db.query(HEADER_TABLE, null,"MAX(key_Division)", null, null, null, null);
}
and I call this method as Cursor cc=db.getBiggestInTheColumn();
But it forcefully close the application.Please help me
You can use simpleQueryForLong and cast it accordingly.
public int getMaxColumnData() {
mDb = mDbManager.getReadableDatabase();
final SQLiteStatement stmt = mDb
.compileStatement("SELECT MAX(column) FROM Table");
return (int) stmt.simpleQueryForLong();
}
public int getBiggestInTheColumn()
{
Cursor c = db.query(HEADER_TABLE, null,new String[] {"MAX(key_Division)"}, null, null, null, null);
try {
c.moveToFirst();
return c.getInt(0);
} finally {
c.close();
}
}

Categories

Resources