increase column value if row already exist in Database table - android

I am trying to create a monitoring app where you can track if a student has been absent for more than 3 days and display it as a notification. However, I am stuck on increasing the number of days in which the student has been absent.
What I've done so far:
absent = (Button) findViewById(R.id.btnabsent);
absent.setOnClickListener(new TextView.OnClickListener(){
#Override
public void onClick(View arg0) {
String idstud=stID.getText().toString();
int attID =scoresDataBaseAdapter.getabsAttID(mRowId);
int absoldid=attID-1;
//Adding the data for the very first time
if (attID == 1){
int score =1;
scoresDataBaseAdapter.insertAbsScore(idstud,attID,mRowId,score);
}
//Check if Data already exists
int abcheck = scoresDataBaseAdapter.checkAbs(mRowId, idstud, absoldid);
if (abcheck == 1){
//Getting the Score column from the existing data
int scoreneww = scoresDataBaseAdapter.getabsAttScore(mRowId,idstud,attID);
//Adding value to existing cata
score = score + 1;
scoresDataBaseAdapter.upabsAttScore(mRowId,score, idstud, absoldid);
scoresDataBaseAdapter.insertAbsScore(idstud,attID,mRowId,scoreneww);
}
And heres my code for my database
public void insertAbsScore(String studID,int attIDs, String Sect, int score)
{
String table = "attendance_absences";
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_StudentID, studID);
newValues.put(KEY_ID, attIDs);
newValues.put(KEY_Sec,Sect);
newValues.put(KEY_Score,score);
// Insert the row into your table
mDb.insert(table, null, newValues);
}
public String getAttID(String Sect)
{
String table = Sect+"_attendance";
Cursor cursor=mDb.query(table, null, null, null, null, null, null);
if(cursor.getCount()<1) // UserName does Not Exist
{
cursor.close();
return "DOES NOT EXIST";
}
cursor.moveToLast();
String reset= cursor.getString(cursor.getColumnIndex("_cid"));
cursor.close();
return reset;
}
public int getabsAttID(String Sect)
{
String table = Sect+"_attendance";
Cursor cursor=mDb.query(table, null, null, null, null, null, null);
if(cursor.getCount()<1) // UserName does Not Exist
{
int reset= 0;
cursor.close();
return reset;
}
cursor.moveToLast();
int reset= cursor.getInt(cursor.getColumnIndex("_cid"));
cursor.close();
return reset;
}
public int countAtt(String mRowId)
{
String table= mRowId+"_attendance";
//int sometotal = (int) DatabaseUtils.longForQuery(mDb, "Select _cid from "+ table+", null).getCount();
int numRows = (int) DatabaseUtils.queryNumEntries(mDb, table);
return numRows;
}
public int countPresents(String mRowId, int id)
{
String table= mRowId+"_attendance_scores";
final String DATABASE_COMPARE = "select count(*) from "+table+ " where _id="+id;
int sometotal = (int) DatabaseUtils.longForQuery(mDb, DATABASE_COMPARE, null);
return sometotal;
}
public int checkAbs(String sect, String id, int attid)
{
String q = "SELECT * FROM attendance_absences where _id='"+id+"' and Section ='"+sect+"' and _cid="+attid;
Cursor cursor = mDb.rawQuery(q, null);
int abcheck=0;
if(cursor.getCount()<1) // Absent does Not Exist
{
cursor.close();
abcheck=1;
return abcheck;
}
else
{
cursor.close();
return abcheck;
}
}
public int getabsAttScore(String sect, String id, int attid)
{
//where _id='"+id+"' and Section ='"+sect+"' and _cid="+attid;
String q = "SELECT * FROM attendance_absences where _id='"+id+"' and Section ='"+sect+"' and _cid="+attid;
Cursor cursor = mDb.rawQuery(q, null);
if(cursor.getCount()<1) // Absent does Not Exist
{
int abscore = 0000;
return abscore;
}
cursor.moveToFirst();
int abscore= cursor.getInt(cursor.getColumnIndex("Score"));
return abscore;
}
public void upabsAttScore(String sect, int score, String id, int attid)
{
ContentValues update = new ContentValues();
update.put("Score",score);
mDb.update("attendance_absences", update,/*where clause*/ "_id='"+id+"' and Section ='"+sect+"' and _cid="+attid, null);
}

I found the answer:
absent = (Button) findViewById(R.id.btnabsent);
absent.setOnClickListener(new TextView.OnClickListener(){
#Override
public void onClick(View arg0) {
String idstud=stID.getText().toString();
int attID =scoresDataBaseAdapter.getabsAttID(mRowId);
Toast.makeText(getApplicationContext(), "cid "+attID, Toast.LENGTH_SHORT).show();
int absoldid=attID-1;
if (attID == 1){
int score =1;
scoresDataBaseAdapter.insertAbsScore(idstud,attID,mRowId,score);
}
if (attID > 1){
int abcheck = scoresDataBaseAdapter.checkAbs(mRowId, idstud, absoldid);
Toast.makeText(getApplicationContext(), "2ndcid "+abcheck, Toast.LENGTH_SHORT).show();
if (abcheck == 1){
int score =1;
scoresDataBaseAdapter.insertAbsScore(idstud,attID,mRowId,score);
}
}
Code for updating DB:
public int checkAbs(String sect, String id, int attid)
{
String q = "SELECT * FROM attendance_absences where _id='"+id+"' and Section ='"+sect+"' and _cid="+attid;
Cursor cursor = mDb.rawQuery(q, null);
int abcheck=0;
if(cursor.getCount()<1) // Absent does Not Exist
{
cursor.close();
abcheck=1;
return abcheck;
}
else
{
cursor.moveToFirst();
int abscore= cursor.getInt(cursor.getColumnIndex("Score"));
abscore = abscore +1;
int absattid= cursor.getInt(cursor.getColumnIndex("_cid"));
absattid = absattid +1;
ContentValues values = new ContentValues();
values.put(KEY_Score, abscore);
values.put(KEY_ID, absattid);
mDb.update(AttendanceAbs_TABLE, values," "+KEY_StudentID +" = '" + id+"' AND "+KEY_Sec+" = '"+sect+"' AND "+KEY_ID+" = "+attid, null);
cursor.close();
return abcheck;
}
}

Related

Unable to calculate total price amount in cart using sqlite

I wanted to calculate the total price of the products in the cart using SQLite. When I set the price in textview using Settext(), it does not return the sum value. This is the gettotalprice method in DBhelper class.
public int getTotalExpenses()
{
int total = 0;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT SUM("+ OrderContract.OrderEntry.COLUMN_PRICE + ") FROM " + OrderContract.OrderEntry.TABLE_NAME, null);
if (cursor.moveToFirst())
{
total = cursor.getInt(4);
}
while (cursor.moveToNext());
return total;
}
OrderProvider class:
package com.example.myapp;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class OrderProvider extends ContentProvider {
// this constant is needed in order to define the path of our modification in the table
public static final int ORDER=100;
public DBHelper mhelper;
public static UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(OrderContract.CONTENT_AUTHORITY,OrderContract.PATH,ORDER);
}
#Override
public boolean onCreate() {
mhelper = new DBHelper(getContext());
return true;
}
#Override
public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase database = mhelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch (match){
case ORDER:
cursor = database.query(OrderContract.OrderEntry.TABLE_NAME, projection, selection, selectionArgs, null,null, sortOrder);
break;
default:
throw new IllegalArgumentException("CANT QUERY");
}
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int match = sUriMatcher.match(uri);
switch (match) {
case ORDER:
return insertCart(uri, values);
default:
throw new IllegalArgumentException("Cant insert data");
}
}
private Uri insertCart(Uri uri, ContentValues values) {
String name = values.getAsString(OrderContract.OrderEntry.COLUMN_NAME);
if(name == null){
throw new IllegalArgumentException("Name is Required");
}
String quantity = values.getAsString(OrderContract.OrderEntry.COLUMN_QUANTITY);
if(quantity == null){
throw new IllegalArgumentException("Quantity is Required");
}
String price = values.getAsString(OrderContract.OrderEntry.COLUMN_PRICE);
if(price == null){
throw new IllegalArgumentException("Price is Required");
}
//insert values into order
SQLiteDatabase database = mhelper.getWritableDatabase();
long id = database.insert(OrderContract.OrderEntry.TABLE_NAME, null, values);
if(id == 0){
return null;
}
getContext().getContentResolver().notifyChange(uri,null);
return ContentUris.withAppendedId(uri,id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
//delete data once order is made
int rowsDeleted;
SQLiteDatabase database = mhelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
switch (match) {
case ORDER:
rowsDeleted = database.delete(OrderContract.OrderEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Cannot delete");
}
if (rowsDeleted!=0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
OrderContract class:
public class OrderContract {
public OrderContract() {
}
//content authority requires package name
public static final String CONTENT_AUTHORITY = "com.example.myapp";
public static final Uri BASE_URI = Uri.parse(("content://" +CONTENT_AUTHORITY));
//same as table name
public static final String PATH = "orders" ;
public static abstract class OrderEntry implements BaseColumns{
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI,PATH);
public static final String TABLE_NAME = "orders" ;
public static final String _ID = BaseColumns._ID ;
public static final String COLUMN_NAME = "name" ;
public static final String COLUMN_QUANTITY = "quantity" ;
public static final String COLUMN_PRICE = "price" ;
}
}
Cart activity:
sofaname=findViewById(R.id.sofaname);
sofaprice=findViewById(R.id.sofaprice);
sofadesc=findViewById(R.id.sofadesc);
plusquantity = findViewById(R.id.addquantity);
minusquantity = findViewById(R.id.subquantity);
quantitynumber = findViewById(R.id.quantity);
addtocart = findViewById(R.id.addtocart);
ImageSlider imageSlider = findViewById(R.id.sofaslider1);
List<SlideModel> slideModels = new ArrayList<>();
slideModels.add(new SlideModel(R.drawable.card14));
slideModels.add(new SlideModel(R.drawable.card6));
slideModels.add(new SlideModel(R.drawable.card7));
imageSlider.setImageList(slideModels,false);
imageSlider.setClickable(false);
DB = new DBHelper(Sofa1.this);
String Name = DB.getProductNamePrice("SELECT F_Name FROM Furniture WHERE F_Type = 'Sofa';");
String Price = DB.getProductNamePrice("SELECT F_Price FROM Furniture WHERE F_Type = 'Sofa';");
String Desc = DB.getProductNamePrice("SELECT F_Description FROM Furniture WHERE F_Type = 'Sofa';");
sofaname.setText(Name);
sofaprice.setText(Price);
sofadesc.setText(Desc);
plusquantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(quantity<5){
//sofaprice
int baseprice= Integer.parseInt(sofaprice.getText().toString());
quantity++;
displayquantity();
totalprice = baseprice * quantity;
String setnewprice = (String.valueOf(totalprice));
sofaprice.setText(setnewprice);
}
}
});
minusquantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int baseprice=0;
String Price = DB.getProductNamePrice("SELECT F_Price FROM Furniture WHERE F_Type = 'Sofa';");
baseprice = Integer.parseInt(Price);
if(quantity>1) {
quantity--;
displayquantity();
totalprice = baseprice * quantity;
String setnewprice = (String.valueOf(totalprice));
sofaprice.setText(setnewprice);
}
}
});
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent =new Intent(Sofa1.this,Cart.class);
startActivity(intent);
// once this button is clicked we want to save our values in the database and send those values
// right away to summary activity where we display the order info
SaveCart();
totalamount = (TextView) findViewById(R.id.total);
int totalAmount = DB.getTotalExpenses();
totalamount.setText(String.valueOf(totalAmount));
}
});
}
private boolean SaveCart() {
String name = sofaname.getText().toString();
String price = sofaprice.getText().toString();
String quantity = quantitynumber.getText().toString();
ContentValues values = new ContentValues();
values.put(OrderContract.OrderEntry.COLUMN_NAME,name);
values.put(OrderContract.OrderEntry.COLUMN_PRICE,price);
values.put(OrderContract.OrderEntry.COLUMN_QUANTITY,quantity);
if(mcurrentcarturi == null){
Uri newUri = getContentResolver().insert(OrderContract.OrderEntry.CONTENT_URI, values);
if(newUri == null){
Toast.makeText(this, "Failed to add to cart", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Product added to cart", Toast.LENGTH_SHORT).show();
}
}
hasallrequiredvalues = true;
return hasallrequiredvalues;
}
private void displayquantity() {
quantitynumber.setText(String.valueOf(quantity));
}
#Override
public #NotNull Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {OrderContract.OrderEntry._ID,
OrderContract.OrderEntry.COLUMN_NAME,
OrderContract.OrderEntry.COLUMN_PRICE,
OrderContract.OrderEntry.COLUMN_QUANTITY};
return new CursorLoader(this, mcurrentcarturi, projection, null, null, null);
}
#Override
public void onLoadFinished(#NotNull Loader<Cursor> loader, Cursor cursor) {
if(cursor==null || cursor.getCount() < 1){
return;
}
if(cursor.moveToFirst()){
int name = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_NAME);
int price = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_PRICE);
int quantity = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_QUANTITY);
String nameofsofa = cursor.getString(name);
String priceofsofa = cursor.getString(price);
String quantityofsofa = cursor.getString(quantity);
sofaname.setText(nameofsofa);
sofaprice.setText(priceofsofa);
quantitynumber.setText(quantityofsofa);
}
}
#Override
public void onLoaderReset(#NotNull Loader<Cursor> loader) {
sofaname.setText("");
sofaprice.setText("");
quantitynumber.setText("");
}
As your query is effectively
SELECT SUM(price) FROM orders;
Only a single column will be returned, thus using total = cursor.getInt(4); should result in an exception as the column is out of bounds, there will only be 1 column and it's index will be 0.
Thus try changing to use :-
public int getTotalExpenses()
{
int total = 0;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT SUM("+ OrderContract.OrderEntry.COLUMN_PRICE + ") FROM " + OrderContract.OrderEntry.TABLE_NAME, null);
if (cursor.moveToFirst())
{
total = cursor.getInt(0); //<<<<<<<<<< CHANGED
}
//while (cursor.moveToNext()); //<<<<<<<<<< COMMENTED OUT NOT NEEDED
cursor.close(); //<<<<<<<<<< ADDED should always close cursor when finished with them
return total;
}

retrieving integer values from SQLite database in android

in this app I`m trying give different welcome message to each type of users
so here is the code in my DB helper class
public int loginCheck(String a,String b)
{
int ty;
SQLiteDatabase db=this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM users where user_name = '"+a+"'AND user_password = '"+b+"';", null);
ty= c.getInt(c.getColumnIndex("user_type"));
if (c.getCount()<=0)
{
c.close();
db.close();
return 2;
}
else
c.close();
db.close();
return ty;
}
it should check the user type whether 0 or 1 ,, and according to the return value the welcome message appears,what i got that this retrieves the number of the column , it retrieves 6 and "user_type" is the sixth column
You need to move to the first row first:
public int loginCheck(String a,String b) {
int ty;
SQLiteDatabase db=this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM users where user_name = '"+a+"' AND user_password = '"+b+"';", null);
if (c.moveToFirst()) {
ty = c.getInt(c.getColumnIndex("user_type"));
} else {
ty = 2;
}
c.close();
db.close();
return ty;
}
cursor.moveToFirst will return false if it wasn't able to move to the first row (e.g. the cursor is empty), so no need for the c.getCount() check
=====
The Android way of doing this (not using rawQuery unless have to):
public int loginCheck(String a,String b) {
int ty;
SQLiteDatabase db=this.getWritableDatabase();
Cursor c = db.query("users", new String[] { "user_type" }, "user_name = ? AND user_password = ?", new String[] {a, user_password}, null, null, null);
if (c.moveToFirst()) {
ty = c.getInt(0);
} else {
ty = 2;
}
c.close();
db.close();
return ty;
}

rawquery dynamic where clause condition in android?

I'm new to android and using sqlite rawquery dynamic where clause condition for the first time and didn't know how to use it. I want to give dynamic value to where clause to get the listview according to particular "mid". How to provide the mid value from SubjectActivty
Here is my code:
TestTable:
public long insert(String id, String time, int mid, String cmarks, String nmarks,
String questions, String testType, String test,String marks) {
log("insert test : " + test);
ContentValues values = new ContentValues();
values.put(KEY_TESTID, id);
values.put(KEY_MID,mid);
values.put(KEY_TEST, test);
values.put(KEY_TIME, time);
values.put(KEY_CMARK, cmarks);
values.put(KEY_NMARK, nmarks);
values.put(KEY_TESTTYPE, testType);
values.put(KEY_QUESTION, questions);
values.put(KEY_Total_Marks, marks);
return db.insert(TABLE_NAME2, null, values);
}
public ArrayList<NotificationListItem> getAllList(
ArrayList<NotificationListItem> privateArrayList) {
openToRead();
privateArrayList.clear();
Cursor cursor = null;
String sql ="SELECT * FROm test_list WHERE mid=?";
cursor= db.rawQuery(sql, null);
log("getAlllist() cursor : " + cursor.getCount());
if (cursor != null) {
log("getAlllist() cursor not null ");
int index = 0;
cursor.moveToFirst();
while (index < cursor.getCount()) {
NotificationListItem item = new NotificationListItem();
int idIndex = cursor.getColumnIndex(TestTable.KEY_TESTID);
int subid= cursor.getColumnIndex(TestTable.KEY_MID);
int nameIndex = cursor.getColumnIndex(TestTable.KEY_TEST);
int idTime = cursor.getColumnIndex(TestTable.KEY_TIME);
int cMarks = cursor.getColumnIndex(TestTable.KEY_CMARK);
int nMarks = cursor.getColumnIndex(TestTable.KEY_NMARK);
int testTypeIndex = cursor.getColumnIndex(TestTable.KEY_TESTTYPE);
int questions = cursor.getColumnIndex(TestTable.KEY_QUESTION);
item.name = cursor.getString(nameIndex);
item.testID = cursor.getString(idIndex);
item.mid=cursor.getInt(subid);
item.time = cursor.getString(idTime);
item.cmark = cursor.getString(cMarks);
item.nmark = cursor.getString(nMarks);
item.testType = cursor.getString(testTypeIndex);
item.questions = cursor.getString(questions);
index++;
privateArrayList.add(item);
cursor.moveToNext();
}
log(" query(): cursor closing");
cursor.close();
db.close();
db = null;
}
return privateArrayList;
}
SubjectActvity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject);
privateListLV = (ListView) findViewById(R.id.privateListLV);
privatelistTable = new SubjectTable(SubjectActivity.this);
testTableStatic = new StaticTestTable(this);
testTable = new TestTable(SubjectActivity.this);
privatelistTable.openToWrite();
privatelistTable.deleteAll();
privatelistTable.insert(10, "Biology");
privatelistTable.insert(20, "Chemistry");
privatelistTable.insert(30, "English");
privatelistTable.insert(40, "Maths");
privatelistTable.insert(50, "GK");
testTable.openToWrite();
testTable.deleteAll();
testTable.insert("1", "10", 10, "5", "2", "2", "Both", "Anatomy", "10");
testTable.insert("2", "10", 20, "5", "2", "2", "Both", "Paper1", "10");
privateArrayList = new ArrayList<NotificationListItem>();
listAdapter = new SubjectCustomListAdapter(this, privateArrayList,
privatelistTable);
privateListLV.setAdapter(listAdapter);
privateListLV.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long arg3) {
NotificationListItem selection = (NotificationListItem) adapter
.getItemAtPosition(position);
String item = selection.getName();
System.out.println("item" +item);
if (!item.contentEquals(" ")) {
subjectid = privatelistTable.getSinlgeEntry(item);
Log.e("selected Value", " " + subjectid);
Intent testact = new Intent(getApplicationContext(),
TestsActivity.class);
testact.putExtra("subject", item);
testact.putExtra("mid",subjectid);
startActivity(testact);
} else {
return;
}
}
});
}
#Override
protected void onResume() {
super.onResume();
updateList();
}
private void updateList() {
privatelistTable.getAllList(privateArrayList);
listAdapter.notifyDataSetChanged();
}
Do as #Der Golem answer OR another way is
Cursor c =db.rawQuery("SELECT * FROM " + tableName + " where mid=" + mid , null);

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

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

Getting the next record into view from database

I have two buttons inside of my application, one for next and one for prev. I want the next button to get the next record inside of my database and display it inside of my view, and the prev button to get the previous record and display it inside of my view. How would I call the next or previous record? I have looked for tutorials and stuff but didn't find any. I anyone has a tutorial please share with me. Thanks for any help. I wish I had some code to provide but I really don't know where to start.
I use an int to pull the record from the dbase.
From my ContactView class
static long record = 1;
public void getData() {
DBase db = new DBase(this);
db.open();
lastRecord = db.lRec();
firstRecord = db.fRec();
rRec = db.getRec(record);
db.close();
}
then my query is from my Dbase class
public String[] getRec(long record) {
record = ContactView.record;
String[] columns = new String[] { KEY_ROWID, KEY_ONE, KEY_TWO,
KEY_THREE, KEY_FOUR, KEY_FIVE, KEY_SIX };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ record, null, null, null, null);
if (c != null && c.moveToFirst()) {
String rRec = c.getString(0);
String rOne = c.getString(1);
String rTwo = c.getString(2);
String rThree = c.getString(3);
String rFour = c.getString(4);
String rFive = c.getString(5);
String rSix = c.getString(6);
String[] rData = { rRec, rOne, rTwo, rThree, rFour,
rFive, rSix };
return rData;
}
return null;
}
and the next few are from my ContactView class
my buttons
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLvPrev:
recordMinus();
display();
break;
case R.id.bSQLvNext:
recordPlus();
display();
break;
}
}
and the methods they call
public void display() {
etSQLvRec.setText(rRec[0]);
etSQLvOne.setText(rRec[1]);
etSQLvTwo.setText(rRec[2]);
etSQLvThree.setText(rRec[3]);
etSQLvFour.setText(rRec[4]);
etSQLvFive.setText(rRec[5]);
etSQLvSix.setText(rRec[6]);
}
public void recordPlus() {
record++;
}
public void recordMinus() {
record--;
}
That will get the record from the database based on the "record" variable, and the buttons increment it, or decrement it, it also skips any "empty" records.
EDIT OK, I had changed some stuff around since I lasted used my db, so use the next recordPlus() and recordMinus() code instead
public void recordPlus() {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
do {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
} while (rRec == null);
}
public void recordMinus() {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
do {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
} while (rRec == null);
}
And you'll need my fRec() and lRec() which find the first and last records in the DB
public long fRec() {
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "min(" +
KEY_ROWID
+ ")" }, null, null, null, null, null);
c.moveToFirst();
long rowID = c.getInt(0);
return rowID;
}
}
public long lRec() {
long lastRec = 0;
String query = "SELECT ROWID from Table order by ROWID DESC limit 1";
Cursor c = ourDatabase.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
lastRec = c.getLong(0);
}
return lastRec;
}

Categories

Resources