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.
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"
I have got these issue, but can not get solutation
Launch timeout has expired, giving up wake lock!
Activity idle timeout for HistoryRecord{44e26a30 com.india.screen/.CategoryList}
This problem get after adding these lines ( String numOfRows="select count(*) from Holyplace_Tbl where State_id='"+stateId+"'";) console nothing print after it
Activity
public class CategoryList extends Activity{
private TableRow holyPlaces,historicalPalces,beach,museum,hills,lakes;
private int stateId;
private AssetDatabaseOpenHelper assetDatabaseHelper;
private Cursor holyplacesCursor,rowsCursor;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.category_screen);
Bundle extras = getIntent().getExtras();
if (extras != null) {
stateId=extras.getInt("stateid");
System.out.println("stateid"+stateId);
}
holyPlaces=(TableRow) findViewById(R.id.holyPlaces);
historicalPalces=(TableRow) findViewById(R.id.historicalPlaces);
museum=(TableRow) findViewById(R.id.museum);
beach=(TableRow) findViewById(R.id.beach);
hills=(TableRow) findViewById(R.id.hills);
lakes=(TableRow) findViewById(R.id.lakes);
assetDatabaseHelper=new AssetDatabaseOpenHelper(CategoryList.this);
assetDatabaseHelper.openDatabase();
assetDatabaseHelper.openReadableMode();
System.out.println("success.....!");
String numOfRows="select count(*) from Holyplace_Tbl where State_id='"+stateId+"'";
System.out.println("rav "+numOfRows);
rowsCursor=assetDatabaseHelper.executeQuery(numOfRows);
System.out.println("hjkdfhfh .............................."+rowsCursor);
System.out.println("hj hi .............................."+rowsCursor);
if(rowsCursor.moveToFirst())
{
System.out.println("hi.........."+rowsCursor.getColumnCount());
do{
int count=rowsCursor.getInt(0);
System.out.println("cu "+count);
System.out.println("cursor.. "+rowsCursor.getCount());
System.out.println("ccccc "+rowsCursor.getInt(0));
System.out.println("jdjhfhf "+rowsCursor.getColumnCount());
}while(rowsCursor.moveToNext());
}
else{
System.out.println("cursor not move");
}
rowsCursor.close();
assetDatabaseHelper.close();
System.out.println("no next value");
}
}
AssetDatabaseOpenHelper.class
public class AssetDatabaseOpenHelper {
private Context context;
private SQLiteDatabase sqliteDatabaseObj;
private String database_name;
private CreateQueries createQueriesObj;
private MySQLiteHelper mySQLitehelperObj;
private int database_version;
private String databaseName="TravelguideDb";
private int databaseVersion=3;
public AssetDatabaseOpenHelper(Context context,String databaseName,int database_version) {
this.context = context;
this.database_name=databaseName;
this.database_version=database_version;
}
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
this.database_name = databaseName;
this.database_version = databaseVersion;
}
public void openDatabase() {
mySQLitehelperObj = new MySQLiteHelper(context, database_name,
database_version);
File dbFile = context.getDatabasePath(database_name);
System.out.println("Assests"+dbFile.exists());
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
}
public void openReadableMode()
{
sqliteDatabaseObj = mySQLitehelperObj.getReadableDatabase();
}
public void openWriteableMode()
{
sqliteDatabaseObj = mySQLitehelperObj.getWritableDatabase();
}
public void close() {
mySQLitehelperObj.close();
}
private void copyDatabase(File dbFile) throws IOException {
OutputStream os = new FileOutputStream(dbFile);
InputStream is = null;
byte[] buffer = new byte[1024];
for(int i=1;i<5;i++)
{
is = context.getAssets().open("TravelguideDb.sqlite.00"+1);
int length;
while ((length=is.read(buffer))!=-1) {
os.write(buffer,0,length);
}
is.close();
}
os.flush();
os.close();
is.close();
}
public Cursor executeQuery(String query)
{
Cursor outputCursor= sqliteDatabaseObj.rawQuery(query, null);
return outputCursor;
}
public void createTable(String tableName, String[] columns, String[] value) {
createQueriesObj = new CreateQueries();
String createTableQuery = createQueriesObj.CreateTableQuery(tableName,
columns, value);
sqliteDatabaseObj.execSQL(createTableQuery);
System.out.println("Query" + createTableQuery);
}
public void deleteTable(String tableName)
{
sqliteDatabaseObj.execSQL("Drop table " + tableName);
}
public void deleteAllDataFromTable(String tableName) {
// truncate table
sqliteDatabaseObj.delete(tableName, null, null);
}
public void deletePerticularRows(String tableName, String whereClause,
String[] whereArgs) {
sqliteDatabaseObj.delete(tableName, whereClause, whereArgs);
}
public Cursor fetchAllRows(String tableName) {
return sqliteDatabaseObj.query(tableName, null, null, null, null, null,
null);
}
public Cursor selectOnWhereCondition(String tableName,
String[] columnsToSelect, String whereColumnName,
String[] whereEqualsTo, String groupBy, String having,
String orderBy) {
return sqliteDatabaseObj.query(tableName, columnsToSelect,
whereColumnName, whereEqualsTo, groupBy, having, orderBy);
}
public void updateRows(String tableName, String[] columnNames,
String[] values, String whereClause, String[] whereArgs)
throws SQLException {
if (columnNames.length != values.length) {
throw new SQLException();
}
ContentValues contentValue = new ContentValues();
int length = values.length;
for (int i = 0; i < length; i++) {
contentValue.put(columnNames[i], values[i]);
}
sqliteDatabaseObj.update(tableName, contentValue, whereClause,
whereArgs);
}
public long addRecords(String TableName, String[] columnNames,
String[] values) throws SQLException {
long result = 0;
if (columnNames.length != values.length) {
throw new SQLException();
} else {
ContentValues contentValues = new ContentValues();
int length = columnNames.length;
for (int i = 0; i < length; i++) {
contentValues.put(columnNames[i], values[i]);
}
result = sqliteDatabaseObj.insert(TableName, null, contentValues);
}
return result;
}
}
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